jiebi/CodeConvo huggingface dataset:
creationTimestamp: null labels: kubernetes.io/bootstrapping: rbac-defaults <del> name: system:csi-external-attacher rules: - apiGroups: - "" resources: - persistentvolumes verbs: - get - list - patch - update - watch - apiGroups: - "" resources: - nodes verbs: - get - list - watch - apiGroups: - storage.k8s.io resources: - volumeattachments verbs: - get - list - patch - update - watch - apiGroups: - "" resources: - events verbs: - create - get - list - patch - update - watch - apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: annotations: rbac.authorization.kubernetes.io/autoupdate: "true" creationTimestamp: null labels: kubernetes.io/bootstrapping: rbac-defaults name: system:csi-external-provisioner rules: - apiGroups: - "" resources: - persistentvolumes verbs: - create - delete - get - list - watch - apiGroups: - "" resources: - persistentvolumeclaims verbs: - get - list - patch - update - watch - apiGroups: - storage.k8s.io resources: - storageclasses verbs: - list - watch - apiGroups: - "" resources: - events verbs: - create - get - list - patch - update - watch - apiGroups: - "" resources: - nodes verbs: - get - list - watch - apiGroups: - storage.k8s.io resources: - csinodes verbs: - get - list - watch - apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: annotations: rbac.authorization.kubernetes.io/autoupdate: "true" creationTimestamp: null labels: kubernetes.io/bootstrapping: rbac-defaults </del> name: system:discovery rules: - nonResourceURLs:
cgroupRoots = append(cgroupRoots, cm.NodeAllocatableRoot(s.CgroupRoot, s.CgroupDriver)) kubeletCgroup, err := cm.GetKubeletContainer(s.KubeletCgroups) if err != nil { <del> return fmt.Errorf("failed to get the kubelet's cgroup: %v", err) } if kubeletCgroup != "" { </del> <ins> klog.Warningf("failed to get the kubelet's cgroup: %v.  Kubelet system container metrics may be missing.", err) } else if kubeletCgroup != "" { </ins> cgroupRoots = append(cgroupRoots, kubeletCgroup) } runtimeCgroup, err := cm.GetRuntimeContainer(s.ContainerRuntime, s.RuntimeCgroups) if err != nil { <del> return fmt.Errorf("failed to get the container runtime's cgroup: %v", err) } if runtimeCgroup != "" { </del> <ins> klog.Warningf("failed to get the container runtime's cgroup: %v. Runtime system container metrics may be missing.", err) } else if runtimeCgroup != "" { </ins> // RuntimeCgroups is optional, so ignore if it isn't specified cgroupRoots = append(cgroupRoots, runtimeCgroup) }
}, []string{"runtime_handler"}, ) <ins> // RunningPodCount is a gauge that tracks the number of Pods currently running RunningPodCount = metrics.NewGauge( &metrics.GaugeOpts{ Subsystem:      KubeletSubsystem, Name:           "running_pod_count", Help:           "Number of pods currently running", StabilityLevel: metrics.ALPHA, }, ) // RunningContainerCount is a gauge that tracks the number of containers currently running RunningContainerCount = metrics.NewGaugeVec( &metrics.GaugeOpts{ Subsystem:      KubeletSubsystem, Name:           "running_container_count", Help:           "Number of containers currently running", StabilityLevel: metrics.ALPHA, }, []string{"container_state"}, ) </ins> ) var registerMetrics sync.Once
legacyregistry.MustRegister(CgroupManagerDuration) legacyregistry.MustRegister(PodWorkerStartDuration) legacyregistry.MustRegister(ContainersPerPodCount) <del> legacyregistry.RawMustRegister(newPodAndContainerCollector(containerCache)) </del> legacyregistry.MustRegister(PLEGRelistDuration) legacyregistry.MustRegister(PLEGDiscardEvents) legacyregistry.MustRegister(PLEGRelistInterval)
legacyregistry.MustRegister(DeprecatedEvictionStatsAge) legacyregistry.MustRegister(DeprecatedDevicePluginRegistrationCount) legacyregistry.MustRegister(DeprecatedDevicePluginAllocationLatency) <ins> legacyregistry.MustRegister(RunningContainerCount) legacyregistry.MustRegister(RunningPodCount) </ins> if utilfeature.DefaultFeatureGate.Enabled(features.DynamicKubeletConfig) { legacyregistry.MustRegister(AssignedConfig) legacyregistry.MustRegister(ActiveConfig)
return time.Since(start).Seconds() } <del> func newPodAndContainerCollector(containerCache kubecontainer.RuntimeCache) *podAndContainerCollector { return &podAndContainerCollector{ containerCache: containerCache, } } // Custom collector for current pod and container counts. type podAndContainerCollector struct { // Cache for accessing information about running containers. containerCache kubecontainer.RuntimeCache } // TODO(vmarmol): Split by source? var ( runningPodCountDesc = prometheus.NewDesc( prometheus.BuildFQName("", KubeletSubsystem, "running_pod_count"), "Number of pods currently running", nil, nil) runningContainerCountDesc = prometheus.NewDesc( prometheus.BuildFQName("", KubeletSubsystem, "running_container_count"), "Number of containers currently running", nil, nil) ) // Describe implements Prometheus' Describe method from the Collector interface. It sends all // available descriptions to the provided channel and retunrs once the last description has been sent. func (pc *podAndContainerCollector) Describe(ch chan<- *prometheus.Desc) { ch <- runningPodCountDesc ch <- runningContainerCountDesc } // Collect implements Prometheus' Collect method from the Collector interface. It's called by the Prometheus // registry when collecting metrics. func (pc *podAndContainerCollector) Collect(ch chan<- prometheus.Metric) { runningPods, err := pc.containerCache.GetPods() if err != nil { klog.Warningf("Failed to get running container information while collecting metrics: %v", err) return } runningContainers := 0 for _, p := range runningPods { runningContainers += len(p.Containers) } ch <- prometheus.MustNewConstMetric( runningPodCountDesc, prometheus.GaugeValue, float64(len(runningPods))) ch <- prometheus.MustNewConstMetric( runningContainerCountDesc, prometheus.GaugeValue, float64(runningContainers)) } </del> const configMapAPIPathFmt = "/api/v1/namespaces/%s/configmaps/%s" func configLabels(source *corev1.NodeConfigSource) (map[string]string, error) {
deps = [ "//pkg/kubelet/container:go_default_library", "//pkg/kubelet/container/testing:go_default_library", <ins> "//pkg/kubelet/metrics:go_default_library", </ins> "//staging/src/k8s.io/apimachinery/pkg/types:go_default_library", "//staging/src/k8s.io/apimachinery/pkg/util/clock:go_default_library", "//staging/src/k8s.io/apimachinery/pkg/util/diff:go_default_library", <ins> "//vendor/github.com/prometheus/client_model/go:go_default_library", </ins> "//vendor/github.com/stretchr/testify/assert:go_default_library", ], )
return state } <ins> func updateRunningPodAndContainerMetrics(pods []*kubecontainer.Pod) { // Set the number of running pods in the parameter metrics.RunningPodCount.Set(float64(len(pods))) // intermediate map to store the count of each "container_state" containerStateCount := make(map[string]int) for _, pod := range pods { containers := pod.Containers for _, container := range containers { // update the corresponding "container_state" in map to set value for the gaugeVec metrics containerStateCount[string(container.State)]++ } } for key, value := range containerStateCount { metrics.RunningContainerCount.WithLabelValues(key).Set(float64(value)) } } </ins> func (pr podRecords) getOld(id types.UID) *kubecontainer.Pod { r, ok := pr[id] if !ok {
"testing" "time" <ins> dto "github.com/prometheus/client_model/go" </ins> "github.com/stretchr/testify/assert" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/clock" "k8s.io/apimachinery/pkg/util/diff" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" containertest "k8s.io/kubernetes/pkg/kubelet/container/testing" <ins> "k8s.io/kubernetes/pkg/kubelet/metrics" </ins> ) const (
assert.Exactly(t, []*PodLifecycleEvent{event}, actualEvents) } } <ins> func TestRunningPodAndContainerCount(t *testing.T) { fakeRuntime := &containertest.FakeRuntime{} runtimeCache, _ := kubecontainer.NewRuntimeCache(fakeRuntime) metrics.Register(runtimeCache) testPleg := newTestGenericPLEG() pleg, runtime := testPleg.pleg, testPleg.runtime runtime.AllPodList = []*containertest.FakePod{ {Pod: &kubecontainer.Pod{ ID: "1234", Containers: []*kubecontainer.Container{ createTestContainer("c1", kubecontainer.ContainerStateRunning), createTestContainer("c2", kubecontainer.ContainerStateUnknown), createTestContainer("c3", kubecontainer.ContainerStateUnknown), }, }}, {Pod: &kubecontainer.Pod{ ID: "4567", Containers: []*kubecontainer.Container{ createTestContainer("c1", kubecontainer.ContainerStateExited), }, }}, } pleg.relist() // assert for container count with label "running" actualMetricRunningContainerCount := &dto.Metric{} expectedMetricRunningContainerCount := float64(1) metrics.RunningContainerCount.WithLabelValues(string(kubecontainer.ContainerStateRunning)).Write(actualMetricRunningContainerCount) assert.Equal(t, expectedMetricRunningContainerCount, actualMetricRunningContainerCount.GetGauge().GetValue()) // assert for container count with label "unknown" actualMetricUnknownContainerCount := &dto.Metric{} expectedMetricUnknownContainerCount := float64(2) metrics.RunningContainerCount.WithLabelValues(string(kubecontainer.ContainerStateUnknown)).Write(actualMetricUnknownContainerCount) assert.Equal(t, expectedMetricUnknownContainerCount, actualMetricUnknownContainerCount.GetGauge().GetValue()) // assert for running pod count actualMetricRunningPodCount := &dto.Metric{} metrics.RunningPodCount.Write(actualMetricRunningPodCount) expectedMetricRunningPodCount := float64(2) assert.Equal(t, expectedMetricRunningPodCount, actualMetricRunningPodCount.GetGauge().GetValue()) } </ins>
) const regexDescribe = "Describe|KubeDescribe|SIGDescribe" <del> const regexContext = "Context" </del> <ins> const regexContext = "^Context$" </ins> type visitor struct { <del> FileSet      *token.FileSet lastDescribe describe cMap         ast.CommentMap </del> <ins> FileSet   *token.FileSet describes []describe cMap      ast.CommentMap </ins> //list of all the conformance tests in the path tests []conformanceData } //describe contains text associated with ginkgo describe container type describe struct { <ins> rparen      token.Pos </ins> text        string lastContext context }
} func (v *visitor) getDescription(value string) string { <del> if len(v.lastDescribe.lastContext.text) > 0 { return strings.Trim(v.lastDescribe.text, """) + " " + strings.Trim(v.lastDescribe.lastContext.text, """) + " " + strings.Trim(value, """) </del> <ins> tokens := []string{} for _, describe := range v.describes { tokens = append(tokens, describe.text) if len(describe.lastContext.text) > 0 { tokens = append(tokens, describe.lastContext.text) } } tokens = append(tokens, value) trimmed := []string{} for _, token := range tokens { trimmed = append(trimmed, strings.Trim(token, """)) </ins> } <del> return strings.Trim(v.lastDescribe.text, """) + " " + strings.Trim(value, """) </del> <ins> return strings.Join(trimmed, " ") </ins> } var (
// It() with a manually embedded [Conformance] tag, which it will complain // about. func (v *visitor) Visit(node ast.Node) (w ast.Visitor) { <ins> lastDescribe := len(v.describes) - 1 </ins> switch t := node.(type) { case *ast.CallExpr: if name := v.matchFuncName(t, regexDescribe); name != "" && len(t.Args) >= 2 { <del> v.lastDescribe = describe{text: name} </del> <ins> v.describes = append(v.describes, describe{text: name, rparen: t.Rparen}) </ins> } else if name := v.matchFuncName(t, regexContext); name != "" && len(t.Args) >= 2 { <del> v.lastDescribe.lastContext = context{text: name} </del> <ins> if lastDescribe > -1 { v.describes[lastDescribe].lastContext = context{text: name} } </ins> } else if v.isConformanceCall(t) { totalConfTests++ v.emit(t.Args[0])
Description: `By default the stdout and stderr from the process being executed in a pod MUST be sent to the pod's logs.` + "nn"}}, }, <ins> // SIGDescribe + KubeDescribe + It, Describe + KubeDescribe + It {"e2e/foo.go", ` var _ = framework.SIGDescribe("Feature", func() { KubeDescribe("Described by", func() { // Description: description1 framework.ConformanceIt("A ConformanceIt", func() {}) }) Describe("Also described via", func() { KubeDescribe("A nested", func() { // Description: description2 framework.ConformanceIt("ConformanceIt", func() {}) }) }) })`, []conformanceData{ {URL: "https://github.com/kubernetes/kubernetes/tree/master/e2e/foo.go#L6", TestName: "Feature Described by A ConformanceIt", Description: "description1nn"}, {URL: "https://github.com/kubernetes/kubernetes/tree/master/e2e/foo.go#L11", TestName: "Feature Also described via A nested ConformanceIt", Description: "description2nn"}, }}, </ins> // KubeDescribe + Context + It {"e2e/foo.go", ` var _ = framework.KubeDescribe("Feature", func() {
// TODO (vladimirvivien) would be nice to name socket with a .sock extension // for consistency. csiAddrTemplate = "/var/lib/kubelet/plugins/%v/csi.sock" <del> csiTimeout      = 15 * time.Second </del> <ins> csiTimeout      = 2 * time.Minute </ins> volNameSep      = "^" volDataFileName = "vol_data.json" fsTypeBlockName = "block"
export DOCKER_CLI_EXPERIMENTAL := enabled # golang version should match the golang version from https://github.com/coreos/etcd/releases for the current ETCD_VERSION. GOLANG_VERSION?=1.10.4 <del> GOARM=7 </del> <ins> GOARM?=7 </ins> TEMP_DIR:=$(shell mktemp -d) ifeq ($(ARCH),amd64)
# Download etcd in a golang container and cross-compile it statically # For each release create a tmp dir 'etcd_release_tmp_dir' and unpack the release tar there. <ins> arch_prefix="" ifeq ($(ARCH),arm) arch_prefix="GOARM=$(GOARM)" endif </ins> for version in $(BUNDLED_ETCD_VERSIONS); do  etcd_release_tmp_dir=$(shell mktemp -d);  docker run --interactive -v $${etcd_release_tmp_dir}:/etcdbin golang:$(GOLANG_VERSION) /bin/bash -c  "git clone https://github.com/coreos/etcd /go/src/github.com/coreos/etcd  && cd /go/src/github.com/coreos/etcd  && git checkout v$${version}  <del> && GOARM=$(GOARM) GOARCH=$(ARCH) ./build  </del> <ins> && $(arch_prefix) GOARCH=$(ARCH) ./build  </ins> && cp -f bin/$(ARCH)/etcd* bin/etcd* /etcdbin; echo 'done'";  cp $$etcd_release_tmp_dir/etcd $$etcd_release_tmp_dir/etcdctl $(TEMP_DIR)/;  cp $(TEMP_DIR)/etcd $(TEMP_DIR)/etcd-$$version;
if [[ $(id -u) != 0 ]]; then sudo=sudo fi <del> "${sudo}" "${KUBE_ROOT}/third_party/multiarch/qemu-user-static/register/register.sh" --reset </del> <ins> ${sudo} "${KUBE_ROOT}/third_party/multiarch/qemu-user-static/register/register.sh" --reset </ins> curl -sSL https://github.com/multiarch/qemu-user-static/releases/download/"${QEMUVERSION}"/x86_64_qemu-"${QEMUARCHS[$arch]}"-static.tar.gz | tar -xz -C "${temp_dir}" # Ensure we don't get surprised by umask settings chmod 0755 "${temp_dir}/qemu-${QEMUARCHS[$arch]}-static"
# This function is for building the go code bin() { <ins> local arch_prefix="" if [[ "${ARCH}" == "arm" ]]; then arch_prefix="GOARM=${GOARM:-7}" fi </ins> for SRC in $@; do docker run --rm -it -v "${TARGET}:${TARGET}:Z" -v "${KUBE_ROOT}":/go/src/k8s.io/kubernetes:Z  golang:"${GOLANG_VERSION}"  /bin/bash -c " cd /go/src/k8s.io/kubernetes/test/images/${SRC_DIR} &&  <del> CGO_ENABLED=0 GOARM=${GOARM} GOARCH=${ARCH} go build -a -installsuffix cgo --ldflags '-w' -o ${TARGET}/${SRC} ./$(dirname "${SRC}")" </del> <ins> CGO_ENABLED=0 ${arch_prefix} GOARCH=${ARCH} go build -a -installsuffix cgo --ldflags '-w' -o ${TARGET}/${SRC} ./$(dirname "${SRC}")" </ins> done }
serverCA         *x509.Certificate backdate         time.Duration <ins> userAgentLock   sync.Mutex </ins> expectUserAgent string lock sync.Mutex csr  *certapi.CertificateSigningRequest } <ins> func (s *csrSimulator) SetExpectUserAgent(a string) { s.userAgentLock.Lock() defer s.userAgentLock.Unlock() s.expectUserAgent = a } func (s *csrSimulator) ExpectUserAgent() string { s.userAgentLock.Lock() defer s.userAgentLock.Unlock() return s.expectUserAgent } </ins> func (s *csrSimulator) ServeHTTP(w http.ResponseWriter, req *http.Request) { s.lock.Lock() defer s.lock.Unlock()
q := req.URL.Query() q.Del("timeout") q.Del("timeoutSeconds") <ins> q.Del("allowWatchBookmarks") </ins> req.URL.RawQuery = q.Encode() t.Logf("Request %q %q %q", req.Method, req.URL, req.UserAgent()) <del> if len(s.expectUserAgent) > 0 && req.UserAgent() != s.expectUserAgent { </del> <ins> if a := s.ExpectUserAgent(); len(a) > 0 && req.UserAgent() != a { </ins> t.Errorf("Unexpected user agent: %s", req.UserAgent()) }
if sp.failScore { return 0, framework.NewStatus(framework.Error, fmt.Sprintf("injecting failure for pod %v", p.Name)) } score := 10 <del> if nodeName == sp.highScoreNode { </del> <ins> if sp.numCalled == 1 { // The first node is scored the highest, the rest is scored lower. sp.highScoreNode = nodeName </ins> score = 100 } return score, nil
cs := context.clientSet // Add multiple nodes, one of them will be scored much higher than the others. <del> nodes, err := createNodes(cs, "test-node", nil, 10) </del> <ins> _, err := createNodes(cs, "test-node", nil, 10) </ins> if err != nil { t.Fatalf("Cannot create nodes: %v", err) } <del> scPlugin.highScoreNode = nodes[3].Name </del> for i, fail := range []bool{false, true} { scPlugin.failScore = fail
if err := saveVolumeData(dataDir, volDataFileName, volData); err != nil { klog.Error(log("failed to save volume info data: %v", err)) <del> if err := os.RemoveAll(dataDir); err != nil { klog.Error(log("failed to remove dir after error [%s]: %v", dataDir, err)) return nil, err </del> <ins> if removeErr := os.RemoveAll(dataDir); removeErr != nil { klog.Error(log("failed to remove dir after error [%s]: %v", dataDir, removeErr)) </ins> } return nil, err }
// FlattenListVisitor flattens any objects that runtime.ExtractList recognizes as a list // - has an "Items" public field that is a slice of runtime.Objects or objects satisfying <del> // that interface - into multiple Infos. An error on any sub item (for instance, if a List // contains an object that does not have a registered client or resource) will terminate // the visit. // TODO: allow errors to be aggregated? </del> <ins> // that interface - into multiple Infos. Returns nil in the case of no errors. // When an error is hit on sub items (for instance, if a List contains an object that does // not have a registered client or resource), returns an aggregate error. </ins> type FlattenListVisitor struct { visitor Visitor typer   runtime.ObjectTyper
if info.Mapping != nil && !info.Mapping.GroupVersionKind.Empty() { preferredGVKs = append(preferredGVKs, info.Mapping.GroupVersionKind) } <ins> errs := []error{} </ins> for i := range items { item, err := v.mapper.infoForObject(items[i], v.typer, preferredGVKs) if err != nil { <del> return err </del> <ins> errs = append(errs, err) continue </ins> } if len(info.ResourceVersion) != 0 { item.ResourceVersion = info.ResourceVersion } if err := fn(item, nil); err != nil { <del> return err </del> <ins> errs = append(errs, err) </ins> } } <del> return nil </del> <ins> return utilerrors.NewAggregate(errs) </ins> }) }
t.Fatal(spew.Sdump(test.Infos)) } } <ins> func TestFlattenListVisitorWithVisitorError(t *testing.T) { b := newDefaultBuilder(). FilenameParam(false, &FilenameOptions{Recursive: false, Filenames: []string{"../../artifacts/deeply-nested.yaml"}}). Flatten() test := &testVisitor{InjectErr: errors.New("visitor error")} err := b.Do().Visit(test.Handle) if err == nil || !strings.Contains(err.Error(), "visitor error") { t.Fatal(err) } if len(test.Infos) != 6 { t.Fatal(spew.Sdump(test.Infos)) } } </ins>
testEndpointReachability(clusterIP, sp.Port, sp.Protocol, execPod) } } func testReachabilityOverNodePorts(nodes *v1.NodeList, sp v1.ServicePort, pod *v1.Pod) { internalAddrs := e2enode.CollectAddresses(nodes, v1.NodeInternalIP) externalAddrs := e2enode.CollectAddresses(nodes, v1.NodeExternalIP) for _, internalAddr := range internalAddrs { <ins> // If the node's internal address points to localhost, then we are not // able to test the service reachability via that address if isInvalidOrLocalhostAddress(internalAddr) { e2elog.Logf("skipping testEndpointReachability() for internal adddress %s", internalAddr) continue } </ins> testEndpointReachability(internalAddr, sp.NodePort, sp.Protocol, pod) } for _, externalAddr := range externalAddrs {
} } <ins> // isInvalidOrLocalhostAddress returns `true` if the provided `ip` is either not // parsable or the loopback address. Otherwise it will return `false`. func isInvalidOrLocalhostAddress(ip string) bool { parsedIP := net.ParseIP(ip) if parsedIP == nil || parsedIP.IsLoopback() { return true } return false } </ins> // testEndpointReachability tests reachability to endpoints (i.e. IP, ServiceName) and ports. Test request is initiated from specified execPod. // TCP and UDP protocol based service are supported at this moment // TODO: add support to test SCTP Protocol based services.
"//staging/src/k8s.io/client-go/rest:go_default_library", "//staging/src/k8s.io/client-go/util/cert:go_default_library", "//staging/src/k8s.io/client-go/util/keyutil:go_default_library", <ins> "//staging/src/k8s.io/client-go/util/retry:go_default_library", </ins> "//staging/src/k8s.io/client-go/util/workqueue:go_default_library", "//staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1:go_default_library", "//staging/src/k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset:go_default_library",
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/intstr" <ins> "k8s.io/apimachinery/pkg/util/uuid" </ins> utilversion "k8s.io/apimachinery/pkg/util/version" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/dynamic" clientset "k8s.io/client-go/kubernetes" <ins> "k8s.io/client-go/util/retry" </ins> "k8s.io/kubernetes/test/e2e/framework" e2edeploy "k8s.io/kubernetes/test/e2e/framework/deployment" e2elog "k8s.io/kubernetes/test/e2e/framework/log" e2epod "k8s.io/kubernetes/test/e2e/framework/pod" "k8s.io/kubernetes/test/utils/crd" imageutils "k8s.io/kubernetes/test/utils/image" <del> "k8s.io/utils/pointer" </del> "github.com/onsi/ginkgo" "github.com/onsi/gomega"