├── LICENSE ├── README.md ├── cilium-host-process-identities-poc-demo ├── HOST_PROCESS_ID_DEMO.diff ├── v1 │ ├── DO-eBPF-MAGIC.sh │ ├── HOST_PROCESS_ID_DEMO.diff │ ├── auditor-pod.yaml │ ├── bank-teller-db-pods.yaml │ ├── ciliumid-auditor.yaml │ ├── ciliumid-auditor.yaml.tmpl │ ├── policy-allow-auditor-db-access.yaml │ ├── policy-allow-teller-db-access.yaml │ └── thief.yaml └── yaml │ ├── DO-eBPF-MAGIC.sh │ ├── auditor-pod.yaml │ ├── bank-teller-db-pods.yaml │ ├── bthief-pod.yaml │ ├── policy-allow-auditor-teller-to-access-db.yaml │ └── z-ciliumid │ ├── ciliumid-auditor.yaml │ └── ciliumid-auditor.yaml.tmpl ├── ebpf-pod-network-stats ├── build-ebpf-netstats-attach-img.sh ├── ebpf-netstats-attach-poc-amd64.yaml ├── ebpf-netstats-attach-poc-arm64.yaml ├── ebpf-netstats-docker-img │ ├── attach_ebpf_netstats_prog.py │ ├── attach_ebpf_netstats_prog.sh │ ├── do_attach_ebpf_netstats_prog.sh │ ├── ebpf-netstats-attach-container-init.sh │ ├── ebpf-netstats-attach.Dockerfile │ └── launch-pod-network-setup-bpftrace.sh ├── ebpf-netstats-program │ ├── Makefile │ ├── bpf_elf_helpers.h │ ├── bpf_network_stats.c │ └── bpf_network_stats_maps.h └── systemd_version │ ├── Makefile │ ├── attach_ebpf_stats_prog.py │ ├── attach_ebpf_stats_prog.sh │ ├── bpf_elf_helpers.h │ ├── bpf_network_stats.c │ ├── bpf_network_stats_maps.h │ ├── build-ebpf-netstats-attach-img-arm64.sh │ ├── ebpf-netstats-attach-poc-arm64.yaml │ ├── ebpf-network-stats-attach.Dockerfile │ ├── init-container.sh │ └── launch-pod-network-setup-bpftrace.sh ├── ebpf-pod-resize-libbpf-rs-CO-RE ├── README.md ├── ebpf-pod-resize-libbpf-co-re │ ├── Cargo.lock │ ├── Cargo.toml │ ├── Makefile │ ├── build-ebpf-pod-resize-co-re-docker-img.sh │ ├── build.rs │ ├── crictl.yaml │ ├── ebpf-pod-resize-co-re.Dockerfile │ ├── ebpf-pod-resize-co-re.yaml │ ├── kube-build-pod.yaml │ └── src │ │ ├── bpf │ │ ├── podsnoop.bpf.c │ │ ├── podsnoop.h │ │ └── vmlinux.h │ │ ├── get-podns-podname-ctrname.sh │ │ ├── main.rs │ │ └── patch-pod-resources.sh ├── kube │ ├── .devcontainer │ │ ├── Dockerfile │ │ ├── README.md │ │ ├── devcontainer.json │ │ └── scurl │ ├── .github │ │ ├── FUNDING.yml │ │ ├── ISSUE_TEMPLATE │ │ │ ├── bug_report.yml │ │ │ ├── config.yml │ │ │ └── feature_request.yml │ │ ├── PULL_REQUEST_TEMPLATE.md │ │ ├── codecov.yml │ │ ├── dependabot.yml │ │ ├── release.yml │ │ └── workflows │ │ │ ├── audit.yml │ │ │ ├── ci.yml │ │ │ ├── clippy.yml │ │ │ ├── coverage.yml │ │ │ ├── devcontainer.yml │ │ │ ├── lint.yml │ │ │ ├── release.yml │ │ │ └── rustfmt.yml │ ├── .gitignore │ ├── CHANGELOG.md │ ├── CONTRIBUTING.md │ ├── Cargo.toml │ ├── LICENSE │ ├── README.md │ ├── SECURITY.md │ ├── clippy.toml │ ├── code-of-conduct.md │ ├── deny.toml │ ├── e2e │ │ ├── Cargo.toml │ │ ├── Dockerfile │ │ ├── README.md │ │ ├── boot.rs │ │ ├── deployment.yaml │ │ └── job.rs │ ├── examples │ │ ├── Cargo.toml │ │ ├── README.md │ │ ├── admission_controller.rs │ │ ├── admission_controller.yaml.tpl │ │ ├── admission_ok.yaml │ │ ├── admission_reject.yaml │ │ ├── admission_setup.sh │ │ ├── configmapgen_controller.rs │ │ ├── configmapgen_controller_crd.yaml │ │ ├── configmapgen_controller_object.yaml │ │ ├── crd-baz.yaml │ │ ├── crd-qux.yaml │ │ ├── crd_api.rs │ │ ├── crd_apply.rs │ │ ├── crd_derive.rs │ │ ├── crd_derive_custom_schema.rs │ │ ├── crd_derive_multi.rs │ │ ├── crd_derive_no_schema.rs │ │ ├── crd_derive_schema.rs │ │ ├── crd_reflector.rs │ │ ├── custom_client.rs │ │ ├── custom_client_tls.rs │ │ ├── custom_client_trace.rs │ │ ├── dynamic_api.rs │ │ ├── dynamic_jsonpath.rs │ │ ├── dynamic_pod.rs │ │ ├── dynamic_watcher.rs │ │ ├── event_watcher.rs │ │ ├── job_api.rs │ │ ├── kubectl.rs │ │ ├── log_stream.rs │ │ ├── multi_watcher.rs │ │ ├── node_reflector.rs │ │ ├── node_watcher.rs │ │ ├── pod_api.rs │ │ ├── pod_attach.rs │ │ ├── pod_cp.rs │ │ ├── pod_evict.rs │ │ ├── pod_exec.rs │ │ ├── pod_paged.rs │ │ ├── pod_portforward.rs │ │ ├── pod_portforward_bind.rs │ │ ├── pod_portforward_hyper_http.rs │ │ ├── pod_reflector.rs │ │ ├── pod_shell.rs │ │ ├── pod_watcher.rs │ │ ├── secret_reflector.rs │ │ ├── secret_syncer.rs │ │ └── secret_syncer_configmap.yaml │ ├── justfile │ ├── kube-client │ │ ├── Cargo.toml │ │ ├── README.md │ │ └── src │ │ │ ├── api │ │ │ ├── core_methods.rs │ │ │ ├── entry.rs │ │ │ ├── mod.rs │ │ │ ├── portforward.rs │ │ │ ├── remote_command.rs │ │ │ ├── subresource.rs │ │ │ └── util │ │ │ │ ├── csr.rs │ │ │ │ └── mod.rs │ │ │ ├── client │ │ │ ├── auth │ │ │ │ ├── mod.rs │ │ │ │ └── oauth.rs │ │ │ ├── body.rs │ │ │ ├── builder.rs │ │ │ ├── config_ext.rs │ │ │ ├── middleware │ │ │ │ ├── base_uri.rs │ │ │ │ ├── extra_headers.rs │ │ │ │ └── mod.rs │ │ │ ├── mod.rs │ │ │ ├── tls.rs │ │ │ └── upgrade.rs │ │ │ ├── config │ │ │ ├── file_config.rs │ │ │ ├── file_loader.rs │ │ │ ├── incluster_config.rs │ │ │ └── mod.rs │ │ │ ├── discovery │ │ │ ├── apigroup.rs │ │ │ ├── mod.rs │ │ │ ├── oneshot.rs │ │ │ └── parse.rs │ │ │ ├── error.rs │ │ │ └── lib.rs │ ├── kube-core │ │ ├── Cargo.toml │ │ ├── README.md │ │ └── src │ │ │ ├── admission.rs │ │ │ ├── conversion │ │ │ ├── mod.rs │ │ │ ├── test_data │ │ │ │ └── simple.json │ │ │ └── types.rs │ │ │ ├── crd.rs │ │ │ ├── discovery.rs │ │ │ ├── dynamic.rs │ │ │ ├── error.rs │ │ │ ├── gvk.rs │ │ │ ├── lib.rs │ │ │ ├── metadata.rs │ │ │ ├── object.rs │ │ │ ├── params.rs │ │ │ ├── request.rs │ │ │ ├── resource.rs │ │ │ ├── response.rs │ │ │ ├── schema.rs │ │ │ ├── subresource.rs │ │ │ ├── util.rs │ │ │ ├── version.rs │ │ │ └── watch.rs │ ├── kube-derive │ │ ├── Cargo.toml │ │ ├── README.md │ │ ├── src │ │ │ ├── custom_resource.rs │ │ │ └── lib.rs │ │ └── tests │ │ │ ├── crd_enum_test.rs │ │ │ ├── crd_schema_test.rs │ │ │ ├── test_ui.rs │ │ │ └── ui │ │ │ ├── fail_with_suggestion.rs │ │ │ ├── fail_with_suggestion.stderr │ │ │ ├── missing_required.rs │ │ │ ├── missing_required.stderr │ │ │ ├── union_fails.rs │ │ │ └── union_fails.stderr │ ├── kube-runtime │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── controller │ │ │ ├── future_hash_map.rs │ │ │ ├── mod.rs │ │ │ └── runner.rs │ │ │ ├── events.rs │ │ │ ├── finalizer.rs │ │ │ ├── lib.rs │ │ │ ├── reflector │ │ │ ├── mod.rs │ │ │ ├── object_ref.rs │ │ │ └── store.rs │ │ │ ├── scheduler.rs │ │ │ ├── utils │ │ │ ├── backoff_reset_timer.rs │ │ │ ├── event_flatten.rs │ │ │ ├── mod.rs │ │ │ ├── stream_backoff.rs │ │ │ └── watch_ext.rs │ │ │ ├── wait.rs │ │ │ └── watcher.rs │ ├── kube │ │ ├── Cargo.toml │ │ └── src │ │ │ └── lib.rs │ ├── release.toml │ ├── rustfmt.toml │ ├── scripts │ │ ├── release-afterdoc.sh │ │ ├── release-gh.sh │ │ ├── release-post.sh │ │ └── release-pre.sh │ └── tarpaulin.toml ├── libbpf-bootstrap │ ├── .github │ │ ├── docker │ │ │ └── Dockerfile.ubuntu │ │ └── workflows │ │ │ └── build.yml │ ├── .gitignore │ ├── .gitmodules │ ├── LICENSE │ ├── README.md │ ├── examples │ │ ├── c │ │ │ ├── .gitignore │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── bootstrap.bpf.c │ │ │ ├── bootstrap.c │ │ │ ├── bootstrap.h │ │ │ ├── fentry.bpf.c │ │ │ ├── fentry.c │ │ │ ├── kprobe.bpf.c │ │ │ ├── kprobe.c │ │ │ ├── minimal.bpf.c │ │ │ ├── minimal.c │ │ │ ├── minimal_legacy.bpf.c │ │ │ ├── minimal_legacy.c │ │ │ ├── profile.bpf.c │ │ │ ├── profile.c │ │ │ ├── profile.h │ │ │ ├── sockfilter.bpf.c │ │ │ ├── sockfilter.c │ │ │ ├── sockfilter.h │ │ │ ├── tc.bpf.c │ │ │ ├── tc.c │ │ │ ├── uprobe.bpf.c │ │ │ ├── uprobe.c │ │ │ ├── usdt.bpf.c │ │ │ ├── usdt.c │ │ │ └── xmake.lua │ │ └── rust │ │ │ ├── .gitignore │ │ │ ├── Cargo.lock │ │ │ ├── Cargo.toml │ │ │ ├── profile │ │ │ ├── .gitignore │ │ │ ├── Cargo.toml │ │ │ ├── build.rs │ │ │ └── src │ │ │ │ ├── bpf │ │ │ │ ├── profile.bpf.c │ │ │ │ ├── profile.h │ │ │ │ └── vmlinux.h │ │ │ │ ├── main.rs │ │ │ │ └── syscall.rs │ │ │ ├── tracecon │ │ │ ├── .gitignore │ │ │ ├── Cargo.lock │ │ │ ├── Cargo.toml │ │ │ ├── README.md │ │ │ ├── Vagrantfile │ │ │ ├── build.rs │ │ │ └── src │ │ │ │ ├── bpf │ │ │ │ ├── tracecon.bpf.c │ │ │ │ └── vmlinux.h │ │ │ │ └── main.rs │ │ │ └── xdp │ │ │ ├── .gitignore │ │ │ ├── Cargo.lock │ │ │ ├── Cargo.toml │ │ │ ├── build.rs │ │ │ └── src │ │ │ ├── bpf │ │ │ ├── vmlinux.h │ │ │ └── xdppass.bpf.c │ │ │ └── main.rs │ ├── tools │ │ ├── cmake │ │ │ ├── FindBpfObject.cmake │ │ │ └── FindLibBpf.cmake │ │ └── gen_vmlinux_h.sh │ └── vmlinux │ │ ├── arm64 │ │ ├── vmlinux.h │ │ └── vmlinux_516.h │ │ ├── vmlinux.h │ │ └── x86 │ │ ├── vmlinux.h │ │ └── vmlinux_508.h └── libbpf-rs │ ├── .gitattributes │ ├── .github │ └── workflows │ │ └── rust.yml │ ├── .gitignore │ ├── CONTRIBUTING.md │ ├── Cargo.lock │ ├── Cargo.toml │ ├── LICENSE │ ├── LICENSE.BSD-2-Clause │ ├── LICENSE.LPGL-2.1 │ ├── README.md │ ├── examples │ ├── bpf_query │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── capable │ │ ├── Cargo.toml │ │ ├── README.md │ │ ├── build.rs │ │ └── src │ │ │ ├── bpf │ │ │ ├── capable.bpf.c │ │ │ ├── capable.h │ │ │ └── vmlinux.h │ │ │ └── main.rs │ ├── runqslower │ │ ├── Cargo.toml │ │ ├── README.md │ │ ├── build.rs │ │ └── src │ │ │ ├── bpf │ │ │ ├── runqslower.bpf.c │ │ │ ├── runqslower.h │ │ │ └── vmlinux.h │ │ │ └── main.rs │ ├── tc_port_whitelist │ │ ├── Cargo.toml │ │ ├── build.rs │ │ └── src │ │ │ ├── bpf │ │ │ ├── tc.bpf.c │ │ │ └── vmlinux.h │ │ │ └── main.rs │ └── vmlinux_515.h │ ├── libbpf-cargo │ ├── Cargo.toml │ ├── LICENSE │ ├── LICENSE.BSD-2-Clause │ ├── LICENSE.LPGL-2.1 │ ├── README.md │ ├── src │ │ ├── btf │ │ │ ├── btf.rs │ │ │ ├── c_types.rs │ │ │ ├── mod.rs │ │ │ └── types.rs │ │ ├── build.rs │ │ ├── gen.rs │ │ ├── lib.rs │ │ ├── main.rs │ │ ├── make.rs │ │ ├── metadata.rs │ │ └── test.rs │ └── test_data │ │ └── vmlinux.h │ └── libbpf-rs │ ├── .cargo │ └── config │ ├── Cargo.toml │ ├── LICENSE │ ├── LICENSE.BSD-2-Clause │ ├── LICENSE.LPGL-2.1 │ ├── README.md │ ├── src │ ├── error.rs │ ├── iter.rs │ ├── lib.rs │ ├── link.rs │ ├── map.rs │ ├── object.rs │ ├── perf_buffer.rs │ ├── print.rs │ ├── program.rs │ ├── query.rs │ ├── ringbuf.rs │ ├── skeleton.rs │ ├── tc.rs │ └── util.rs │ └── tests │ ├── README.md │ ├── bin │ └── src │ │ ├── percpu_map.bpf.c │ │ ├── ringbuf.bpf.c │ │ ├── runqslower.bpf.c │ │ ├── runqslower.h │ │ ├── taskiter.bpf.c │ │ ├── tc-unit.bpf.c │ │ └── usdt.bpf.c │ ├── bpf_object_regen.sh │ ├── test.rs │ ├── test_print.rs │ └── test_tc.rs ├── ebpf-pod-resize ├── README.md ├── bootstrap-ebpf-demo.sh ├── build-ebpf-pod-resize-docker-img-amd64.sh ├── build-ebpf-pod-resize-docker-img.sh ├── crictl.yaml ├── ebpf-pod-resize-demo-amd64.yaml ├── ebpf-pod-resize-demo.Dockerfile ├── ebpf-pod-resize-demo.yaml ├── init-ebpf-pod-resize.sh ├── kube-build-pod-amd64.yaml ├── kube-build-pod.yaml ├── launch-ebpf-pod-resize.sh └── podsnoop.py └── tc-vs-xdp-perf ├── Makefile ├── README.md ├── fg ├── no_ebpf.svg ├── tc_ebpf.svg ├── xdp_drv.svg └── xdp_generic.svg ├── tc_ingress.c └── xdp_ingress.c /README.md: -------------------------------------------------------------------------------- 1 | # ebpf-playground 2 | eBPF playground 3 | -------------------------------------------------------------------------------- /cilium-host-process-identities-poc-demo/v1/DO-eBPF-MAGIC.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | 3 | RED='\033[0;31m' 4 | ORANGE='\033[0;33m' 5 | BLUE='\033[1;94m' 6 | PURPLE='\033[0;35m' 7 | GREEN='\033[1;92m' 8 | NC='\033[0m' 9 | 10 | NETWORK_IDENTITY=${1:-12345} 11 | 12 | function num_to_hex_str() { 13 | local size=$1 14 | local value=$2 15 | local hexstr=$(printf "%0${size}x" $value) 16 | local spaced_hexstr=$(echo $hexstr | sed -E 's/(..)/\1 /g') 17 | local reversed_hexstr=$(echo $spaced_hexstr | awk '{for(i=NF;i>=1;i--) printf "%s ",$i}') 18 | echo $reversed_hexstr 19 | } 20 | 21 | #echo "Looking up bank-auditor container-id." 22 | C_ID=$(crictl ps | grep bank-auditor | awk '{print $1}') 23 | 24 | echo -e "${PURPLE}Looking up cgroup-id of bank-auditor container (id=${C_ID}).${NC}" 25 | CG_ID=$(ls -ldi $(find /sys/fs/cgroup/kubepods/besteffort/ -type d | grep ${C_ID}) | awk '{print $1}') 26 | 27 | BPF_MAP_KEY=$(num_to_hex_str 16 ${CG_ID}) 28 | BPF_MAP_VALUE=$(num_to_hex_str 8 ${NETWORK_IDENTITY}) 29 | 30 | sed s/__AUDITOR_POD_IDENTITY__/\"${NETWORK_IDENTITY}\"/ ciliumid-auditor.yaml.tmpl > ciliumid-auditor.yaml 31 | echo -e "${PURPLE}Creating CiliumIdentity (Id=${NETWORK_IDENTITY}) for bank-auditor hostNetwork pod (cgroup-id=${CG_ID}).${NC}" 32 | kubectl create -f ~/demo/ciliumid-auditor.yaml 33 | if [ $? -ne 0 ]; then 34 | echo -e "${RED}ERROR: Unable to create CiliumIdentity for bank-auditor pod. ERROR_CODE=$?${NC}" 35 | fi 36 | 37 | echo -e "${PURPLE}Adding cgroup-id of bank-auditor to BPF map host_process_netid_map.${NC}" 38 | HP_MAP_ID=$(bpftool map list | grep host_process | awk '{print $1}' | cut -d: -f1) 39 | BPFTOOL_CMD="bpftool map update id ${HP_MAP_ID} key hex ${BPF_MAP_KEY} value hex ${BPF_MAP_VALUE}" 40 | echo -e "${PURPLE} ...executing bpftool command: '${BPFTOOL_CMD}'${NC}" 41 | eval "${BPFTOOL_CMD}" 42 | if [ $? -eq 0 ]; then 43 | echo -e "${BLUE}Success adding network-identity ${NETWORK_IDENTITY} for bank-auditor container (cgroup-id=${CG_ID}) to host_process_network_id BPF map. ${GREEN}✔${NC}" 44 | fi 45 | -------------------------------------------------------------------------------- /cilium-host-process-identities-poc-demo/v1/auditor-pod.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Pod 3 | metadata: 4 | name: bank-auditor 5 | labels: 6 | role: auditor 7 | spec: 8 | hostNetwork: true 9 | nodeName: master 10 | containers: 11 | - name: ctr 12 | image: skiibum/testpod:qos 13 | -------------------------------------------------------------------------------- /cilium-host-process-identities-poc-demo/v1/bank-teller-db-pods.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Pod 3 | metadata: 4 | name: bank-teller 5 | labels: 6 | role: teller 7 | spec: 8 | nodeName: master 9 | containers: 10 | - name: ctr 11 | image: skiibum/testpod:qos 12 | --- 13 | apiVersion: v1 14 | kind: Pod 15 | metadata: 16 | name: bank-db 17 | labels: 18 | role: database 19 | spec: 20 | nodeName: node1 21 | containers: 22 | - name: ctr 23 | image: skiibum/testpod:qos 24 | -------------------------------------------------------------------------------- /cilium-host-process-identities-poc-demo/v1/ciliumid-auditor.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: cilium.io/v2 2 | kind: CiliumIdentity 3 | metadata: 4 | labels: 5 | io.cilium.k8s.policy.cluster: kubernetes 6 | io.cilium.k8s.policy.serviceaccount: default 7 | io.kubernetes.pod.namespace: default 8 | role: auditor 9 | name: "12345" 10 | security-labels: 11 | k8s:io.cilium.k8s.namespace.labels.kubernetes.io/metadata.name: default 12 | k8s:io.cilium.k8s.policy.cluster: kubernetes 13 | k8s:io.cilium.k8s.policy.serviceaccount: default 14 | k8s:io.kubernetes.pod.namespace: default 15 | k8s:role: auditor 16 | -------------------------------------------------------------------------------- /cilium-host-process-identities-poc-demo/v1/ciliumid-auditor.yaml.tmpl: -------------------------------------------------------------------------------- 1 | apiVersion: cilium.io/v2 2 | kind: CiliumIdentity 3 | metadata: 4 | labels: 5 | io.cilium.k8s.policy.cluster: kubernetes 6 | io.cilium.k8s.policy.serviceaccount: default 7 | io.kubernetes.pod.namespace: default 8 | role: auditor 9 | name: __AUDITOR_POD_IDENTITY__ 10 | security-labels: 11 | k8s:io.cilium.k8s.namespace.labels.kubernetes.io/metadata.name: default 12 | k8s:io.cilium.k8s.policy.cluster: kubernetes 13 | k8s:io.cilium.k8s.policy.serviceaccount: default 14 | k8s:io.kubernetes.pod.namespace: default 15 | k8s:role: auditor 16 | -------------------------------------------------------------------------------- /cilium-host-process-identities-poc-demo/v1/policy-allow-auditor-db-access.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: "cilium.io/v2" 2 | kind: CiliumClusterwideNetworkPolicy 3 | metadata: 4 | name: "allow-auditor-to-access-db" 5 | spec: 6 | endpointSelector: 7 | matchLabels: 8 | role: database 9 | ingress: 10 | - fromEndpoints: 11 | - matchLabels: 12 | role: auditor 13 | -------------------------------------------------------------------------------- /cilium-host-process-identities-poc-demo/v1/policy-allow-teller-db-access.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: "cilium.io/v2" 2 | kind: CiliumNetworkPolicy 3 | metadata: 4 | name: "allow-teller-to-access-db" 5 | spec: 6 | endpointSelector: 7 | matchLabels: 8 | role: database 9 | ingress: 10 | - fromEndpoints: 11 | - matchLabels: 12 | role: teller 13 | -------------------------------------------------------------------------------- /cilium-host-process-identities-poc-demo/v1/thief.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Pod 3 | metadata: 4 | name: thief 5 | labels: 6 | role: scammer 7 | spec: 8 | hostNetwork: true 9 | nodeName: master 10 | containers: 11 | - name: ctr 12 | image: skiibum/testpod:qos 13 | -------------------------------------------------------------------------------- /cilium-host-process-identities-poc-demo/yaml/DO-eBPF-MAGIC.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | 3 | RED='\033[0;31m' 4 | ORANGE='\033[0;33m' 5 | BLUE='\033[1;94m' 6 | PURPLE='\033[1;35m' 7 | PURPLEL='\033[0;35m' 8 | GREEN='\033[1;92m' 9 | NC='\033[0m' 10 | 11 | NETWORK_IDENTITY=${1:-12345} 12 | 13 | function num_to_hex_str() { 14 | local size=$1 15 | local value=$2 16 | local hexstr=$(printf "%0${size}x" $value) 17 | local spaced_hexstr=$(echo $hexstr | sed -E 's/(..)/\1 /g') 18 | local reversed_hexstr=$(echo $spaced_hexstr | awk '{for(i=NF;i>=1;i--) printf "%s ",$i}') 19 | echo $reversed_hexstr 20 | } 21 | 22 | #echo "Looking up bank-auditor container-id." 23 | C_ID=$(crictl ps | grep bank-auditor | awk '{print $1}') 24 | 25 | echo -e "👀 ${PURPLE}Looking up cgroup-id of bank-auditor container (container-id=${C_ID}) 👀${NC}" 26 | CG_ID=$(ls -ldi $(find /sys/fs/cgroup/kubepods.slice/kubepods-besteffort.slice/ -type d | grep ${C_ID}) | awk '{print $1}') 27 | 28 | BPF_MAP_KEY=$(num_to_hex_str 16 ${CG_ID}) 29 | BPF_MAP_VALUE=$(num_to_hex_str 8 ${NETWORK_IDENTITY}) 30 | 31 | sed s/__AUDITOR_POD_IDENTITY__/\"${NETWORK_IDENTITY}\"/ z-ciliumid/ciliumid-auditor.yaml.tmpl > z-ciliumid/ciliumid-auditor.yaml 32 | echo -e "🛠 ${PURPLE}Creating CiliumIdentity object (cilium-id=${NETWORK_IDENTITY}) for bank-auditor hostNetwork pod (cgroup-id=${CG_ID}) 🛠${NC}" 33 | printf " ☑️ " && kubectl create -f ~/demo/z-ciliumid/ciliumid-auditor.yaml 34 | if [ $? -ne 0 ]; then 35 | echo -e "${RED}ERROR: Unable to create CiliumIdentity for bank-auditor pod. ERROR_CODE=$?${NC}" 36 | fi 37 | 38 | echo -e "🐝 ${PURPLE}Adding network identity of bank-auditor container to HOST_PROCESS_NETID BPF map${NC} 🐝" 39 | HP_MAP_ID=$(bpftool map list | grep host_process | awk '{print $1}' | cut -d: -f1) 40 | BPFTOOL_CMD="bpftool map update id ${HP_MAP_ID} key hex ${BPF_MAP_KEY} value hex ${BPF_MAP_VALUE}" 41 | echo -e "${NC} ☑️ cmd: '${BPFTOOL_CMD}'${NC}" 42 | eval "${BPFTOOL_CMD}" 43 | if [ $? -eq 0 ]; then 44 | echo -e "✅ ${BLUE}Success! bank-auditor network identity ${NETWORK_IDENTITY} is now associated with cgroup-id ${CG_ID} ✅${NC}" 45 | fi 46 | -------------------------------------------------------------------------------- /cilium-host-process-identities-poc-demo/yaml/auditor-pod.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Pod 3 | metadata: 4 | name: bank-auditor 5 | labels: 6 | role: auditor 7 | spec: 8 | hostNetwork: true 9 | nodeName: master 10 | containers: 11 | - name: ctr 12 | image: skiibum/testpod:qos 13 | -------------------------------------------------------------------------------- /cilium-host-process-identities-poc-demo/yaml/bank-teller-db-pods.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Pod 3 | metadata: 4 | name: bank-teller 5 | labels: 6 | role: teller 7 | spec: 8 | nodeName: master 9 | containers: 10 | - name: ctr 11 | image: skiibum/testpod:qos 12 | --- 13 | apiVersion: v1 14 | kind: Pod 15 | metadata: 16 | name: bank-db 17 | labels: 18 | role: database 19 | spec: 20 | nodeName: node1 21 | containers: 22 | - name: ctr 23 | image: skiibum/testpod:qos 24 | -------------------------------------------------------------------------------- /cilium-host-process-identities-poc-demo/yaml/bthief-pod.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Pod 3 | metadata: 4 | name: thief 5 | labels: 6 | role: scammer 7 | spec: 8 | hostNetwork: true 9 | nodeName: master 10 | containers: 11 | - name: ctr 12 | image: skiibum/testpod:qos 13 | -------------------------------------------------------------------------------- /cilium-host-process-identities-poc-demo/yaml/policy-allow-auditor-teller-to-access-db.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: "cilium.io/v2" 2 | kind: CiliumNetworkPolicy 3 | metadata: 4 | name: "allow-teller-auditor-to-access-db" 5 | spec: 6 | endpointSelector: 7 | matchLabels: 8 | role: database 9 | ingress: 10 | - fromEndpoints: 11 | - matchLabels: 12 | role: teller 13 | - matchLabels: 14 | role: auditor 15 | -------------------------------------------------------------------------------- /cilium-host-process-identities-poc-demo/yaml/z-ciliumid/ciliumid-auditor.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: cilium.io/v2 2 | kind: CiliumIdentity 3 | metadata: 4 | labels: 5 | io.cilium.k8s.policy.cluster: kubernetes 6 | io.cilium.k8s.policy.serviceaccount: default 7 | io.kubernetes.pod.namespace: default 8 | role: auditor 9 | name: "34567" 10 | security-labels: 11 | k8s:io.cilium.k8s.namespace.labels.kubernetes.io/metadata.name: default 12 | k8s:io.cilium.k8s.policy.cluster: kubernetes 13 | k8s:io.cilium.k8s.policy.serviceaccount: default 14 | k8s:io.kubernetes.pod.namespace: default 15 | k8s:role: auditor 16 | -------------------------------------------------------------------------------- /cilium-host-process-identities-poc-demo/yaml/z-ciliumid/ciliumid-auditor.yaml.tmpl: -------------------------------------------------------------------------------- 1 | apiVersion: cilium.io/v2 2 | kind: CiliumIdentity 3 | metadata: 4 | labels: 5 | io.cilium.k8s.policy.cluster: kubernetes 6 | io.cilium.k8s.policy.serviceaccount: default 7 | io.kubernetes.pod.namespace: default 8 | role: auditor 9 | name: __AUDITOR_POD_IDENTITY__ 10 | security-labels: 11 | k8s:io.cilium.k8s.namespace.labels.kubernetes.io/metadata.name: default 12 | k8s:io.cilium.k8s.policy.cluster: kubernetes 13 | k8s:io.cilium.k8s.policy.serviceaccount: default 14 | k8s:io.kubernetes.pod.namespace: default 15 | k8s:role: auditor 16 | -------------------------------------------------------------------------------- /ebpf-pod-network-stats/build-ebpf-netstats-attach-img.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -x 2 | 3 | cpu_arch="amd64" 4 | if [[ "$(arch)" == "aarch64" ]]; then 5 | cpu_arch="arm64" 6 | fi 7 | 8 | pushd ebpf-netstats-program 9 | make clean 10 | make all 11 | popd 12 | 13 | docker rmi -f skiibum/ebpf-netstats-attach-${cpu_arch}:poc 14 | docker image build -t skiibum/ebpf-netstats-attach-${cpu_arch}:poc -f ebpf-netstats-docker-img/ebpf-netstats-attach.Dockerfile . 15 | -------------------------------------------------------------------------------- /ebpf-pod-network-stats/ebpf-netstats-docker-img/attach_ebpf_netstats_prog.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/bash -x 2 | 3 | # Set this environment variable to provide location of the eBPF stats program 4 | #export eBPF_PROGRAM_NAME="" 5 | 6 | # Set this environment variable to provide eBPF section name of stats program 7 | #export eBPF_SECTION_NAME="" 8 | 9 | #TODO: Investigate why 'retval' from bpftrace is garbage when using upstream bits vs. 'GODEBUG=1 make all' bits 10 | # Calling attach_ebpf_netstats_prog.py still works since it aims to attach eBPF program to all containerd 11 | # generated network namespaces ('cni-' prefix). Specifying only certain CNI network interfaces (via pod 12 | # annotations or some other means) is a possible future work item if that is desired. 13 | #if [ $1 == 0 ]; then 14 | # echo $(date '+%T.%N') > /tmp/timestamp 15 | # python3 /attach_ebpf_netstats_prog.py 16 | # echo $(date '+%T.%N') >> /tmp/timestamp 17 | #fi 18 | 19 | # Directly invoke shell commands to attach eBPF program because python program performance sucks 20 | /do_attach_ebpf_netstats_prog.sh 21 | -------------------------------------------------------------------------------- /ebpf-pod-network-stats/ebpf-netstats-docker-img/do_attach_ebpf_netstats_prog.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/bash 2 | 3 | #TODO: Update from env variables 4 | TX_STATS_eBPF_PROGRAM_NAME="./obj/bpf_network_stats.o" 5 | TX_STATS_eBPF_SECTION_NAME="pod_net_stats_tx" 6 | 7 | echo $(date '+%T.%N') 8 | for ifname in $(nsenter -t 1 -m -u -n -i ip -o -d link show type veth | grep "cni-" | awk '{print $2}' | cut -d@ -f1) 9 | do 10 | tc -o filter show dev $ifname ingress | grep $TX_STATS_eBPF_SECTION_NAME > /dev/null 2>&1 11 | if [ $? -ne 0 ] 12 | then 13 | tc qdisc add dev $ifname clsact 14 | tc filter add dev $ifname ingress bpf da obj $TX_STATS_eBPF_PROGRAM_NAME sec $TX_STATS_eBPF_SECTION_NAME 15 | fi 16 | done 17 | echo $(date '+%T.%N') 18 | -------------------------------------------------------------------------------- /ebpf-pod-network-stats/ebpf-netstats-docker-img/ebpf-netstats-attach-container-init.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -xe 2 | 3 | apt-get update -y 4 | apt-get install -y linux-headers-$(uname -r) 5 | -------------------------------------------------------------------------------- /ebpf-pod-network-stats/ebpf-netstats-docker-img/ebpf-netstats-attach.Dockerfile: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: MIT 2 | # Copyright (c) 2022 The Authors. 3 | 4 | # Authors: Vinay Kulkarni <@vinaykul> 5 | 6 | # Permission is hereby granted, free of charge, to any person obtaining a copy 7 | # of this software and associated documentation files (the "Software"), to deal 8 | # in the Software without restriction, including without limitation the rights 9 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | # copies of the Software, and to permit persons to whom the Software is 11 | # furnished to do so, subject to the following conditions:The above copyright 12 | # notice and this permission notice shall be included in all copies or 13 | # substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", 14 | # WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 15 | # TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 16 | # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE 17 | # FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 18 | # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR 19 | # THE USE OR OTHER DEALINGS IN THE SOFTWARE. 20 | 21 | FROM ubuntu:20.04 22 | 23 | RUN apt-get update -y 24 | RUN apt-get install -y vim iproute2 bpfcc-tools bpftrace python3 python3-pip 25 | RUN pip3 install --upgrade pip 26 | RUN pip3 install --upgrade pyroute2 27 | 28 | #TODO: Replace this demo bpf_network_stats.o with desired (real) eBPF stats program 29 | COPY ebpf-netstats-program/obj/bpf_network_stats.o /obj/ 30 | COPY ebpf-netstats-docker-img/attach_ebpf_netstats_prog.sh / 31 | COPY ebpf-netstats-docker-img/do_attach_ebpf_netstats_prog.sh / 32 | COPY ebpf-netstats-docker-img/attach_ebpf_netstats_prog.py / 33 | COPY ebpf-netstats-docker-img/ebpf-netstats-attach-container-init.sh / 34 | COPY ebpf-netstats-docker-img/launch-pod-network-setup-bpftrace.sh / 35 | 36 | CMD /launch-pod-network-setup-bpftrace.sh 37 | -------------------------------------------------------------------------------- /ebpf-pod-network-stats/ebpf-netstats-docker-img/launch-pod-network-setup-bpftrace.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -xe 2 | 3 | # 4 | # NOTE: Currently, we have a limitation - we need debug version of containerd 5 | # To build debug version of containerd: 6 | # git clone containerd/containerd 7 | # cd containerd 8 | # 9 | # GODEBUG=1 make all 10 | # 6 | 7 | /* Note: 8 | * 9 | * Below ELF section names and bpf_elf_map structure definition 10 | * are not (!) kernel ABI. It's rather a "contract" between the 11 | * application and the BPF loader in tc. For compatibility, the 12 | * section names should stay as-is. Introduction of aliases, if 13 | * needed, are a possibility, though. 14 | */ 15 | 16 | /* ELF section names, etc */ 17 | #define ELF_SECTION_LICENSE "license" 18 | #define ELF_SECTION_MAPS "maps" 19 | #define ELF_SECTION_PROG "prog" 20 | #define ELF_SECTION_CLASSIFIER "classifier" 21 | #define ELF_SECTION_ACTION "action" 22 | 23 | #define ELF_MAX_MAPS 64 24 | #define ELF_MAX_LICENSE_LEN 128 25 | 26 | /* Object pinning settings */ 27 | #define PIN_NONE 0 28 | #define PIN_OBJECT_NS 1 29 | #define PIN_GLOBAL_NS 2 30 | 31 | /* ELF map definition */ 32 | struct bpf_elf_map { 33 | __u32 type; 34 | __u32 size_key; 35 | __u32 size_value; 36 | __u32 max_elem; 37 | __u32 flags; 38 | __u32 id; 39 | __u32 pinning; 40 | __u32 inner_id; 41 | __u32 inner_idx; 42 | }; 43 | 44 | #endif /* __BPF_ELF__ */ 45 | -------------------------------------------------------------------------------- /ebpf-pod-network-stats/ebpf-netstats-program/bpf_network_stats.c: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-2.0 2 | // Author: Vinay Kulkarni <@vinaykul> 3 | 4 | //#include "vmlinux.h" 5 | #include 6 | #include 7 | #include 8 | #include "bpf_network_stats_maps.h" 9 | #include "bpf_elf_helpers.h" 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | 18 | SEC("pod_net_stats_tx") 19 | int tc_pod_net_stats_tx(struct __sk_buff *skb) 20 | { 21 | char msg[] = "==>> SRC: %x BYTES=%u\n"; 22 | uint64_t cgid = bpf_skb_cgroup_id(skb); 23 | void *data = (void *)(long)skb->data; 24 | void *data_end = (void *)(long)skb->data_end; 25 | uint64_t len = (uint64_t)(skb->data_end - skb->data); 26 | 27 | if (data + sizeof(struct ethhdr) + sizeof(struct iphdr) < data_end) { 28 | struct ethhdr *eth = data; 29 | struct iphdr *ip = (data + sizeof(struct ethhdr)); 30 | bpf_trace_printk(msg, sizeof(msg), bpf_ntohl(ip->saddr), len); 31 | } 32 | return TC_ACT_OK; 33 | } 34 | 35 | char __license[] SEC("license") = "GPL"; 36 | -------------------------------------------------------------------------------- /ebpf-pod-network-stats/ebpf-netstats-program/bpf_network_stats_maps.h: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-2.0 2 | // Author: Vinay Kulkarni <@vinaykul> 3 | 4 | #ifndef __BFP_NETSTATS_H 5 | #define __BFP_NETSTATS_H 6 | 7 | struct tx_net_stats_key_t { 8 | __u32 saddr; 9 | } __attribute__((packed, aligned(4))); 10 | 11 | struct tx_net_stats_t { 12 | __u64 tx_bytes; 13 | __u64 tx_pkts; 14 | } __attribute__((packed, aligned(8))); 15 | 16 | #endif /* __BFP_NETSTATS_H */ 17 | -------------------------------------------------------------------------------- /ebpf-pod-network-stats/systemd_version/Makefile: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: GPL-2.0-or-later 2 | 3 | CLANG=clang 4 | CLANGFLAGS= -I.\ 5 | -Wno-unused-value -Wno-pointer-sign\ 6 | -Wno-compare-distinct-pointer-types \ 7 | -Wno-gnu-variable-sized-type-not-at-end \ 8 | -Wno-address-of-packed-member -Wno-tautological-compare \ 9 | -Wno-unknown-warning-option -O1 -emit-llvm -c -o - 10 | LLC=llc -march=bpf -filetype=obj 11 | 12 | bpfsrc = $(wildcard *.c) 13 | bpfobj = $(bpfsrc:.c=.o) 14 | 15 | all: tcbpf 16 | mkdir -p obj 17 | mv *.o obj/ 18 | 19 | tcbpf: $(bpfobj) 20 | 21 | %.o: %.c 22 | $(CLANG) -c $^ $(CLANGFLAGS) | $(LLC) -o $@ 23 | 24 | clean: 25 | rm -rf obj 26 | 27 | -------------------------------------------------------------------------------- /ebpf-pod-network-stats/systemd_version/attach_ebpf_stats_prog.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/bash -x 2 | 3 | # Set this environment variable to provide location of the eBPF stats program 4 | #export eBPF_PROGRAM_NAME="" 5 | 6 | # Set this environment variable to provide eBPF section name of stats program 7 | #export eBPF_SECTION_NAME="" 8 | 9 | if [ $1 == 0 ]; then 10 | python3 ./attach_ebpf_stats_prog.py 11 | fi 12 | -------------------------------------------------------------------------------- /ebpf-pod-network-stats/systemd_version/bpf_elf_helpers.h: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: GPL-2.0 */ 2 | #ifndef __BPF_ELF__ 3 | #define __BPF_ELF__ 4 | 5 | #include 6 | 7 | /* Note: 8 | * 9 | * Below ELF section names and bpf_elf_map structure definition 10 | * are not (!) kernel ABI. It's rather a "contract" between the 11 | * application and the BPF loader in tc. For compatibility, the 12 | * section names should stay as-is. Introduction of aliases, if 13 | * needed, are a possibility, though. 14 | */ 15 | 16 | /* ELF section names, etc */ 17 | #define ELF_SECTION_LICENSE "license" 18 | #define ELF_SECTION_MAPS "maps" 19 | #define ELF_SECTION_PROG "prog" 20 | #define ELF_SECTION_CLASSIFIER "classifier" 21 | #define ELF_SECTION_ACTION "action" 22 | 23 | #define ELF_MAX_MAPS 64 24 | #define ELF_MAX_LICENSE_LEN 128 25 | 26 | /* Object pinning settings */ 27 | #define PIN_NONE 0 28 | #define PIN_OBJECT_NS 1 29 | #define PIN_GLOBAL_NS 2 30 | 31 | /* ELF map definition */ 32 | struct bpf_elf_map { 33 | __u32 type; 34 | __u32 size_key; 35 | __u32 size_value; 36 | __u32 max_elem; 37 | __u32 flags; 38 | __u32 id; 39 | __u32 pinning; 40 | __u32 inner_id; 41 | __u32 inner_idx; 42 | }; 43 | 44 | #endif /* __BPF_ELF__ */ 45 | -------------------------------------------------------------------------------- /ebpf-pod-network-stats/systemd_version/bpf_network_stats.c: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-2.0 2 | // Author: Vinay Kulkarni <@vinaykul> 3 | 4 | //#include "vmlinux.h" 5 | #include 6 | #include 7 | #include 8 | #include "bpf_network_stats_maps.h" 9 | #include "bpf_elf_helpers.h" 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | 18 | SEC("pod_net_stats_tx") 19 | int tc_pod_net_stats_tx(struct __sk_buff *skb) 20 | { 21 | char msg[] = "==>> SRC: %x BYTES=%u\n"; 22 | uint64_t cgid = bpf_skb_cgroup_id(skb); 23 | void *data = (void *)(long)skb->data; 24 | void *data_end = (void *)(long)skb->data_end; 25 | uint64_t len = (uint64_t)(skb->data_end - skb->data); 26 | 27 | if (data + sizeof(struct ethhdr) + sizeof(struct iphdr) < data_end) { 28 | struct ethhdr *eth = data; 29 | struct iphdr *ip = (data + sizeof(struct ethhdr)); 30 | bpf_trace_printk(msg, sizeof(msg), bpf_ntohl(ip->saddr), len); 31 | } 32 | return TC_ACT_OK; 33 | } 34 | 35 | char __license[] SEC("license") = "GPL"; 36 | -------------------------------------------------------------------------------- /ebpf-pod-network-stats/systemd_version/bpf_network_stats_maps.h: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-2.0 2 | // Author: Vinay Kulkarni <@vinaykul> 3 | 4 | #ifndef __BFP_NETSTATS_H 5 | #define __BFP_NETSTATS_H 6 | 7 | struct tx_net_stats_key_t { 8 | __u32 saddr; 9 | } __attribute__((packed, aligned(4))); 10 | 11 | struct tx_net_stats_t { 12 | __u64 tx_bytes; 13 | __u64 tx_pkts; 14 | } __attribute__((packed, aligned(8))); 15 | 16 | #endif /* __BFP_NETSTATS_H */ 17 | -------------------------------------------------------------------------------- /ebpf-pod-network-stats/systemd_version/build-ebpf-netstats-attach-img-arm64.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -x 2 | 3 | make clean 4 | docker rmi -f skiibum/ebpf-netstats-attach-arm64:poc 5 | 6 | make all 7 | docker image build -t skiibum/ebpf-netstats-attach-arm64:poc -f ebpf-network-stats-attach.Dockerfile . 8 | -------------------------------------------------------------------------------- /ebpf-pod-network-stats/systemd_version/ebpf-network-stats-attach.Dockerfile: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: MIT 2 | # Copyright (c) 2022 The Authors. 3 | 4 | # Authors: Vinay Kulkarni <@vinaykul> 5 | 6 | # Permission is hereby granted, free of charge, to any person obtaining a copy 7 | # of this software and associated documentation files (the "Software"), to deal 8 | # in the Software without restriction, including without limitation the rights 9 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | # copies of the Software, and to permit persons to whom the Software is 11 | # furnished to do so, subject to the following conditions:The above copyright 12 | # notice and this permission notice shall be included in all copies or 13 | # substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", 14 | # WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 15 | # TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 16 | # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE 17 | # FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 18 | # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR 19 | # THE USE OR OTHER DEALINGS IN THE SOFTWARE. 20 | 21 | FROM ubuntu:20.04 22 | 23 | RUN apt-get update -y 24 | RUN apt-get install -y bpfcc-tools bpftrace python3 python3-pyroute2 25 | 26 | #TODO: Replace this demo bpf_network_stats.o with desired (real) eBPF stats program 27 | COPY obj/bpf_network_stats.o /obj/ 28 | COPY attach_ebpf_stats_prog.sh attach_ebpf_stats_prog.py init-container.sh launch-pod-network-setup-bpftrace.sh / 29 | 30 | CMD /launch-pod-network-setup-bpftrace.sh 31 | -------------------------------------------------------------------------------- /ebpf-pod-network-stats/systemd_version/init-container.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -xe 2 | 3 | apt-get update -y 4 | apt-get install -y linux-headers-$(uname -r) 5 | -------------------------------------------------------------------------------- /ebpf-pod-network-stats/systemd_version/launch-pod-network-setup-bpftrace.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -xe 2 | 3 | # 4 | # NOTE: Currently, we have a limitation - we need debug version of containerd 5 | # To build debug version of containerd: 6 | # git clone containerd/containerd 7 | # cd containerd 8 | # 9 | # GODEBUG=1 make all 10 | # "] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | anyhow = "1.0" 9 | libbpf-rs = { path = "../libbpf-rs/libbpf-rs" } 10 | libc = "0.2" 11 | plain = "0.2" 12 | kube = { version = "0.75.0", features = ["runtime", "derive"] } 13 | k8s-openapi = { version = "0.16.0", features = ["v1_25"] } 14 | tokio-util = "0.7.0" 15 | assert-json-diff = "2.0.1" 16 | validator = { version = "0.16.0", features = ["derive"] } 17 | futures = "0.3.17" 18 | jsonpath_lib = "0.3.0" 19 | serde = { version = "1.0.130", features = ["derive"] } 20 | serde_json = "1.0.68" 21 | serde_yaml = "0.8.21" 22 | tokio = { version = "1.14.0", features = ["full"] } 23 | either = "1.6.1" 24 | schemars = "0.8.6" 25 | static_assertions = "1.1.0" 26 | tar = "0.4.37" 27 | tracing = "0.1.29" 28 | tracing-subscriber = "0.3.3" 29 | warp = { version = "0.3", default-features = false, features = ["tls"] } 30 | http = "0.2.5" 31 | json-patch = "0.2.6" 32 | tower = { version = "0.4.6", features = ["limit"] } 33 | tower-http = { version = "0.3.2", features = ["trace", "decompression-gzip"] } 34 | hyper = { version = "0.14.13", features = ["client", "http1", "stream", "tcp"] } 35 | thiserror = "1.0.29" 36 | backoff = "0.4.0" 37 | clap = { version = "4.0", default-features = false, features = ["std", "cargo", "derive"] } 38 | edit = "0.1.3" 39 | tokio-stream = { version = "0.1.9", features = ["net"] } 40 | you-can = "0.0.14" 41 | 42 | [build-dependencies] 43 | libbpf-cargo = { path = "../libbpf-rs/libbpf-cargo" } 44 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/ebpf-pod-resize-libbpf-co-re/Makefile: -------------------------------------------------------------------------------- 1 | # Author: Vinay Kulkarni <@vinaykul> 2 | 3 | all: skel 4 | cargo build 5 | cp src/get-podns-podname-ctrname.sh target/debug/ 6 | cp src/patch-pod-resources.sh target/debug/ 7 | 8 | bpf: vmlinux 9 | cargo libbpf build 10 | 11 | skel: bpf 12 | cargo libbpf gen 13 | 14 | vmlinux: 15 | bpftool btf dump file /sys/kernel/btf/vmlinux format c > ./src/bpf/vmlinux.h 16 | 17 | clean: 18 | cargo clean 19 | rm -f src/bpf/*.rs 20 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/ebpf-pod-resize-libbpf-co-re/build-ebpf-pod-resize-co-re-docker-img.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -x 2 | 3 | make clean && make all 4 | 5 | docker rmi -f skiibum/ebpf-pod-resize-co-re:demo 6 | docker image build -t skiibum/ebpf-pod-resize-co-re:demo -f ebpf-pod-resize-co-re.Dockerfile . 7 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/ebpf-pod-resize-libbpf-co-re/build.rs: -------------------------------------------------------------------------------- 1 | use libbpf_cargo::SkeletonBuilder; 2 | use std::{env, path::PathBuf}; 3 | 4 | const SRC: &str = "src/bpf/podsnoop.bpf.c"; 5 | 6 | fn main() { 7 | let mut out = 8 | PathBuf::from(env::var_os("OUT_DIR").expect("OUT_DIR must be set in build script")); 9 | out.push("podsnoop.skel.rs"); 10 | SkeletonBuilder::new() 11 | .source(SRC) 12 | .build_and_generate(&out) 13 | .unwrap(); 14 | println!("cargo:rerun-if-changed={}", SRC); 15 | } 16 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/ebpf-pod-resize-libbpf-co-re/crictl.yaml: -------------------------------------------------------------------------------- 1 | runtime-endpoint: unix:///containerd/containerd.sock 2 | image-endpoint: unix:///containerd/containerd.sock 3 | timeout: 2 4 | debug: false 5 | pull-image-on-create: false 6 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/ebpf-pod-resize-libbpf-co-re/ebpf-pod-resize-co-re.Dockerfile: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: MIT 2 | # Copyright (c) 2022 The Authors. 3 | 4 | # Authors: Vinay Kulkarni <@vinaykul> 5 | 6 | # Permission is hereby granted, free of charge, to any person obtaining a copy 7 | # of this software and associated documentation files (the "Software"), to deal 8 | # in the Software without restriction, including without limitation the rights 9 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | # copies of the Software, and to permit persons to whom the Software is 11 | # furnished to do so, subject to the following conditions:The above copyright 12 | # notice and this permission notice shall be included in all copies or 13 | # substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", 14 | # WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 15 | # TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 16 | # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE 17 | # FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 18 | # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR 19 | # THE USE OR OTHER DEALINGS IN THE SOFTWARE. 20 | 21 | FROM ubuntu:22.04 22 | RUN apt-get update -y && apt-get upgrade -y 23 | RUN apt-get install -y apt-utils sudo libelf1 vim jq curl apt-transport-https gnupg 24 | RUN curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add - 25 | RUN echo "deb https://apt.kubernetes.io/ kubernetes-xenial main" | sudo tee /etc/apt/sources.list.d/kubernetes.list 26 | RUN apt-get update -y && apt-get install -y cri-tools kubectl 27 | COPY crictl.yaml /etc/ 28 | COPY src/get-podns-podname-ctrname.sh src/patch-pod-resources.sh target/debug/podsnoop / 29 | CMD /podsnoop 30 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/ebpf-pod-resize-libbpf-co-re/ebpf-pod-resize-co-re.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ServiceAccount 3 | metadata: 4 | name: ebpf-pod-resize-demo 5 | namespace: kube-system 6 | --- 7 | apiVersion: rbac.authorization.k8s.io/v1 8 | kind: ClusterRoleBinding 9 | metadata: 10 | name: ebpf-pod-resize-demo 11 | namespace: kube-system 12 | roleRef: 13 | apiGroup: rbac.authorization.k8s.io 14 | kind: ClusterRole 15 | name: cluster-admin 16 | subjects: 17 | - kind: ServiceAccount 18 | name: ebpf-pod-resize-demo 19 | namespace: kube-system 20 | --- 21 | apiVersion: apps/v1 22 | kind: DaemonSet 23 | metadata: 24 | name: ebpf-pod-resize-demo 25 | namespace: kube-system 26 | labels: 27 | k8s-app: ebpf-pod-resize-demo 28 | spec: 29 | selector: 30 | matchLabels: 31 | name: ebpf-pod-resize-demo 32 | template: 33 | metadata: 34 | labels: 35 | name: ebpf-pod-resize-demo 36 | spec: 37 | serviceAccountName: ebpf-pod-resize-demo 38 | terminationGracePeriodSeconds: 30 39 | tolerations: 40 | - key: node-role.kubernetes.io/control-plane 41 | operator: Exists 42 | effect: NoSchedule 43 | - key: node-role.kubernetes.io/master 44 | operator: Exists 45 | effect: NoSchedule 46 | hostNetwork: true 47 | hostPID: true 48 | hostIPC: true 49 | volumes: 50 | - name: sys-volume 51 | hostPath: 52 | path: /sys 53 | - name: var-run-containerd-volume 54 | hostPath: 55 | path: /var/run/containerd 56 | containers: 57 | - name: ebpf-pod-resize-co-re 58 | image: skiibum/ebpf-pod-resize-co-re:demo 59 | imagePullPolicy: IfNotPresent 60 | command: ["/podsnoop"] 61 | env: 62 | - name: MY_NODE_NAME 63 | value: "127.0.0.1" 64 | resources: 65 | requests: 66 | cpu: 500m 67 | memory: 400Mi 68 | volumeMounts: 69 | - name: sys-volume 70 | mountPath: /sys 71 | readOnly: false 72 | - name: var-run-containerd-volume 73 | mountPath: /containerd 74 | readOnly: true 75 | securityContext: 76 | allowPrivilegeEscalation: true 77 | capabilities: 78 | add: ["SYS_ADMIN", "SYS_RESOURCE", "BPF", "PERFMON"] 79 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/ebpf-pod-resize-libbpf-co-re/kube-build-pod.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Pod 3 | metadata: 4 | name: kube-build-pod 5 | annotations: 6 | "ebpf-resize": '{ 7 | "cname": "kube-build-ctr", 8 | "commands": ["make"], 9 | "resize": "{\"requests\":{\"memory\":\"5Gi\"},\"limits\":{\"memory\":\"5Gi\"}}" 10 | }' 11 | spec: 12 | containers: 13 | - name: kube-build-ctr 14 | image: skiibum/kube-build:v1.25 15 | imagePullPolicy: IfNotPresent 16 | command: ["tail", "-f", "/dev/null"] 17 | resources: 18 | limits: 19 | cpu: "5" 20 | memory: "50Mi" 21 | requests: 22 | cpu: "4" 23 | memory: "50Mi" 24 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/ebpf-pod-resize-libbpf-co-re/src/bpf/podsnoop.h: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-2.0 2 | // Author: Vinay Kulkarni <@vinaykul> 3 | 4 | #ifndef __PODSNOOP_H 5 | #define __PODSNOOP_H 6 | 7 | #define BUF_SIZE 32 8 | 9 | struct pod_command { 10 | char cmd[BUF_SIZE]; 11 | }; 12 | 13 | struct pod_exec_event { 14 | u64 cgroup_id; 15 | u32 cgroup_pid; 16 | u8 cgroup_cmd[BUF_SIZE]; 17 | }; 18 | 19 | #endif /* __PODSNOOP_H */ 20 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/ebpf-pod-resize-libbpf-co-re/src/get-podns-podname-ctrname.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cgroup_id=$1 4 | cgroup_pid=$2 5 | 6 | pod_name=$(nsenter -t ${cgroup_pid} -u hostname 2>/dev/null) 7 | if [ -z "${pod_name}" ]; then 8 | exit 2 9 | fi 10 | 11 | ctr_id=$(basename $(find /sys/fs/cgroup -inum ${cgroup_id} | grep kubepods | grep unified) 2>/dev/null) 12 | if [ -z "${ctr_id}" ]; then 13 | ctr_id=$(basename $(find /sys/fs/cgroup -inum ${cgroup_id} | grep kubepods) 2>/dev/null) 14 | fi 15 | if [ -z "${ctr_id}" ]; then 16 | exit 2 17 | fi 18 | 19 | pod_ns=$(crictl inspect ${ctr_id} | jq '.status.labels."io.kubernetes.pod.namespace"' 2>/dev/null) 20 | if [ -z "${pod_ns}" ]; then 21 | exit 2 22 | fi 23 | 24 | ctr_name=$(crictl inspect ${ctr_id} | jq .status.metadata.name 2>/dev/null) 25 | if [ -z "${ctr_name}" ]; then 26 | exit 2 27 | fi 28 | 29 | printf '{"pod_ns": %s, "pod_name": "%s", "container_name": %s}' ${pod_ns} ${pod_name} ${ctr_name} 30 | exit 0 31 | 32 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/ebpf-pod-resize-libbpf-co-re/src/patch-pod-resources.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | pod_name=$1 4 | container_name=$2 5 | resources=$3 6 | pod_ns=${4:default} 7 | 8 | patch_str="{\"spec\":{\"containers\":[{\"name\":\"${container_name}\",\"resources\":${resources}}]}}" 9 | kubectl -n ${pod_ns} patch pod ${pod_name} --patch ${patch_str} 10 | exit 0 11 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/.devcontainer/README.md: -------------------------------------------------------------------------------- 1 | # `kube-rs` Development container 2 | 3 | This directory provides a [_devcontainer_][dc] configuration that configures a 4 | reproducible development environment for this project. This base image should 5 | contain only the bare necessities to get up and running with `kube-rs`. 6 | Customizations should be made in per-user configuration. 7 | 8 | ## Usage 9 | 10 | Install the VS Code [Remote Development extension pack][remote-exts] after which 11 | VS Code should build (first use) then run the container in the background. 12 | 13 | ## Docker 14 | 15 | This configuration currently uses the parent host's Docker daemon (rather than 16 | running a separate docker daemon within in the container). It creates 17 | devcontainers on the host network so it's easy to use k3d clusters hosted in the 18 | parent host's docker daemon. 19 | 20 | ## Personalizing 21 | 22 | This configuration is supposed to provide a minimal setup without catering to 23 | any one developer's personal tastes. Devcontainers can be extended with per-user 24 | configuration. 25 | 26 | To add your own extensions to the devcontainer, configure default extensions in 27 | your VS Code settings: 28 | 29 | ```jsonc 30 | "remote.containers.defaultExtensions": [ 31 | "eamodio.gitlens", 32 | "GitHub.copilot", 33 | "GitHub.vscode-pull-request-github", 34 | "mutantdino.resourcemonitor", 35 | ], 36 | ``` 37 | 38 | Furthermore, you can configure a [_dotfiles_ repository][df] to perform 39 | customizations with a VS Code setting like: 40 | 41 | ```jsonc 42 | "dotfiles.repository": "https://github.com/olix0r/dotfiles.git", 43 | ``` 44 | 45 | [dc]: https://code.visualstudio.com/docs/remote/containers 46 | [df]: https://dotfiles.github.io/ 47 | [remote-exts]: https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.vscode-remote-extensionpack 48 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "kube-dev", 3 | 4 | // TODO publish a version of this image to the organization's package registry and then comment 5 | // out the `dockerFile` configuration. 6 | //"image": "ghcr.io/kube-rs/dev:v1", 7 | "dockerFile": "./Dockerfile", 8 | 9 | // These extensions are loaded for all users by default. 10 | "extensions": [ 11 | "rust-lang.rust-analyzer", 12 | "NathanRidley.autotrim", 13 | "samverschueren.final-newline", 14 | "tamasfe.even-better-toml", 15 | "vadimcn.vscode-lldb", 16 | // "zxh404.vscode-proto3" 17 | ], 18 | 19 | // Set project-specific VS Code settings here. 20 | "settings": { 21 | // Prevent conflicting versions of the Kubernetes API from being loaded. 22 | "rust-analyzer.cargo.allFeatures": false, 23 | }, 24 | 25 | // // `make clippy` and `make lint` require the nightly toolchain, so install 26 | // // it as the container is created. 27 | // "postCreateCommand": "rustup toolcahin add nightly && rustup default nightly", 28 | 29 | // Configure docker. 30 | "runArgs": [ 31 | "--init", 32 | // Use the host network so we can access k3d, etc. 33 | "--net=host", 34 | // For lldb 35 | "--cap-add=SYS_PTRACE", 36 | "--security-opt=seccomp=unconfined" 37 | ], 38 | "overrideCommand": false, 39 | "remoteUser": "code", 40 | 41 | // Mount the parent host's docker socket into the container. 42 | "mounts": [ 43 | "source=/var/run/docker.sock,target=/var/run/docker-host.sock,type=bind" 44 | ] 45 | } 46 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/.devcontainer/scurl: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # Run `curl` with flags to ensure transport security.` 4 | 5 | exec curl --proto '=https' --tlsv1.3 -vsSfL $@ 6 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [clux] 4 | #patreon: # Replace with a single Patreon username 5 | #open_collective: # Replace with a single Open Collective username 6 | #ko_fi: # Replace with a single Ko-fi username 7 | #tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | #community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | #liberapay: # Replace with a single Liberapay username 10 | #issuehunt: # Replace with a single IssueHunt username 11 | #otechie: # Replace with a single Otechie username 12 | #custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: true 2 | contact_links: 3 | - name: 🙋🏾 Question 4 | url: https://github.com/kube-rs/kube-rs/discussions/new 5 | about: Use this link to submit your ❓ to GitHub Discussions. 6 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/.github/ISSUE_TEMPLATE/feature_request.yml: -------------------------------------------------------------------------------- 1 | name: "🚀 Feature Request" 2 | description: "I have a specific suggestion for Kube!" 3 | labels: ["enhancement"] 4 | body: 5 | - type: markdown 6 | attributes: 7 | value: Thanks for taking the time to suggest a new feature! Please fill out this form as completely as possible. 8 | 9 | - type: dropdown 10 | attributes: 11 | label: Would you like to work on this feature? 12 | description: | 13 | **NOTE**: Let us know if you would like to submit a PR for this. We are more than happy to help you through the process. 14 | options: 15 | - "yes" 16 | - "no" 17 | - "maybe" 18 | 19 | - type: textarea 20 | attributes: 21 | label: What problem are you trying to solve? 22 | description: | 23 | A concise description of what the problem is. 24 | placeholder: | 25 | I have an issue when [...] 26 | validations: 27 | required: true 28 | 29 | - type: textarea 30 | attributes: 31 | label: Describe the solution you'd like 32 | validations: 33 | required: true 34 | 35 | - type: textarea 36 | attributes: 37 | label: Describe alternatives you've considered 38 | validations: 39 | required: true 40 | 41 | - type: textarea 42 | attributes: 43 | label: Documentation, Adoption, Migration Strategy 44 | description: | 45 | If you can, explain how users will be able to use this and how it might be documented. Maybe a mock-up? 46 | 47 | - type: dropdown 48 | attributes: 49 | label: Target crate for feature 50 | description: | 51 | **NOTE**: Select the crate(s) you think should be responsible for the feature 52 | multiple: true 53 | options: 54 | - kube-core 55 | - kube-client 56 | - kube-derive 57 | - kube-runtime 58 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 8 | 9 | ## Motivation 10 | 11 | 15 | 16 | ## Solution 17 | 18 | 21 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/.github/codecov.yml: -------------------------------------------------------------------------------- 1 | comment: 2 | require_changes: no 3 | layout: "diff,files" 4 | 5 | #flags: 6 | # kube: 7 | # paths: ["kube"] 8 | # core: 9 | # paths: ["kube-core"] 10 | # client: 11 | # paths: ["kube-client"] 12 | # runtime: 13 | # paths: ["kube-runtime"] 14 | # derive: 15 | # paths: ["kube-derive"] 16 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "github-actions" 4 | directory: "/" 5 | schedule: 6 | interval: "weekly" 7 | labels: 8 | - "dependencies" 9 | 10 | - package-ecosystem: "cargo" 11 | directory: "/" 12 | schedule: 13 | interval: "weekly" 14 | labels: 15 | - "dependencies" 16 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/.github/release.yml: -------------------------------------------------------------------------------- 1 | # https://docs.github.com/en/repositories/releasing-projects-on-github/automatically-generated-release-notes 2 | changelog: 3 | exclude: 4 | labels: [changelog-exclude] 5 | categories: 6 | # Types from https://keepachangelog.com/en/1.0.0/ 7 | # `Added` for new features 8 | - title: Added 9 | labels: [changelog-add] 10 | # `Changed` for changes in existing functionality 11 | - title: Changed 12 | labels: [changelog-change] 13 | # `Deprecated` for soon-to-be removed features 14 | - title: Deprecated 15 | labels: [changelog-deprecate] 16 | # `Removed` for now removed features 17 | - title: Removed 18 | labels: [changelog-remove] 19 | # `Fixed` for any bug fixes 20 | - title: Fixed 21 | labels: [changelog-fix] 22 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/.github/workflows/audit.yml: -------------------------------------------------------------------------------- 1 | name: audit 2 | on: 3 | schedule: 4 | # Run at 00:00 UTC every day 5 | - cron: '0 0 * * *' 6 | 7 | jobs: 8 | audit: 9 | if: ${{ github.repository_owner == 'kube-rs' }} 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | - uses: actions-rs/toolchain@v1 14 | with: 15 | toolchain: stable 16 | profile: minimal 17 | override: true 18 | - uses: actions-rs/audit-check@v1 19 | with: 20 | token: ${{ secrets.GITHUB_TOKEN }} 21 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/.github/workflows/clippy.yml: -------------------------------------------------------------------------------- 1 | name: clippy 2 | on: 3 | pull_request: 4 | jobs: 5 | clippy_nightly: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@v2 9 | - uses: actions-rs/toolchain@v1 10 | with: 11 | toolchain: nightly 12 | components: clippy 13 | override: true 14 | - uses: actions-rs/clippy-check@v1 15 | with: 16 | args: "--workspace" 17 | token: ${{ secrets.GITHUB_TOKEN }} 18 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/.github/workflows/coverage.yml: -------------------------------------------------------------------------------- 1 | name: coverage 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | 9 | jobs: 10 | tarpaulin-codecov: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Checkout 14 | uses: actions/checkout@v2 15 | - name: Install stable toolchain 16 | uses: actions-rs/toolchain@v1 17 | with: 18 | toolchain: stable 19 | override: true 20 | - uses: Swatinem/rust-cache@v1 21 | - uses: AbsaOSS/k3d-action@v2 22 | name: "Create Single Cluster" 23 | with: 24 | cluster-name: "test-cluster-1" 25 | args: >- 26 | --agents 1 27 | --image docker.io/rancher/k3s:v1.22.4-k3s1 28 | --k3s-arg "--no-deploy=traefik,servicelb,metrics-server@server:*" 29 | - name: Run cargo-tarpaulin 30 | uses: actions-rs/tarpaulin@v0.1 31 | with: 32 | version: '0.18.5' 33 | out-type: Xml 34 | - uses: codecov/codecov-action@v3 35 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/.github/workflows/devcontainer.yml: -------------------------------------------------------------------------------- 1 | name: devcontainer 2 | 3 | # When a pull request is opened that changes the Devcontainer configuration, 4 | # ensure that the container continues to build properly. 5 | on: 6 | pull_request: 7 | paths: 8 | - .devcontainer/** 9 | 10 | permissions: 11 | contents: read 12 | 13 | jobs: 14 | build: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v2 18 | - run: docker build .devcontainer 19 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: lint 2 | on: 3 | pull_request: 4 | 5 | jobs: 6 | cargo-deny: 7 | name: cargo deny 8 | runs-on: ubuntu-latest 9 | strategy: 10 | matrix: 11 | checks: 12 | - advisories 13 | - bans licenses sources 14 | 15 | # Prevent sudden announcement of a new advisory from failing ci: 16 | continue-on-error: ${{ matrix.checks == 'advisories' }} 17 | 18 | steps: 19 | - uses: actions/checkout@v2 20 | - uses: EmbarkStudios/cargo-deny-action@v1 21 | with: 22 | command: check ${{ matrix.checks }} 23 | 24 | rustfmt: 25 | name: rustfmt 26 | runs-on: ubuntu-latest 27 | steps: 28 | - uses: actions/checkout@v2 29 | - uses: actions-rs/toolchain@v1.0.7 30 | with: 31 | profile: minimal 32 | toolchain: nightly 33 | components: rustfmt 34 | override: true 35 | - name: Run rustfmt 36 | id: rustfmt 37 | run: rustfmt +nightly --edition 2018 --check $(find . -type f -iname *.rs) 38 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: release 2 | 3 | on: 4 | push: 5 | tags: 6 | - '[0-9]+.[0-9]+.[0-9]+' 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | if: ${{ github.repository_owner == 'kube-rs' }} 12 | steps: 13 | - name: Checkout 14 | uses: actions/checkout@v2 15 | - name: Generate release info 16 | run: ./scripts/release-gh.sh 17 | - name: Release 18 | uses: softprops/action-gh-release@v1 19 | env: 20 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 21 | with: 22 | # Note: body is pre-pended to generated release notes 23 | body_path: release.txt 24 | # github generated notes based on changelog-* tags 25 | # the format of this is configured in the github native: .github/release.yml 26 | generate_release_notes: true 27 | draft: true 28 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/.github/workflows/rustfmt.yml: -------------------------------------------------------------------------------- 1 | # When pushed to main, run `cargo +nightly fmt --all` and open a PR. 2 | name: rustfmt 3 | on: 4 | push: 5 | # Limit to `main` because this action creates a PR 6 | branches: 7 | - main 8 | jobs: 9 | rustfmt_nightly: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Checkout sources 13 | uses: actions/checkout@v2 14 | 15 | - name: Install nightly toolchain with rustfmt available 16 | uses: actions-rs/toolchain@v1 17 | with: 18 | toolchain: nightly 19 | override: true 20 | components: rustfmt 21 | 22 | - run: rustfmt +nightly --edition 2018 $(find . -type f -iname *.rs) 23 | 24 | - name: Create Pull Request 25 | uses: peter-evans/create-pull-request@v4 26 | with: 27 | commit-message: rustfmt 28 | signoff: true 29 | title: rustfmt 30 | body: | 31 | Changes from `rustfmt +nightly --edition 2018 $(find . -type f -iname *.rs)`. 32 | branch: rustfmt 33 | # Delete branch when merged 34 | delete-branch: true 35 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/.gitignore: -------------------------------------------------------------------------------- 1 | .vscode/ 2 | .idea/ 3 | /target 4 | **/*.rs.bk 5 | Cargo.lock 6 | e2e/boot 7 | e2e/job 8 | examples/admission-controller-tls* 9 | examples/admission_extfile.cnf 10 | examples/ca.* 11 | tarpaulin-report.html 12 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | default-members = ["kube"] 3 | members = [ 4 | "kube", 5 | "kube-client", 6 | "kube-core", 7 | "kube-derive", 8 | "kube-runtime", 9 | 10 | # internal 11 | "e2e", 12 | "examples", 13 | ] 14 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | We provide security updates for the two most recent minor versions released on `crates.io`. 6 | 7 | For example, if `0.70.1` is the most recent stable version, we will address security updates for `0.69` and later. 8 | Once `0.71.1` is released, we will no longer provide updates for `0.69` releases. 9 | 10 | ## Reporting a Vulnerability 11 | 12 | To report a security problem in Kube-rs, please contact at least two [maintainers](https://kube.rs/maintainers/) 13 | 14 | These people will help diagnose the severity of the issue and determine how to address the issue. 15 | Issues deemed to be non-critical will be filed as GitHub issues. 16 | Critical issues will receive immediate attention and be fixed as quickly as possible. 17 | 18 | ## Security Advisories 19 | 20 | When serious security problems in Kube-rs are discovered and corrected, we issue a security advisory, describing the problem and containing a pointer to the fix. 21 | 22 | These are announced the [RustSec Advisory Database](https://github.com/rustsec/advisory-db), to our github issues under the label `critical`, as well as discord and other primary communication channels. 23 | 24 | Security issues are fixed as soon as possible, and the fixes are propagated to the stable branches as fast as possible. However, when a vulnerability is found during a code audit, or when several other issues are likely to be spotted and fixed in the near future, the security team may delay the release of a Security Advisory, so that one unique, comprehensive Security Advisory covering several vulnerabilities can be issued. 25 | Communication with vendors and other distributions shipping the same code may also cause these delays. 26 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/clippy.toml: -------------------------------------------------------------------------------- 1 | blacklisted-names = [] 2 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/code-of-conduct.md: -------------------------------------------------------------------------------- 1 | # Community Code of Conduct 2 | 3 | kube-rs follows the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/master/code-of-conduct.md). 4 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/e2e/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "e2e" 3 | version = "0.1.0" 4 | authors = ["clux "] 5 | publish = false 6 | edition = "2021" 7 | license = "Apache-2.0" 8 | 9 | [package.metadata.release] 10 | release = false 11 | 12 | [[bin]] 13 | name = "job" 14 | path = "job.rs" 15 | 16 | [[bin]] 17 | name = "boot" 18 | path = "boot.rs" 19 | 20 | [features] 21 | latest = ["k8s-openapi/v1_25"] 22 | mk8sv = ["k8s-openapi/v1_20"] 23 | rustls = ["kube/rustls-tls"] 24 | openssl = ["kube/openssl-tls"] 25 | 26 | [dependencies] 27 | anyhow = "1.0.44" 28 | tracing = "0.1.29" 29 | tracing-subscriber = "0.3.3" 30 | futures = "0.3.17" 31 | kube = { path = "../kube", version = "^0.75.0", default-features = false, features = ["client", "runtime", "ws", "admission", "gzip"] } 32 | k8s-openapi = { version = "0.16.0", default-features = false } 33 | serde_json = "1.0.68" 34 | tokio = { version = "1.14.0", features = ["full"] } 35 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/e2e/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM gcr.io/distroless/static:nonroot 2 | COPY --chown=nonroot:nonroot ./job /app/ 3 | ENTRYPOINT ["/app/job"] 4 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/e2e/README.md: -------------------------------------------------------------------------------- 1 | # E2E tests 2 | 3 | Small set of tests complete e2e flows, like local vs. in-cluster configs, incluster namespace defaulting, and non-standard feature flags that are hard to test within kube. 4 | 5 | **[You probably do not want to make an E2E test](../CONTRIBUTING.md#test-guidelines)**. 6 | 7 | ## boot 8 | 9 | Simple executable that lists pods. 10 | 11 | Intended as a compilation target to ensure kube builds with any k8s-openapi version feature selection greater than or equal to our MK8SV. 12 | 13 | ## job 14 | 15 | A more advanced application that is containerised and deployed into a cluster on CI during the `e2e` job via [our ci workflow](https://github.com/kube-rs/kube/blob/2b5e4ad788366125448ad40eadaf68cf9ceeaf31/.github/workflows/ci.yml#L58-L107). 16 | 17 | Functionally equivalent to the `job_api` example. Creates a noop job, waits for it to complete, then deletes it. 18 | 19 | Intended as a safety mechanism to ensure in-cluster authenication is working, not hanging, and its minimal work is is verifiable out-of-band. 20 | 21 | ## Testing Strategy 22 | 23 | ### job 24 | 25 | Compile the `job` binary (via [muslrust](https://github.com/clux/muslrust)) and put the it into a [distroless:static](https://github.com/GoogleContainerTools/distroless) image. 26 | 27 | Then, import the image into `k3d` (to avoid pushing), and apply the [test yaml](./deployment.yaml). We can observe the job completes. 28 | 29 | Running these locally requires a local cluster. Use `just k3d` to start a simple one. 30 | 31 | Then, run `just e2e-incluster openssl,latest` or `just e2e-incluster rustls,latest`. 32 | 33 | ### boot 34 | 35 | Build the `boot` bin against various `k8s-openapi` version features, and check that it runs. Uses local auth; not dockerised. 36 | 37 | To run this with all feature combinations combinations, run `just e2e-mink8s`. 38 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/e2e/boot.rs: -------------------------------------------------------------------------------- 1 | use k8s_openapi::api::core::v1::Pod; 2 | use kube::{Api, Client, ResourceExt}; 3 | 4 | #[tokio::main] 5 | async fn main() -> anyhow::Result<()> { 6 | tracing_subscriber::fmt::init(); 7 | let client = Client::try_default().await?; 8 | let pods: Api = Api::all(client); 9 | for p in pods.list(&Default::default()).await? { 10 | tracing::info!("Found pod {}", p.name_any()); 11 | } 12 | Ok(()) 13 | } 14 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/e2e/deployment.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: v1 3 | kind: Namespace 4 | metadata: 5 | name: apps 6 | 7 | --- 8 | # Scoped service account 9 | apiVersion: v1 10 | kind: ServiceAccount 11 | metadata: 12 | name: e2e 13 | namespace: apps 14 | automountServiceAccountToken: true 15 | 16 | --- 17 | # Access for the service account 18 | kind: Role 19 | apiVersion: rbac.authorization.k8s.io/v1 20 | metadata: 21 | namespace: apps 22 | name: e2e-role 23 | rules: 24 | - apiGroups: 25 | - batch 26 | resources: 27 | - jobs 28 | verbs: 29 | - create 30 | - get 31 | - watch 32 | - list 33 | - delete 34 | 35 | --- 36 | # Binding the role to the account in apps 37 | kind: RoleBinding 38 | apiVersion: rbac.authorization.k8s.io/v1 39 | metadata: 40 | name: e2e-binding 41 | namespace: apps 42 | subjects: 43 | - kind: ServiceAccount 44 | name: e2e 45 | roleRef: 46 | kind: Role 47 | name: e2e-role 48 | apiGroup: rbac.authorization.k8s.io 49 | 50 | --- 51 | # Main job 52 | apiVersion: batch/v1 53 | kind: Job 54 | metadata: 55 | name: e2e 56 | namespace: apps 57 | labels: 58 | app: e2e 59 | spec: 60 | template: 61 | metadata: 62 | labels: 63 | app: e2e 64 | spec: 65 | serviceAccountName: e2e 66 | restartPolicy: Never 67 | containers: 68 | - name: e2e 69 | image: "clux/kube-e2e:latest" 70 | imagePullPolicy: IfNotPresent 71 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/e2e/job.rs: -------------------------------------------------------------------------------- 1 | use k8s_openapi::api::batch::v1::Job; 2 | use kube::{ 3 | api::{Api, DeleteParams, PostParams}, 4 | runtime::wait::{await_condition, conditions}, 5 | Client, 6 | }; 7 | use tracing::info; 8 | 9 | #[tokio::main] 10 | async fn main() -> anyhow::Result<()> { 11 | tracing_subscriber::fmt::init(); 12 | let client = Client::try_default().await?; 13 | let jobs: Api = Api::default_namespaced(client); 14 | 15 | info!("Creating job"); 16 | let name = "empty-job"; 17 | let data = serde_json::from_value(serde_json::json!({ 18 | "apiVersion": "batch/v1", 19 | "kind": "Job", 20 | "metadata": { 21 | "name": name, 22 | }, 23 | "spec": { 24 | "template": { 25 | "metadata": { 26 | "name": "empty-job-pod" 27 | }, 28 | "spec": { 29 | "containers": [{ 30 | "name": "empty", 31 | "image": "alpine:latest" 32 | }], 33 | "restartPolicy": "Never", 34 | } 35 | } 36 | } 37 | }))?; 38 | jobs.create(&PostParams::default(), &data).await?; 39 | 40 | info!("Waiting for job to complete"); 41 | let cond = await_condition(jobs.clone(), name, conditions::is_job_completed()); 42 | let _ = tokio::time::timeout(std::time::Duration::from_secs(20), cond).await?; 43 | 44 | info!("Cleaning up job record"); 45 | jobs.delete(name, &DeleteParams::background()).await?; 46 | Ok(()) 47 | } 48 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/admission_controller.yaml.tpl: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: admissionregistration.k8s.io/v1beta1 3 | kind: MutatingWebhookConfiguration 4 | metadata: 5 | name: admission-controller-demo 6 | webhooks: 7 | - name: foo-admission.default.svc 8 | # Optionally restrict events from namespaces with a specific label. 9 | # namespaceSelector: 10 | # matchLabels: 11 | # some-label: "true" 12 | clientConfig: 13 | caBundle: "${CA_PEM_B64}" 14 | url: "https://${PRIVATE_IP}:8443/mutate" 15 | # For controllers behind k8s services, use the format below instead of a url 16 | #service: 17 | # name: foo-admission 18 | # namespace: default 19 | # path: "/mutate" 20 | rules: 21 | - operations: ["CREATE", "UPDATE"] 22 | apiGroups: ["clux.dev"] 23 | apiVersions: ["v1"] 24 | resources: ["foos"] 25 | failurePolicy: Fail 26 | admissionReviewVersions: ["v1", "v1beta1"] 27 | sideEffects: None 28 | timeoutSeconds: 5 29 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/admission_ok.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: clux.dev/v1 2 | kind: Foo 3 | metadata: 4 | name: ok 5 | spec: 6 | name: ok 7 | info: this is accepted, and a label is added 8 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/admission_reject.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: clux.dev/v1 2 | kind: Foo 3 | metadata: 4 | name: reject 5 | labels: 6 | illegal: "ohno" 7 | spec: 8 | name: reject 9 | info: this is rejected 10 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/admission_setup.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | 4 | # This script is loosely adapting the TLS setup described in 5 | # https://kubernetes.io/blog/2019/03/21/a-guide-to-kubernetes-admission-controllers/#tls-certificates 6 | # for local development 7 | 8 | # Require: a private ip reachable from your cluster. 9 | # If using k3d to test locally, then probably 10.x.x.x or 192.168.X.X 10 | # When running behind a Service in-cluster; 0.0.0.0 11 | test -n "${ADMISSION_PRIVATE_IP}" 12 | 13 | # Cleanup: Remove old MutatingWebhookConfiguration if exists (immutable) 14 | kubectl delete mutatingwebhookconfiguration admission-controller-demo || true 15 | # If behind a service: 16 | #kubectl -n default delete secret admission-controller-tls || true 17 | 18 | # Get your IP into the cert 19 | echo "subjectAltName = IP:${ADMISSION_PRIVATE_IP}" > admission_extfile.cnf 20 | # Or, if using DNS (e.g. when running behind a service): 21 | #echo "subjectAltName = DNS:admission-controller.default.svc" > admission_extfile.cnf 22 | 23 | # Generate the CA cert and private key 24 | openssl req -nodes -new -x509 \ 25 | -keyout ca.key \ 26 | -out ca.crt -subj "/CN=admission-controller-demo" 27 | 28 | # Generate the private key for the webhook server 29 | openssl genrsa -out admission-controller-tls.key 2048 30 | 31 | # Generate a Certificate Signing Request (CSR) for the private key 32 | # and sign it with the private key of the CA. 33 | openssl req -new -key admission-controller-tls.key \ 34 | -subj "/CN=admission-controller-demo" \ 35 | | openssl x509 -req -CA ca.crt -CAkey ca.key \ 36 | -CAcreateserial -out admission-controller-tls.crt \ 37 | -extfile admission_extfile.cnf 38 | 39 | CA_PEM64="$(openssl base64 -A < ca.crt)" 40 | # shellcheck disable=SC2016 41 | sed -e 's@${CA_PEM_B64}@'"$CA_PEM64"'@g' < admission_controller.yaml.tpl | 42 | sed -e 's@${PRIVATE_IP}@'"$ADMISSION_PRIVATE_IP"'@g' \ 43 | | kubectl create -f - 44 | 45 | # if behind a service: 46 | #kubectl -n default create secret tls admission-controller-tls \ 47 | # --cert admission-controller-tls.crt \ 48 | # --key admission-controller-tls.key 49 | # similar guide: https://www.openpolicyagent.org/docs/v0.11.0/kubernetes-admission-control/ 50 | 51 | # Sanity: 52 | kubectl get mutatingwebhookconfiguration admission-controller-demo -oyaml 53 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/configmapgen_controller_crd.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apiextensions.k8s.io/v1 2 | kind: CustomResourceDefinition 3 | metadata: 4 | name: configmapgenerators.nullable.se 5 | spec: 6 | group: nullable.se 7 | names: 8 | kind: ConfigMapGenerator 9 | plural: configmapgenerators 10 | shortNames: 11 | - cmg 12 | singular: configmapgenerator 13 | scope: Namespaced 14 | versions: 15 | - name: v1 16 | served: true 17 | storage: true 18 | schema: 19 | openAPIV3Schema: 20 | type: object 21 | properties: 22 | spec: 23 | type: object 24 | properties: 25 | content: 26 | type: string 27 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/configmapgen_controller_object.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: nullable.se/v1 2 | kind: ConfigMapGenerator 3 | metadata: 4 | name: foo 5 | spec: 6 | content: Hey! 7 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/crd-baz.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: clux.dev/v1 2 | kind: Foo 3 | metadata: 4 | name: baz 5 | spec: 6 | name: baz 7 | info: this is baz 8 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/crd-qux.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: clux.dev/v1 2 | kind: Foo 3 | metadata: 4 | name: qux 5 | spec: 6 | name: qux 7 | info: this is qux 8 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/custom_client.rs: -------------------------------------------------------------------------------- 1 | // Minimal custom client example. 2 | use k8s_openapi::api::core::v1::Pod; 3 | use tracing::*; 4 | 5 | use kube::{client::ConfigExt, Api, Client, Config, ResourceExt}; 6 | 7 | #[tokio::main] 8 | async fn main() -> anyhow::Result<()> { 9 | tracing_subscriber::fmt::init(); 10 | 11 | let config = Config::infer().await?; 12 | let https = config.openssl_https_connector()?; 13 | let service = tower::ServiceBuilder::new() 14 | .layer(config.base_uri_layer()) 15 | .option_layer(config.auth_layer()?) 16 | .service(hyper::Client::builder().build(https)); 17 | let client = Client::new(service, config.default_namespace); 18 | 19 | let pods: Api = Api::default_namespaced(client); 20 | for p in pods.list(&Default::default()).await? { 21 | info!("{}", p.name_any()); 22 | } 23 | 24 | Ok(()) 25 | } 26 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/custom_client_tls.rs: -------------------------------------------------------------------------------- 1 | // Custom client supporting both openssl-tls and rustls-tls 2 | // Must enable `rustls-tls` feature to run this. 3 | // Run with `USE_RUSTLS=1` to pick rustls. 4 | use k8s_openapi::api::core::v1::Pod; 5 | use tower::ServiceBuilder; 6 | use tracing::*; 7 | 8 | use kube::{client::ConfigExt, Api, Client, Config, ResourceExt}; 9 | 10 | #[tokio::main] 11 | async fn main() -> anyhow::Result<()> { 12 | tracing_subscriber::fmt::init(); 13 | 14 | let config = Config::infer().await?; 15 | 16 | // Pick TLS at runtime 17 | let use_rustls = std::env::var("USE_RUSTLS").map(|s| s == "1").unwrap_or(false); 18 | let client = if use_rustls { 19 | let https = config.rustls_https_connector()?; 20 | let service = ServiceBuilder::new() 21 | .layer(config.base_uri_layer()) 22 | .service(hyper::Client::builder().build(https)); 23 | Client::new(service, config.default_namespace) 24 | } else { 25 | let https = config.openssl_https_connector()?; 26 | let service = ServiceBuilder::new() 27 | .layer(config.base_uri_layer()) 28 | .service(hyper::Client::builder().build(https)); 29 | Client::new(service, config.default_namespace) 30 | }; 31 | 32 | let pods: Api = Api::default_namespaced(client); 33 | for p in pods.list(&Default::default()).await? { 34 | info!("{}", p.name_any()); 35 | } 36 | 37 | Ok(()) 38 | } 39 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/dynamic_api.rs: -------------------------------------------------------------------------------- 1 | //! In this example we will implement something similar to `kubectl get all`. 2 | 3 | use kube::{ 4 | api::{Api, DynamicObject, ResourceExt}, 5 | discovery::{verbs, Discovery, Scope}, 6 | Client, 7 | }; 8 | use tracing::*; 9 | 10 | #[tokio::main] 11 | async fn main() -> anyhow::Result<()> { 12 | tracing_subscriber::fmt::init(); 13 | let client = Client::try_default().await?; 14 | 15 | let discovery = Discovery::new(client.clone()).run().await?; 16 | for group in discovery.groups() { 17 | for (ar, caps) in group.recommended_resources() { 18 | if !caps.supports_operation(verbs::LIST) { 19 | continue; 20 | } 21 | let api: Api = if caps.scope == Scope::Cluster { 22 | Api::all_with(client.clone(), &ar) 23 | } else { 24 | Api::default_namespaced_with(client.clone(), &ar) 25 | }; 26 | 27 | info!("{}/{} : {}", group.name(), ar.version, ar.kind); 28 | 29 | let list = api.list(&Default::default()).await?; 30 | for item in list.items { 31 | let name = item.name_any(); 32 | let ns = item.metadata.namespace.map(|s| s + "/").unwrap_or_default(); 33 | info!("\t\t{}{}", ns, name); 34 | } 35 | } 36 | } 37 | 38 | Ok(()) 39 | } 40 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/dynamic_jsonpath.rs: -------------------------------------------------------------------------------- 1 | use k8s_openapi::api::core::v1::Pod; 2 | use kube::{ 3 | api::{Api, ListParams}, 4 | Client, 5 | }; 6 | use tracing::*; 7 | 8 | #[tokio::main] 9 | async fn main() -> anyhow::Result<()> { 10 | tracing_subscriber::fmt::init(); 11 | let client = Client::try_default().await?; 12 | 13 | // Equivalent to `kubectl get pods --all-namespace \ 14 | // -o jsonpath='{.items[*].spec.containers[*].image}'` 15 | let field_selector = std::env::var("FIELD_SELECTOR").unwrap_or_default(); 16 | let jsonpath = format!( 17 | "{}{}", 18 | "$", 19 | std::env::var("JSONPATH").unwrap_or_else(|_| ".items[*].spec.containers[*].image".into()) 20 | ); 21 | 22 | let pods: Api = Api::::all(client); 23 | let list_params = ListParams::default().fields(&field_selector); 24 | let list = pods.list(&list_params).await?; 25 | 26 | // Use the given JSONPATH to filter the ObjectList 27 | let list_json = serde_json::to_value(&list)?; 28 | let res = jsonpath_lib::select(&list_json, &jsonpath).unwrap(); 29 | info!("\t\t {:?}", res); 30 | Ok(()) 31 | } 32 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/dynamic_pod.rs: -------------------------------------------------------------------------------- 1 | use kube::{ 2 | api::{Api, ApiResource, NotUsed, Object, ResourceExt}, 3 | Client, 4 | }; 5 | use serde::Deserialize; 6 | use tracing::*; 7 | 8 | #[tokio::main] 9 | async fn main() -> anyhow::Result<()> { 10 | tracing_subscriber::fmt::init(); 11 | let client = Client::try_default().await?; 12 | 13 | // Here we replace heavy type k8s_openapi::api::core::v1::PodSpec with 14 | #[derive(Clone, Deserialize, Debug)] 15 | struct PodSpecSimple { 16 | containers: Vec, 17 | } 18 | #[derive(Clone, Deserialize, Debug)] 19 | struct ContainerSimple { 20 | #[allow(dead_code)] 21 | image: String, 22 | } 23 | type PodSimple = Object; 24 | 25 | // Here we simply steal the type info from k8s_openapi, but we could create this from scratch. 26 | let ar = ApiResource::erase::(&()); 27 | 28 | let pods: Api = Api::default_namespaced_with(client, &ar); 29 | for p in pods.list(&Default::default()).await? { 30 | info!("Pod {} runs: {:?}", p.name_any(), p.spec.containers); 31 | } 32 | 33 | Ok(()) 34 | } 35 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/dynamic_watcher.rs: -------------------------------------------------------------------------------- 1 | use futures::{StreamExt, TryStreamExt}; 2 | use kube::{ 3 | api::{Api, DynamicObject, GroupVersionKind, ListParams, ResourceExt}, 4 | discovery::{self, Scope}, 5 | runtime::{watcher, WatchStreamExt}, 6 | Client, 7 | }; 8 | use tracing::*; 9 | 10 | use std::env; 11 | 12 | #[tokio::main] 13 | async fn main() -> anyhow::Result<()> { 14 | tracing_subscriber::fmt::init(); 15 | let client = Client::try_default().await?; 16 | 17 | // Take dynamic resource identifiers: 18 | let group = env::var("GROUP").unwrap_or_else(|_| "clux.dev".into()); 19 | let version = env::var("VERSION").unwrap_or_else(|_| "v1".into()); 20 | let kind = env::var("KIND").unwrap_or_else(|_| "Foo".into()); 21 | 22 | // Turn them into a GVK 23 | let gvk = GroupVersionKind::gvk(&group, &version, &kind); 24 | // Use API discovery to identify more information about the type (like its plural) 25 | let (ar, caps) = discovery::pinned_kind(&client, &gvk).await?; 26 | 27 | // Use the full resource info to create an Api with the ApiResource as its DynamicType 28 | let api = Api::::all_with(client, &ar); 29 | 30 | // Fully compatible with kube-runtime 31 | let mut items = watcher(api, ListParams::default()).applied_objects().boxed(); 32 | while let Some(p) = items.try_next().await? { 33 | if caps.scope == Scope::Cluster { 34 | info!("saw {}", p.name_any()); 35 | } else { 36 | info!("saw {} in {}", p.name_any(), p.namespace().unwrap()); 37 | } 38 | } 39 | Ok(()) 40 | } 41 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/event_watcher.rs: -------------------------------------------------------------------------------- 1 | use futures::{pin_mut, TryStreamExt}; 2 | use k8s_openapi::api::core::v1::Event; 3 | use kube::{ 4 | api::{Api, ListParams}, 5 | runtime::{watcher, WatchStreamExt}, 6 | Client, 7 | }; 8 | use tracing::*; 9 | 10 | #[tokio::main] 11 | async fn main() -> anyhow::Result<()> { 12 | tracing_subscriber::fmt::init(); 13 | let client = Client::try_default().await?; 14 | 15 | let events: Api = Api::all(client); 16 | let lp = ListParams::default(); 17 | 18 | let ew = watcher(events, lp).applied_objects(); 19 | 20 | pin_mut!(ew); 21 | while let Some(event) = ew.try_next().await? { 22 | handle_event(event)?; 23 | } 24 | Ok(()) 25 | } 26 | 27 | // This function lets the app handle an added/modified event from k8s 28 | fn handle_event(ev: Event) -> anyhow::Result<()> { 29 | info!( 30 | "Event: \"{}\" via {} {}", 31 | ev.message.unwrap().trim(), 32 | ev.involved_object.kind.unwrap(), 33 | ev.involved_object.name.unwrap() 34 | ); 35 | Ok(()) 36 | } 37 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/job_api.rs: -------------------------------------------------------------------------------- 1 | use k8s_openapi::api::batch::v1::Job; 2 | use kube::{ 3 | api::{Api, DeleteParams, PostParams}, 4 | runtime::wait::{await_condition, conditions}, 5 | Client, 6 | }; 7 | use tracing::info; 8 | 9 | #[tokio::main] 10 | async fn main() -> anyhow::Result<()> { 11 | tracing_subscriber::fmt::init(); 12 | let client = Client::try_default().await?; 13 | let jobs: Api = Api::default_namespaced(client); 14 | 15 | info!("Creating job"); 16 | let name = "empty-job"; 17 | let data = serde_json::from_value(serde_json::json!({ 18 | "apiVersion": "batch/v1", 19 | "kind": "Job", 20 | "metadata": { 21 | "name": name, 22 | }, 23 | "spec": { 24 | "template": { 25 | "metadata": { 26 | "name": "empty-job-pod" 27 | }, 28 | "spec": { 29 | "containers": [{ 30 | "name": "empty", 31 | "image": "alpine:latest" 32 | }], 33 | "restartPolicy": "Never", 34 | } 35 | } 36 | } 37 | }))?; 38 | jobs.create(&PostParams::default(), &data).await?; 39 | 40 | info!("Waiting for job to complete"); 41 | let cond = await_condition(jobs.clone(), name, conditions::is_job_completed()); 42 | let _ = tokio::time::timeout(std::time::Duration::from_secs(20), cond).await?; 43 | 44 | info!("Cleaning up job record"); 45 | jobs.delete(name, &DeleteParams::background()).await?; 46 | Ok(()) 47 | } 48 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/log_stream.rs: -------------------------------------------------------------------------------- 1 | use anyhow::{anyhow, Result}; 2 | use futures::{StreamExt, TryStreamExt}; 3 | use k8s_openapi::api::core::v1::Pod; 4 | use kube::{ 5 | api::{Api, LogParams}, 6 | Client, 7 | }; 8 | use std::env; 9 | use tracing::*; 10 | 11 | #[tokio::main] 12 | async fn main() -> Result<()> { 13 | tracing_subscriber::fmt::init(); 14 | let client = Client::try_default().await?; 15 | 16 | let mypod = env::args() 17 | .nth(1) 18 | .ok_or_else(|| anyhow!("Usage: log_follow "))?; 19 | info!("Fetching logs for {:?}", mypod); 20 | 21 | let pods: Api = Api::default_namespaced(client); 22 | let mut logs = pods 23 | .log_stream(&mypod, &LogParams { 24 | follow: true, 25 | tail_lines: Some(1), 26 | ..LogParams::default() 27 | }) 28 | .await? 29 | .boxed(); 30 | 31 | while let Some(line) = logs.try_next().await? { 32 | info!("{:?}", String::from_utf8_lossy(&line)); 33 | } 34 | Ok(()) 35 | } 36 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/multi_watcher.rs: -------------------------------------------------------------------------------- 1 | use futures::{stream, StreamExt, TryStreamExt}; 2 | use k8s_openapi::api::{ 3 | apps::v1::Deployment, 4 | core::v1::{ConfigMap, Secret}, 5 | }; 6 | use kube::{ 7 | api::{Api, ListParams, ResourceExt}, 8 | runtime::{watcher, WatchStreamExt}, 9 | Client, 10 | }; 11 | use tracing::*; 12 | 13 | #[tokio::main] 14 | async fn main() -> anyhow::Result<()> { 15 | tracing_subscriber::fmt::init(); 16 | let client = Client::try_default().await?; 17 | 18 | let deploys: Api = Api::default_namespaced(client.clone()); 19 | let cms: Api = Api::default_namespaced(client.clone()); 20 | let secret: Api = Api::default_namespaced(client.clone()); 21 | let dep_watcher = watcher(deploys, ListParams::default()); 22 | let cm_watcher = watcher(cms, ListParams::default()); 23 | let sec_watcher = watcher(secret, ListParams::default()); 24 | 25 | // select on applied events from all watchers 26 | let mut combo_stream = stream::select_all(vec![ 27 | dep_watcher.applied_objects().map_ok(Watched::Deploy).boxed(), 28 | cm_watcher.applied_objects().map_ok(Watched::Config).boxed(), 29 | sec_watcher.applied_objects().map_ok(Watched::Secret).boxed(), 30 | ]); 31 | // SelectAll Stream elements must have the same Item, so all packed in this: 32 | #[allow(clippy::large_enum_variant)] 33 | enum Watched { 34 | Config(ConfigMap), 35 | Deploy(Deployment), 36 | Secret(Secret), 37 | } 38 | while let Some(o) = combo_stream.try_next().await? { 39 | match o { 40 | Watched::Config(cm) => info!("Got configmap: {}", cm.name_any()), 41 | Watched::Deploy(d) => info!("Got deployment: {}", d.name_any()), 42 | Watched::Secret(s) => info!("Got secret: {}", s.name_any()), 43 | } 44 | } 45 | Ok(()) 46 | } 47 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/node_reflector.rs: -------------------------------------------------------------------------------- 1 | use futures::{StreamExt, TryStreamExt}; 2 | use k8s_openapi::api::core::v1::Node; 3 | use kube::{ 4 | api::{Api, ListParams, ResourceExt}, 5 | runtime::{reflector, watcher, WatchStreamExt}, 6 | Client, 7 | }; 8 | use tracing::*; 9 | 10 | #[tokio::main] 11 | async fn main() -> anyhow::Result<()> { 12 | tracing_subscriber::fmt::init(); 13 | let client = Client::try_default().await?; 14 | 15 | let nodes: Api = Api::all(client.clone()); 16 | let lp = ListParams::default() 17 | .labels("kubernetes.io/arch=amd64") // filter instances by label 18 | .timeout(10); // short watch timeout in this example 19 | 20 | let (reader, writer) = reflector::store(); 21 | let rf = reflector(writer, watcher(nodes, lp)); 22 | 23 | // Periodically read our state in the background 24 | tokio::spawn(async move { 25 | loop { 26 | let nodes = reader.state().iter().map(|r| r.name_any()).collect::>(); 27 | info!("Current {} nodes: {:?}", nodes.len(), nodes); 28 | tokio::time::sleep(std::time::Duration::from_secs(10)).await; 29 | } 30 | }); 31 | 32 | // Drain and log applied events from the reflector 33 | let mut rfa = rf.applied_objects().boxed(); 34 | while let Some(event) = rfa.try_next().await? { 35 | info!("saw {}", event.name_any()); 36 | } 37 | 38 | Ok(()) 39 | } 40 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/node_watcher.rs: -------------------------------------------------------------------------------- 1 | use backoff::ExponentialBackoff; 2 | use futures::{pin_mut, TryStreamExt}; 3 | use k8s_openapi::api::core::v1::{Event, Node}; 4 | use kube::{ 5 | api::{Api, ListParams, ResourceExt}, 6 | runtime::{watcher, WatchStreamExt}, 7 | Client, 8 | }; 9 | use tracing::*; 10 | 11 | #[tokio::main] 12 | async fn main() -> anyhow::Result<()> { 13 | tracing_subscriber::fmt::init(); 14 | let client = Client::try_default().await?; 15 | let events: Api = Api::all(client.clone()); 16 | let nodes: Api = Api::all(client.clone()); 17 | 18 | let lp = ListParams::default().labels("beta.kubernetes.io/arch=amd64"); 19 | let obs = watcher(nodes, lp) 20 | .backoff(ExponentialBackoff::default()) 21 | .applied_objects(); 22 | 23 | pin_mut!(obs); 24 | while let Some(n) = obs.try_next().await? { 25 | check_for_node_failures(&events, n).await?; 26 | } 27 | Ok(()) 28 | } 29 | 30 | // A simple node problem detector 31 | async fn check_for_node_failures(events: &Api, o: Node) -> anyhow::Result<()> { 32 | let name = o.name_any(); 33 | // Nodes often modify a lot - only print broken nodes 34 | if let Some(true) = o.spec.unwrap().unschedulable { 35 | let failed = o 36 | .status 37 | .unwrap() 38 | .conditions 39 | .unwrap() 40 | .into_iter() 41 | .filter(|c| { 42 | // In a failed state either some of the extra conditions are not False 43 | // Or the Ready state is False 44 | (c.status == "True" && c.type_ != "Ready") || (c.status == "False" && c.type_ == "Ready") 45 | }) 46 | .map(|c| c.message) 47 | .collect::>(); // failed statuses 48 | warn!("Unschedulable Node: {}, ({:?})", name, failed); 49 | // Find events related to this node 50 | let opts = 51 | ListParams::default().fields(&format!("involvedObject.kind=Node,involvedObject.name={}", name)); 52 | let evlist = events.list(&opts).await?; 53 | for e in evlist { 54 | warn!("Node event: {:?}", serde_json::to_string_pretty(&e)?); 55 | } 56 | } else { 57 | info!("Healthy node: {}", name); 58 | } 59 | Ok(()) 60 | } 61 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/pod_evict.rs: -------------------------------------------------------------------------------- 1 | use futures::{StreamExt, TryStreamExt}; 2 | use k8s_openapi::api::core::v1::Pod; 3 | use serde_json::json; 4 | use tracing::*; 5 | 6 | use kube::{ 7 | api::{Api, EvictParams, ListParams, PostParams, ResourceExt, WatchEvent}, 8 | Client, 9 | }; 10 | 11 | #[tokio::main] 12 | async fn main() -> anyhow::Result<()> { 13 | tracing_subscriber::fmt::init(); 14 | let client = Client::try_default().await?; 15 | 16 | // Create a Job 17 | let pod_name = "empty-pod"; 18 | let empty_pod = serde_json::from_value(json!({ 19 | "apiVersion": "v1", 20 | "kind": "Pod", 21 | "metadata": { 22 | "name": pod_name, 23 | }, 24 | "spec": { 25 | "containers": [{ 26 | "name": "empty", 27 | "image": "alpine:latest", 28 | "command": ["tail", "-f", "/dev/null"] 29 | }], 30 | } 31 | }))?; 32 | 33 | let pods: Api = Api::default_namespaced(client); 34 | let pp = PostParams::default(); 35 | pods.create(&pp, &empty_pod).await?; 36 | 37 | // Wait until the pod is running, although it's not necessary 38 | let lp = ListParams::default() 39 | .fields("metadata.name=empty-pod") 40 | .timeout(10); 41 | let mut stream = pods.watch(&lp, "0").await?.boxed(); 42 | while let Some(status) = stream.try_next().await? { 43 | match status { 44 | WatchEvent::Added(o) => { 45 | info!("Added {}", o.name_any()); 46 | } 47 | WatchEvent::Modified(o) => { 48 | let s = o.status.as_ref().expect("status exists on pod"); 49 | if s.phase.clone().unwrap_or_default() == "Running" { 50 | info!("Ready to evict to {}", o.name_any()); 51 | break; 52 | } 53 | } 54 | _ => {} 55 | } 56 | } 57 | 58 | // Evict the pod 59 | let ep = EvictParams::default(); 60 | let eres = pods.evict(pod_name, &ep).await?; 61 | info!("{:?}", eres); 62 | Ok(()) 63 | } 64 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/pod_paged.rs: -------------------------------------------------------------------------------- 1 | use k8s_openapi::api::core::v1::Pod; 2 | use kube::{ 3 | api::{Api, ListParams, ResourceExt}, 4 | Client, 5 | }; 6 | use tracing::*; 7 | 8 | const PAGE_SIZE: u32 = 5; 9 | 10 | #[tokio::main] 11 | async fn main() -> anyhow::Result<()> { 12 | tracing_subscriber::fmt::init(); 13 | let client = Client::try_default().await?; 14 | let api = Api::::default_namespaced(client); 15 | 16 | let mut continue_token: Option = None; 17 | for page in 1.. { 18 | info!("Fetching Page #{page}"); 19 | continue_token = fetch_page(&api, continue_token).await?; 20 | 21 | if continue_token.is_none() { 22 | info!("End of list"); 23 | break; 24 | } 25 | } 26 | 27 | Ok(()) 28 | } 29 | 30 | async fn fetch_page(api: &Api, continue_token: Option) -> anyhow::Result> { 31 | let mut lp = ListParams::default().limit(PAGE_SIZE); 32 | if let Some(token) = continue_token { 33 | lp = lp.continue_token(&token); 34 | } 35 | 36 | let pods = api.list(&lp).await?; 37 | let continue_token = pods.metadata.continue_.clone(); 38 | for p in pods { 39 | info!("Found Pod: {}", p.name_any()); 40 | } 41 | 42 | Ok(continue_token) 43 | } 44 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/pod_portforward.rs: -------------------------------------------------------------------------------- 1 | use futures::StreamExt; 2 | use k8s_openapi::api::core::v1::Pod; 3 | use tracing::*; 4 | 5 | use kube::{ 6 | api::{Api, DeleteParams, PostParams}, 7 | runtime::wait::{await_condition, conditions::is_pod_running}, 8 | Client, ResourceExt, 9 | }; 10 | 11 | use tokio::io::AsyncWriteExt; 12 | 13 | #[tokio::main] 14 | async fn main() -> anyhow::Result<()> { 15 | tracing_subscriber::fmt::init(); 16 | let client = Client::try_default().await?; 17 | 18 | let p: Pod = serde_json::from_value(serde_json::json!({ 19 | "apiVersion": "v1", 20 | "kind": "Pod", 21 | "metadata": { "name": "example" }, 22 | "spec": { 23 | "containers": [{ 24 | "name": "nginx", 25 | "image": "nginx", 26 | }], 27 | } 28 | }))?; 29 | 30 | let pods: Api = Api::default_namespaced(client); 31 | // Stop on error including a pod already exists or is still being deleted. 32 | pods.create(&PostParams::default(), &p).await?; 33 | 34 | // Wait until the pod is running, otherwise we get 500 error. 35 | let running = await_condition(pods.clone(), "example", is_pod_running()); 36 | let _ = tokio::time::timeout(std::time::Duration::from_secs(15), running).await?; 37 | 38 | let mut pf = pods.portforward("example", &[80]).await?; 39 | let mut port = pf.take_stream(80).unwrap(); 40 | port.write_all(b"GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\nAccept: */*\r\n\r\n") 41 | .await?; 42 | let mut rstream = tokio_util::io::ReaderStream::new(port); 43 | if let Some(res) = rstream.next().await { 44 | match res { 45 | Ok(bytes) => { 46 | let response = std::str::from_utf8(&bytes[..]).unwrap(); 47 | info!("resp: {}", response); 48 | assert!(response.contains("Welcome to nginx!")); 49 | } 50 | Err(err) => warn!("{:?}", err), 51 | } 52 | } 53 | 54 | // Delete it 55 | info!("deleting"); 56 | pods.delete("example", &DeleteParams::default()) 57 | .await? 58 | .map_left(|pdel| { 59 | assert_eq!(pdel.name_any(), "example"); 60 | }); 61 | 62 | Ok(()) 63 | } 64 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/pod_reflector.rs: -------------------------------------------------------------------------------- 1 | use futures::TryStreamExt; 2 | use k8s_openapi::api::core::v1::Pod; 3 | use kube::{ 4 | api::{Api, ListParams}, 5 | runtime::{reflector, watcher, WatchStreamExt}, 6 | Client, ResourceExt, 7 | }; 8 | use tracing::*; 9 | 10 | #[tokio::main] 11 | async fn main() -> anyhow::Result<()> { 12 | tracing_subscriber::fmt::init(); 13 | let client = Client::try_default().await?; 14 | 15 | let api: Api = Api::default_namespaced(client); 16 | let (reader, writer) = reflector::store::(); 17 | 18 | tokio::spawn(async move { 19 | // Show state every 5 seconds of watching 20 | loop { 21 | tokio::time::sleep(std::time::Duration::from_secs(5)).await; 22 | info!("Current pod count: {}", reader.state().len()); 23 | // full information with debug logs 24 | for p in reader.state() { 25 | let yaml = serde_yaml::to_string(p.as_ref()).unwrap(); 26 | debug!("Pod {}: \n{}", p.name_any(), yaml); 27 | } 28 | } 29 | }); 30 | 31 | let stream = watcher(api, ListParams::default()).map_ok(|ev| { 32 | ev.modify(|pod| { 33 | // memory optimization for our store - we don't care about fields/annotations/status 34 | pod.managed_fields_mut().clear(); 35 | pod.annotations_mut().clear(); 36 | pod.status = None; 37 | }) 38 | }); 39 | 40 | let rf = reflector(writer, stream).applied_objects(); 41 | futures::pin_mut!(rf); 42 | 43 | while let Some(pod) = rf.try_next().await? { 44 | info!("saw {}", pod.name_any()); 45 | } 46 | Ok(()) 47 | } 48 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/pod_watcher.rs: -------------------------------------------------------------------------------- 1 | use futures::prelude::*; 2 | use k8s_openapi::api::core::v1::Pod; 3 | use kube::{ 4 | api::{Api, ListParams, ResourceExt}, 5 | runtime::{watcher, WatchStreamExt}, 6 | Client, 7 | }; 8 | use tracing::*; 9 | 10 | #[tokio::main] 11 | async fn main() -> anyhow::Result<()> { 12 | tracing_subscriber::fmt::init(); 13 | let client = Client::try_default().await?; 14 | let api = Api::::default_namespaced(client); 15 | 16 | watcher(api, ListParams::default()) 17 | .applied_objects() 18 | .try_for_each(|p| async move { 19 | info!("saw {}", p.name_any()); 20 | if let Some(unready_reason) = pod_unready(&p) { 21 | warn!("{}", unready_reason); 22 | } 23 | Ok(()) 24 | }) 25 | .await?; 26 | Ok(()) 27 | } 28 | 29 | fn pod_unready(p: &Pod) -> Option { 30 | let status = p.status.as_ref().unwrap(); 31 | if let Some(conds) = &status.conditions { 32 | let failed = conds 33 | .iter() 34 | .filter(|c| c.type_ == "Ready" && c.status == "False") 35 | .map(|c| c.message.clone().unwrap_or_default()) 36 | .collect::>() 37 | .join(","); 38 | if !failed.is_empty() { 39 | if p.metadata.labels.as_ref().unwrap().contains_key("job-name") { 40 | return None; // ignore job based pods, they are meant to exit 0 41 | } 42 | return Some(format!("Unready pod {}: {}", p.name_any(), failed)); 43 | } 44 | } 45 | None 46 | } 47 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/secret_reflector.rs: -------------------------------------------------------------------------------- 1 | use futures::TryStreamExt; 2 | use k8s_openapi::api::core::v1::Secret; 3 | use kube::{ 4 | api::{Api, ListParams, ResourceExt}, 5 | runtime::{reflector, reflector::Store, watcher, WatchStreamExt}, 6 | Client, 7 | }; 8 | use std::collections::BTreeMap; 9 | use tracing::*; 10 | 11 | /// Example way to read secrets 12 | #[derive(Debug)] 13 | enum Decoded { 14 | /// Usually secrets are just short utf8 encoded strings 15 | Utf8(String), 16 | /// But it's allowed to just base64 encode binary in the values 17 | Bytes(Vec), 18 | } 19 | 20 | fn decode(secret: &Secret) -> BTreeMap { 21 | let mut res = BTreeMap::new(); 22 | // Ignoring binary data for now 23 | if let Some(data) = secret.data.clone() { 24 | for (k, v) in data { 25 | if let Ok(b) = std::str::from_utf8(&v.0) { 26 | res.insert(k, Decoded::Utf8(b.to_string())); 27 | } else { 28 | res.insert(k, Decoded::Bytes(v.0)); 29 | } 30 | } 31 | } 32 | res 33 | } 34 | 35 | fn spawn_periodic_reader(reader: Store) { 36 | tokio::spawn(async move { 37 | loop { 38 | // Periodically read our state 39 | let cms: Vec<_> = reader 40 | .state() 41 | .iter() 42 | .map(|s| format!("{}: {:?}", s.name_any(), decode(s).keys())) 43 | .collect(); 44 | info!("Current secrets: {:?}", cms); 45 | tokio::time::sleep(std::time::Duration::from_secs(15)).await; 46 | } 47 | }); 48 | } 49 | 50 | #[tokio::main] 51 | async fn main() -> anyhow::Result<()> { 52 | tracing_subscriber::fmt::init(); 53 | let client = Client::try_default().await?; 54 | 55 | let secrets: Api = Api::default_namespaced(client); 56 | let lp = ListParams::default().timeout(10); // short watch timeout in this example 57 | 58 | let (reader, writer) = reflector::store::(); 59 | let rf = reflector(writer, watcher(secrets, lp)); 60 | 61 | spawn_periodic_reader(reader); // read from a reader in the background 62 | 63 | rf.applied_objects() 64 | .try_for_each(|s| async move { 65 | info!("saw: {}", s.name_any()); 66 | Ok(()) 67 | }) 68 | .await?; 69 | Ok(()) 70 | } 71 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/examples/secret_syncer_configmap.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ConfigMap 3 | metadata: 4 | name: secret-syncer-example 5 | labels: 6 | configmap-secret-syncer.nullable.se/sync: "true" 7 | data: 8 | foo: bar 9 | spam: eggs 10 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-client/README.md: -------------------------------------------------------------------------------- 1 | # kube-client 2 | [![Client Capabilities](https://img.shields.io/badge/Kubernetes%20client-Silver-blue.svg?style=plastic&colorB=C0C0C0&colorA=306CE8)](https://github.com/kubernetes/design-proposals-archive/blob/main/api-machinery/csi-new-client-library-procedure.md#client-capabilities) 3 | [![Client Support Level](https://img.shields.io/badge/kubernetes%20client-beta-green.svg?style=plastic&colorA=306CE8)](https://github.com/kubernetes/design-proposals-archive/blob/main/api-machinery/csi-new-client-library-procedure.md#client-support-level) 4 | 5 | The rust counterpart to [kubernetes/client-go](https://github.com/kubernetes/apimachinery). 6 | Contains the IO layer plus the core Api layer, and also as well as config parsing. 7 | 8 | ## Usage 9 | This crate, and all its features, are re-exported from the facade-crate `kube`. 10 | 11 | ## Docs 12 | See the **[kube-client API Docs](https://docs.rs/kube-client/)** 13 | 14 | ## Development 15 | Help very welcome! To help out on this crate check out these labels: 16 | - https://github.com/kube-rs/kube/labels/client 17 | - https://github.com/kube-rs/kube/labels/api 18 | - https://github.com/kube-rs/kube/labels/config 19 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-client/src/api/util/csr.rs: -------------------------------------------------------------------------------- 1 | use crate::{api::Api, Error, Result}; 2 | use k8s_openapi::api::certificates::v1::CertificateSigningRequest; 3 | use kube_core::params::{Patch, PatchParams}; 4 | 5 | 6 | impl Api { 7 | /// Partially update approval of the specified CertificateSigningRequest. 8 | pub async fn patch_approval( 9 | &self, 10 | name: &str, 11 | pp: &PatchParams, 12 | patch: &Patch

, 13 | ) -> Result { 14 | let mut req = self 15 | .request 16 | .patch_subresource("approval", name, pp, patch) 17 | .map_err(Error::BuildRequest)?; 18 | req.extensions_mut().insert("approval"); 19 | self.client.request::(req).await 20 | } 21 | 22 | /// Get the CertificateSigningRequest. May differ from get(name) 23 | pub async fn get_approval(&self, name: &str) -> Result { 24 | self.get_subresource("approval", name).await 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-client/src/client/body.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | pin::Pin, 3 | task::{Context, Poll}, 4 | }; 5 | 6 | use futures::stream::Stream; 7 | use http_body::Body; 8 | use pin_project::pin_project; 9 | 10 | // Wrap `http_body::Body` to implement `Stream`. 11 | #[pin_project] 12 | pub struct IntoStream { 13 | #[pin] 14 | body: B, 15 | } 16 | 17 | impl IntoStream { 18 | pub(crate) fn new(body: B) -> Self { 19 | Self { body } 20 | } 21 | } 22 | 23 | impl Stream for IntoStream 24 | where 25 | B: Body, 26 | { 27 | type Item = Result; 28 | 29 | fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 30 | self.project().body.poll_data(cx) 31 | } 32 | } 33 | 34 | pub trait BodyStreamExt: Body { 35 | fn into_stream(self) -> IntoStream 36 | where 37 | Self: Sized, 38 | { 39 | IntoStream::new(self) 40 | } 41 | } 42 | 43 | impl BodyStreamExt for T where T: Body {} 44 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-client/src/client/middleware/extra_headers.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Arc; 2 | 3 | use http::{header::HeaderName, request::Request, HeaderValue}; 4 | use tower::{Layer, Service}; 5 | 6 | #[derive(Clone)] 7 | /// Layer that adds a static set of extra headers to each request 8 | pub struct ExtraHeadersLayer { 9 | pub(crate) headers: Arc>, 10 | } 11 | 12 | impl Layer for ExtraHeadersLayer { 13 | type Service = ExtraHeaders; 14 | 15 | fn layer(&self, inner: S) -> Self::Service { 16 | ExtraHeaders { 17 | inner, 18 | headers: self.headers.clone(), 19 | } 20 | } 21 | } 22 | 23 | #[derive(Clone)] 24 | /// Service that adds a static set of extra headers to each request 25 | pub struct ExtraHeaders { 26 | inner: S, 27 | headers: Arc>, 28 | } 29 | 30 | impl Service> for ExtraHeaders 31 | where 32 | S: Service>, 33 | { 34 | type Error = S::Error; 35 | type Future = S::Future; 36 | type Response = S::Response; 37 | 38 | fn poll_ready(&mut self, cx: &mut std::task::Context<'_>) -> std::task::Poll> { 39 | self.inner.poll_ready(cx) 40 | } 41 | 42 | fn call(&mut self, mut req: Request) -> Self::Future { 43 | req.headers_mut().extend(self.headers.iter().cloned()); 44 | self.inner.call(req) 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-core/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "kube-core" 3 | description = "Kube shared types, traits and client-less behavior" 4 | version = "0.75.0" 5 | authors = [ 6 | "clux ", 7 | "kazk ", 8 | ] 9 | edition = "2021" 10 | rust-version = "1.60.0" 11 | license = "Apache-2.0" 12 | repository = "https://github.com/kube-rs/kube" 13 | readme = "../README.md" 14 | 15 | [package.metadata.docs.rs] 16 | features = ["ws", "admission", "jsonpatch", "k8s-openapi/v1_25"] 17 | rustdoc-args = ["--cfg", "docsrs"] 18 | 19 | [features] 20 | ws = [] 21 | admission = ["json-patch"] 22 | jsonpatch = ["json-patch"] 23 | schema = ["schemars"] 24 | 25 | [dependencies] 26 | serde = { version = "1.0.130", features = ["derive"] } 27 | serde_json = "1.0.68" 28 | thiserror = "1.0.29" 29 | form_urlencoded = "1.0.1" 30 | http = "0.2.5" 31 | json-patch = { version = "0.2.6", optional = true } 32 | once_cell = "1.8.0" 33 | chrono = { version = "0.4.19", default-features = false, features = ["clock"] } 34 | schemars = { version = "0.8.6", optional = true } 35 | 36 | [dependencies.k8s-openapi] 37 | version = "0.16.0" 38 | default-features = false 39 | features = [] 40 | 41 | [dev-dependencies.k8s-openapi] 42 | version = "0.16.0" 43 | default-features = false 44 | features = ["v1_25"] 45 | 46 | [dev-dependencies] 47 | assert-json-diff = "2.0.1" 48 | kube = { path = "../kube", version = "<1.0.0, >=0.53.0" } 49 | serde_yaml = "0.8.23" 50 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-core/README.md: -------------------------------------------------------------------------------- 1 | # kube-core 2 | Core traits and types necessary for interacting with the kubernetes API. 3 | The rust counterpart to [kubernetes/apimachinery](https://github.com/kubernetes/apimachinery). 4 | 5 | ## Usage 6 | This crate is always re-exported from `kube` (even without features) under [`kube::core`](https://docs.rs/kube/*/kube/core/index.html). 7 | 8 | ## Docs 9 | See the **[kube-core API Docs](https://docs.rs/kube-core/)** 10 | 11 | ## Development 12 | Help very welcome! We need generic utilities, helpers like those in apimachinery, testing improvements, or just documentation. See https://github.com/kube-rs/kube/labels/core 13 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-core/src/conversion/mod.rs: -------------------------------------------------------------------------------- 1 | //! Contains types useful for implementing custom resource conversion webhooks. 2 | 3 | pub use self::types::{ 4 | ConversionRequest, ConversionResponse, ConversionReview, ConvertConversionReviewError, 5 | }; 6 | 7 | /// Defines low-level typings. 8 | mod types; 9 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-core/src/error.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | use thiserror::Error; 3 | 4 | /// An error response from the API. 5 | #[derive(Error, Deserialize, Serialize, Debug, Clone, Eq, PartialEq)] 6 | #[error("{message}: {reason}")] 7 | pub struct ErrorResponse { 8 | /// The status 9 | pub status: String, 10 | /// A message about the error 11 | #[serde(default)] 12 | pub message: String, 13 | /// The reason for the error 14 | #[serde(default)] 15 | pub reason: String, 16 | /// The error code 17 | pub code: u16, 18 | } 19 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-core/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Crate with types and traits necessary for interacting with the Kubernetes API 2 | //! 3 | //! This crate provides the minimal apimachinery necessary to make requests to the kubernetes API. 4 | //! 5 | //! It does not export export a client, but it also has almost no dependencies. 6 | //! 7 | //! Everything in this crate is re-exported from [`kube`](https://crates.io/crates/kube) 8 | //! (even with zero features) under [`kube::core`]((https://docs.rs/kube/*/kube/core/index.html)). 9 | #![cfg_attr(docsrs, feature(doc_cfg))] 10 | #![deny(missing_docs)] 11 | #![forbid(unsafe_code)] 12 | 13 | #[cfg_attr(docsrs, doc(cfg(feature = "admission")))] 14 | #[cfg(feature = "admission")] 15 | pub mod admission; 16 | 17 | pub mod conversion; 18 | 19 | pub mod discovery; 20 | 21 | pub mod dynamic; 22 | pub use dynamic::{ApiResource, DynamicObject}; 23 | 24 | pub mod crd; 25 | pub use crd::CustomResourceExt; 26 | 27 | pub mod gvk; 28 | pub use gvk::{GroupVersion, GroupVersionKind, GroupVersionResource}; 29 | 30 | pub mod metadata; 31 | pub use metadata::{ListMeta, ObjectMeta, TypeMeta}; 32 | 33 | pub mod object; 34 | pub use object::{NotUsed, Object, ObjectList}; 35 | 36 | pub mod params; 37 | 38 | pub mod request; 39 | pub use request::Request; 40 | 41 | mod resource; 42 | pub use resource::{ 43 | ClusterResourceScope, DynamicResourceScope, NamespaceResourceScope, Resource, ResourceExt, ResourceScope, 44 | SubResourceScope, 45 | }; 46 | 47 | pub mod response; 48 | pub use response::Status; 49 | 50 | #[cfg_attr(docsrs, doc(cfg(feature = "schema")))] 51 | #[cfg(feature = "schema")] 52 | pub mod schema; 53 | 54 | pub mod subresource; 55 | 56 | pub mod util; 57 | 58 | pub mod watch; 59 | pub use watch::WatchEvent; 60 | 61 | mod error; 62 | pub use error::ErrorResponse; 63 | 64 | mod version; 65 | pub use version::Version; 66 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-core/src/metadata.rs: -------------------------------------------------------------------------------- 1 | //! Metadata structs used in traits, lists, and dynamic objects. 2 | pub use k8s_openapi::apimachinery::pkg::apis::meta::v1::{ListMeta, ObjectMeta}; 3 | use serde::{Deserialize, Serialize}; 4 | 5 | /// Type information that is flattened into every kubernetes object 6 | #[derive(Deserialize, Serialize, Clone, Default, Debug, Eq, PartialEq, Hash)] 7 | #[serde(rename_all = "camelCase")] 8 | pub struct TypeMeta { 9 | /// The version of the API 10 | pub api_version: String, 11 | 12 | /// The name of the API 13 | pub kind: String, 14 | } 15 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-derive/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "kube-derive" 3 | description = "Custom derives for the kube kubernetes crates" 4 | version = "0.75.0" 5 | authors = [ 6 | "clux ", 7 | "kazk ", 8 | ] 9 | edition = "2021" 10 | rust-version = "1.60.0" 11 | license = "Apache-2.0" 12 | repository = "https://github.com/kube-rs/kube" 13 | readme = "../README.md" 14 | 15 | [dependencies] 16 | proc-macro2 = "1.0.29" 17 | quote = "1.0.10" 18 | syn = { version = "1.0.80", features = ["extra-traits"] } 19 | serde_json = "1.0.68" 20 | darling = "0.14.0" 21 | 22 | [lib] 23 | proc-macro = true 24 | 25 | [dev-dependencies] 26 | serde = { version = "1.0.130", features = ["derive"] } 27 | serde_yaml = "0.8.21" 28 | kube = { path = "../kube", default-features = false, version = "<1.0.0, >=0.61.0", features = ["derive"] } 29 | k8s-openapi = { version = "0.16.0", default-features = false, features = ["v1_25"] } 30 | schemars = { version = "0.8.6", features = ["chrono"] } 31 | validator = { version = "0.16.0", features = ["derive"] } 32 | chrono = { version = "0.4.19", default-features = false } 33 | trybuild = "1.0.48" 34 | assert-json-diff = "2.0.2" 35 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-derive/README.md: -------------------------------------------------------------------------------- 1 | # kube-derive 2 | Add `#[derive(CustomResource)]` to your custom resource struct. 3 | 4 | ## Installation 5 | Add the `derive` feature to `kube`: 6 | 7 | ```toml 8 | [dependencies] 9 | kube = { version = "0.75.0", feature = ["derive"] } 10 | ``` 11 | 12 | ## Usage 13 | See the **[kube-derive API Docs](https://docs.rs/kube-derive/)** 14 | 15 | ## Examples 16 | See the `crd_` prefixed [examples](../examples) for more. 17 | 18 | ## Development 19 | Help very welcome! Kubebuilder like features, testing improvement, openapi feature. See https://github.com/kube-rs/kube/labels/derive 20 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-derive/tests/test_ui.rs: -------------------------------------------------------------------------------- 1 | // Test that `kube-derive` outputs helpful error messages. 2 | // If you make a change, remove `tests/ui/*.stderr` and run `cargo test`. 3 | // Then copy the files that appear under `wip/` if it's what you expected. 4 | // Alternatively, run `TRYBUILD=overwrite cargo test`. 5 | // See https://github.com/dtolnay/trybuild 6 | #[test] 7 | fn test_failures() { 8 | let t = trybuild::TestCases::new(); 9 | t.compile_fail("tests/ui/*.rs"); 10 | } 11 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-derive/tests/ui/fail_with_suggestion.rs: -------------------------------------------------------------------------------- 1 | use kube_derive::CustomResource; 2 | use schemars::JsonSchema; 3 | use serde::{Deserialize, Serialize}; 4 | 5 | #[derive(CustomResource, Serialize, Deserialize, Debug, Clone, JsonSchema)] 6 | #[kube(group = "clux.dev", version = "v1", kind = "Foo", shortnames = "foo")] 7 | struct FooSpec { 8 | foo: String, 9 | } 10 | 11 | fn main() {} 12 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-derive/tests/ui/fail_with_suggestion.stderr: -------------------------------------------------------------------------------- 1 | error: Unknown field: `shortnames`. Did you mean `shortname`? 2 | --> $DIR/fail_with_suggestion.rs:6:58 3 | | 4 | 6 | #[kube(group = "clux.dev", version = "v1", kind = "Foo", shortnames = "foo")] 5 | | ^^^^^^^^^^ 6 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-derive/tests/ui/missing_required.rs: -------------------------------------------------------------------------------- 1 | use kube_derive::CustomResource; 2 | use schemars::JsonSchema; 3 | use serde::{Deserialize, Serialize}; 4 | 5 | #[derive(CustomResource, Serialize, Deserialize, Debug, Clone, JsonSchema)] 6 | struct FooSpec { 7 | foo: String, 8 | } 9 | 10 | fn main() {} 11 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-derive/tests/ui/missing_required.stderr: -------------------------------------------------------------------------------- 1 | error: Missing field `group` 2 | --> $DIR/missing_required.rs:5:10 3 | | 4 | 5 | #[derive(CustomResource, Serialize, Deserialize, Debug, Clone, JsonSchema)] 5 | | ^^^^^^^^^^^^^^ 6 | | 7 | = note: this error originates in the derive macro `CustomResource` (in Nightly builds, run with -Z macro-backtrace for more info) 8 | 9 | error: Missing field `version` 10 | --> $DIR/missing_required.rs:5:10 11 | | 12 | 5 | #[derive(CustomResource, Serialize, Deserialize, Debug, Clone, JsonSchema)] 13 | | ^^^^^^^^^^^^^^ 14 | | 15 | = note: this error originates in the derive macro `CustomResource` (in Nightly builds, run with -Z macro-backtrace for more info) 16 | 17 | error: Missing field `kind` 18 | --> $DIR/missing_required.rs:5:10 19 | | 20 | 5 | #[derive(CustomResource, Serialize, Deserialize, Debug, Clone, JsonSchema)] 21 | | ^^^^^^^^^^^^^^ 22 | | 23 | = note: this error originates in the derive macro `CustomResource` (in Nightly builds, run with -Z macro-backtrace for more info) 24 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-derive/tests/ui/union_fails.rs: -------------------------------------------------------------------------------- 1 | use kube_derive::CustomResource; 2 | use schemars::JsonSchema; 3 | use serde::{Deserialize, Serialize}; 4 | 5 | #[derive(CustomResource, Serialize, Deserialize, JsonSchema)] 6 | union FooSpec { 7 | int: u32, 8 | } 9 | 10 | fn main() {} 11 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-derive/tests/ui/union_fails.stderr: -------------------------------------------------------------------------------- 1 | error: Unions can not #[derive(CustomResource)] 2 | --> tests/ui/union_fails.rs:6:7 3 | | 4 | 6 | union FooSpec { 5 | | ^^^^^^^ 6 | 7 | error: Serde does not support derive for unions 8 | --> tests/ui/union_fails.rs:6:1 9 | | 10 | 6 | / union FooSpec { 11 | 7 | | int: u32, 12 | 8 | | } 13 | | |_^ 14 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-runtime/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-runtime/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "kube-runtime" 3 | version = "0.75.0" 4 | description = "Kubernetes futures controller runtime" 5 | authors = [ 6 | "Teo Klestrup Röijezon ", 7 | "clux ", 8 | ] 9 | license = "Apache-2.0" 10 | repository = "https://github.com/kube-rs/kube" 11 | readme = "../README.md" 12 | keywords = ["kubernetes", "runtime", "reflector", "watcher", "controller"] 13 | categories = ["web-programming::http-client"] 14 | rust-version = "1.60.0" 15 | edition = "2021" 16 | 17 | [package.metadata.docs.rs] 18 | features = ["k8s-openapi/v1_25"] 19 | # Define the configuration attribute `docsrs`. Used to enable `doc_cfg` feature. 20 | rustdoc-args = ["--cfg", "docsrs"] 21 | 22 | [dependencies] 23 | futures = "0.3.17" 24 | kube-client = { path = "../kube-client", version = "=0.75.0", default-features = false, features = ["jsonpatch", "client"] } 25 | derivative = "2.1.1" 26 | serde = "1.0.130" 27 | smallvec = "1.7.0" 28 | ahash = "0.8" 29 | parking_lot = "0.12.0" 30 | pin-project = "1.0.2" 31 | tokio = { version = "1.14.0", features = ["time"] } 32 | tokio-util = { version = "0.7.0", features = ["time"] } 33 | tracing = "0.1.29" 34 | json-patch = "0.2.6" 35 | serde_json = "1.0.68" 36 | thiserror = "1.0.29" 37 | backoff = "0.4.0" 38 | 39 | [dependencies.k8s-openapi] 40 | version = "0.16.0" 41 | default-features = false 42 | 43 | [dev-dependencies] 44 | kube = { path = "../kube", features = ["derive", "client", "runtime"], version = "<1.0.0, >=0.60.0" } 45 | serde_json = "1.0.68" 46 | tokio = { version = "1.14.0", features = ["full", "test-util"] } 47 | rand = "0.8.0" 48 | schemars = "0.8.6" 49 | 50 | [dev-dependencies.k8s-openapi] 51 | version = "0.16.0" 52 | default-features = false 53 | features = ["v1_25"] 54 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-runtime/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Common components for building Kubernetes operators 2 | //! 3 | //! This crate contains the core building blocks to allow users to build 4 | //! controllers/operators/watchers that need to synchronize/reconcile kubernetes 5 | //! state. 6 | //! 7 | //! Newcomers are recommended to start with the [`Controller`] builder, which gives an 8 | //! opinionated starting point that should be appropriate for simple operators, but all 9 | //! components are designed to be usable á la carte if your operator doesn't quite fit that mold. 10 | 11 | #![forbid(unsafe_code)] 12 | #![deny(clippy::all)] 13 | #![deny(clippy::pedantic)] 14 | // Triggered by many derive macros (kube-derive, derivative) 15 | #![allow(clippy::default_trait_access)] 16 | #![allow(clippy::type_repetition_in_bounds)] 17 | // Triggered by Tokio macros 18 | #![allow(clippy::semicolon_if_nothing_returned)] 19 | 20 | pub mod controller; 21 | k8s_openapi::k8s_if_ge_1_19! { 22 | pub mod events; 23 | } 24 | pub mod finalizer; 25 | pub mod reflector; 26 | pub mod scheduler; 27 | pub mod utils; 28 | pub mod wait; 29 | pub mod watcher; 30 | 31 | pub use controller::{applier, Controller}; 32 | pub use finalizer::finalizer; 33 | pub use reflector::reflector; 34 | pub use scheduler::scheduler; 35 | pub use utils::WatchStreamExt; 36 | pub use watcher::watcher; 37 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube-runtime/src/utils/watch_ext.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | utils::{event_flatten::EventFlatten, stream_backoff::StreamBackoff}, 3 | watcher, 4 | }; 5 | use backoff::backoff::Backoff; 6 | 7 | use futures::{Stream, TryStream}; 8 | 9 | /// Extension trait for streams returned by [`watcher`](watcher()) or [`reflector`](crate::reflector::reflector) 10 | pub trait WatchStreamExt: Stream { 11 | /// Apply a [`Backoff`] policy to a [`Stream`] using [`StreamBackoff`] 12 | fn backoff(self, b: B) -> StreamBackoff 13 | where 14 | B: Backoff, 15 | Self: TryStream + Sized, 16 | { 17 | StreamBackoff::new(self, b) 18 | } 19 | 20 | /// Flatten a [`watcher()`] stream into a stream of applied objects 21 | /// 22 | /// All Added/Modified events are passed through, and critical errors bubble up. 23 | fn applied_objects(self) -> EventFlatten 24 | where 25 | Self: Stream, watcher::Error>> + Sized, 26 | { 27 | EventFlatten::new(self, false) 28 | } 29 | 30 | /// Flatten a [`watcher()`] stream into a stream of touched objects 31 | /// 32 | /// All Added/Modified/Deleted events are passed through, and critical errors bubble up. 33 | fn touched_objects(self) -> EventFlatten 34 | where 35 | Self: Stream, watcher::Error>> + Sized, 36 | { 37 | EventFlatten::new(self, true) 38 | } 39 | } 40 | impl WatchStreamExt for St where St: Stream {} 41 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/kube/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "kube" 3 | version = "0.75.0" 4 | description = "Kubernetes client and async controller runtime" 5 | authors = [ 6 | "clux ", 7 | "Teo Klestrup Röijezon ", 8 | "kazk ", 9 | ] 10 | license = "Apache-2.0" 11 | repository = "https://github.com/kube-rs/kube" 12 | readme = "../README.md" 13 | keywords = ["kubernetes", "client", "runtime"] 14 | categories = ["web-programming::http-client"] 15 | rust-version = "1.60.0" 16 | edition = "2021" 17 | 18 | [features] 19 | default = ["client", "openssl-tls"] 20 | rustls-tls = ["kube-client/rustls-tls"] 21 | openssl-tls = ["kube-client/openssl-tls"] 22 | ws = ["kube-client/ws", "kube-core/ws"] 23 | oauth = ["kube-client/oauth"] 24 | gzip = ["kube-client/gzip"] 25 | client = ["kube-client/client", "config"] 26 | jsonpatch = ["kube-core/jsonpatch"] 27 | admission = ["kube-core/admission"] 28 | derive = ["kube-derive", "kube-core/schema"] 29 | config = ["kube-client/config"] 30 | runtime = ["kube-runtime"] 31 | 32 | [package.metadata.docs.rs] 33 | features = ["client", "rustls-tls", "openssl-tls", "derive", "ws", "oauth", "jsonpatch", "admission", "runtime", "k8s-openapi/v1_25"] 34 | # Define the configuration attribute `docsrs`. Used to enable `doc_cfg` feature. 35 | rustdoc-args = ["--cfg", "docsrs"] 36 | 37 | [dependencies] 38 | kube-derive = { path = "../kube-derive", version = "=0.75.0", optional = true } 39 | kube-core = { path = "../kube-core", version = "=0.75.0" } 40 | kube-client = { path = "../kube-client", version = "=0.75.0", default-features = false, optional = true } 41 | kube-runtime = { path = "../kube-runtime", version = "=0.75.0", optional = true} 42 | 43 | # Not used directly, but required by resolver 2.0 to ensure that the k8s-openapi dependency 44 | # is considered part of the "deps" graph rather than just the "dev-deps" graph 45 | [dependencies.k8s-openapi] 46 | version = "0.16.0" 47 | default-features = false 48 | 49 | [dev-dependencies] 50 | tokio = { version = "1.14.0", features = ["full"] } 51 | futures = "0.3.17" 52 | serde_json = "1.0.68" 53 | validator = { version = "0.16.0", features = ["derive"] } 54 | serde = { version = "1.0.130", features = ["derive"] } 55 | schemars = "0.8.6" 56 | 57 | [dev-dependencies.k8s-openapi] 58 | version = "0.16.0" 59 | default-features = false 60 | features = ["v1_25"] 61 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/release.toml: -------------------------------------------------------------------------------- 1 | # Release process :: cargo-release >= 0.18.3 2 | # 3 | # Dependencies: cargo-release, cargo-tree, sd, ripgrep 4 | # 5 | # 0. (optional) cargo release minor ; verify readme + changelog bumped; then git reset --hard 6 | # 1. PUBLISH_GRACE_SLEEP=20 cargo release minor --execute 7 | # 1X. - on failure: follow plan manually, cd into next dirs and publish insequence with cargo publish --features=k8s-openapi/v1_25 8 | # 2. check consolidated commit 9 | # 2X. - on failure: git commit --amend and insert version 10 | # 3. ./scripts/release-post.sh 11 | 12 | # Reference 13 | # https://github.com/sunng87/cargo-release/blob/master/docs/reference.md 14 | 15 | consolidate-commits = true 16 | shared-version = true 17 | pre-release-hook = ["../scripts/release-pre.sh"] 18 | pre-release-commit-message = "release {{version}}" 19 | # leave tagging + pushing to postrelease script (due to potential failures in 1 and 2) 20 | push = false 21 | tag = false 22 | # A Kubernetes version is normally supplied by the application consuming the library in the end. 23 | # Since we don't have that when verifying, supply one ourselves. 24 | enable-features = ["k8s-openapi/v1_25"] 25 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/rustfmt.toml: -------------------------------------------------------------------------------- 1 | overflow_delimited_expr = true 2 | newline_style = "Unix" 3 | imports_granularity = "Crate" 4 | reorder_impl_items = true 5 | blank_lines_upper_bound = 2 6 | comment_width = 110 7 | max_width = 110 8 | inline_attribute_width = 80 9 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/scripts/release-afterdoc.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -eo pipefail 3 | 4 | main() { 5 | if [ -z "$1" ]; then 6 | echo "please use ./release-afterdoc.sh TAG" 7 | echo "TAG is probably the result of: git tag -l | tail -n 1" 8 | exit 1 9 | fi 10 | local -r RELNAME="$1" 11 | local -r RELEASE="$(curl -sSL -H "Accept: application/vnd.github.v3+json" "https://api.github.com/repos/kube-rs/kube/releases/tags/${RELNAME}")" 12 | local -r RELREG="$(echo "${RELNAME}" | sd -s "." "\.")" 13 | local -r HURL="$(echo "${RELEASE}" | jq '.html_url' -r)" 14 | # Skipping New Contributors highight from CHANGELOG + across repos for brevity and to avoid pinging them excessively 15 | local -r BODY="$(echo "${RELEASE}" | jq '.body' -r | sd "## New Contributors[\w\W]*$" "")" 16 | if grep -E "^${RELREG} / " CHANGELOG.md; then 17 | # We only run the script if the headline is unchanged (done at the end) 18 | 19 | # Add in the body first 20 | sd "(^${RELREG} / [\d-]+\n===================\n)" "\$1${BODY}" CHANGELOG.md 21 | # fix newlines issues caused last jq/sd combo: (^M at end of lines) 22 | sd "\r" "" CHANGELOG.md 23 | 24 | # Link the headline 25 | sd "^${RELREG} / " "[${RELNAME}](${HURL}) / " CHANGELOG.md 26 | fi 27 | } 28 | 29 | # This script ports manual RELEASE notes into the CHANGELOG post publishing 30 | # and links to the github releases so that the website has good links. 31 | # 32 | # This is run manually after hitting publish on the auto-created draft release. 33 | # 34 | # Usage: 35 | # 36 | # ./scripts/release-afterdoc.sh 0.68.0 37 | # inspect diff, then commit and push if OK. 38 | # 39 | # shellcheck disable=SC2068 40 | main $@ 41 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/scripts/release-gh.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | 4 | main() { 5 | cd "$(dirname "${BASH_SOURCE[0]}")" && cd .. # aka $WORKSPACE_ROOT 6 | 7 | # allow passing in date so we can test this 8 | local -r DATE=${1:-$(date +%Y-%m-%d)} 9 | # extract a dated release between equals dividers (assuming consistent whitespace) 10 | grep "${DATE}" -A 250 CHANGELOG.md \ 11 | | tail -n +3 \ 12 | | sed '1,/===================/!d' \ 13 | | head -n -3 > release.txt 14 | 15 | # Add links to critical bugs 16 | local -r CRITISSUES="$(curl -sSL -H "Accept: application/vnd.github.v3+json" https://api.github.com/repos/kube-rs/kube/issues?labels=critical)" 17 | if (( $(echo "${CRITISSUES}" | jq length) > 0 )); then 18 | echo -e "\n### Known Issues" >> release.txt 19 | echo "${CRITISSUES}" | jq '.[] | "- \(.title) - #[\(.number)](\(.url))"' -r >> release.txt 20 | fi 21 | } 22 | 23 | # shellcheck disable=SC2068 24 | main $@ 25 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/scripts/release-post.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -euo pipefail 3 | 4 | main() { 5 | cd "$(dirname "${BASH_SOURCE[0]}")" && cd .. # aka $WORKSPACE_ROOT 6 | local -r CURRENT_VER="$(rg "kube =" README.md | head -n 1 | awk -F"\"" '{print $2}')" 7 | git tag -a "${CURRENT_VER}" -m "${CURRENT_VER}" 8 | git push 9 | git push --tags 10 | } 11 | 12 | # post release script run manually after cargo-release 13 | # shellcheck disable=SC2068 14 | main $@ 15 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/kube/tarpaulin.toml: -------------------------------------------------------------------------------- 1 | # Usage: configure your kubernetes context and run cargo tarpaulin 2 | # Runs integration tests (--ignored) plus --lib tests on main crates 3 | # 4 | # NB: cargo tarpaulin -- --test-threads 1 (can help diagnose test interdependencies) 5 | # NB: Tests should complete in about 30-60s after the compile 6 | # NB: full recompiles happen every time: https://github.com/xd009642/tarpaulin/issues/777 even with --skip-clean 7 | 8 | [one_pass_coverage] 9 | workspace = true 10 | features = "kube/derive kube/runtime kube/ws" 11 | color = "Always" 12 | ignored = true 13 | timeout = "600s" 14 | exclude = ["e2e"] 15 | # NB: proc macro code is not picked up by tarpaulin - so could maybe skip kube-derive completely 16 | excluded_files = ["kube-derive/tests"] 17 | # NB: skipping Doctests because they are slow to build and generally marked no_run 18 | run-types = ["Tests"] 19 | ignore_tests = true 20 | 21 | # We could potentially pass in examples here 22 | # but: they don't help in covering kube-derive, and they force a full recompile 23 | #[example_pass] 24 | #features = "default" 25 | #packages = ["kube-examples"] 26 | #excluded_files = ["examples/"] 27 | #example = ["crd_derive_schema"] 28 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/.github/docker/Dockerfile.ubuntu: -------------------------------------------------------------------------------- 1 | ARG VERSION="22.04" 2 | FROM ubuntu:${VERSION} 3 | 4 | ARG LLVM_VERSION="14" 5 | ENV LLVM_VERSION=$LLVM_VERSION 6 | 7 | ARG SHORTNAME="jammy" 8 | 9 | RUN apt-get update && apt-get install -y curl gnupg 10 | RUN if [ "${LLVM_VERSION}" = "16" ]; \ 11 | then \ 12 | echo "\n\ 13 | deb http://apt.llvm.org/${SHORTNAME}/ llvm-toolchain-${SHORTNAME} main\n\ 14 | deb-src http://apt.llvm.org/${SHORTNAME}/ llvm-toolchain-${SHORTNAME} main\n\ 15 | " >> /etc/apt/sources.list;\ 16 | else \ 17 | echo "\n\ 18 | deb http://apt.llvm.org/${SHORTNAME}/ llvm-toolchain-${SHORTNAME}-${LLVM_VERSION} main\n\ 19 | deb-src http://apt.llvm.org/${SHORTNAME}/ llvm-toolchain-${SHORTNAME}-${LLVM_VERSION} main\n\ 20 | " >> /etc/apt/sources.list; \ 21 | fi 22 | RUN curl -L https://apt.llvm.org/llvm-snapshot.gpg.key | apt-key add - 23 | 24 | ARG DEBIAN_FRONTEND="noninteractive" 25 | ENV TZ="Etc/UTC" 26 | 27 | RUN apt-get update && apt-get install -y \ 28 | libelf-dev \ 29 | zlib1g-dev \ 30 | libbfd-dev \ 31 | clang-${LLVM_VERSION} \ 32 | libclang-${LLVM_VERSION}-dev \ 33 | libclang-common-${LLVM_VERSION}-dev \ 34 | libclang1-${LLVM_VERSION} \ 35 | llvm-${LLVM_VERSION} \ 36 | llvm-${LLVM_VERSION}-dev \ 37 | llvm-${LLVM_VERSION}-runtime \ 38 | libllvm${LLVM_VERSION} \ 39 | make pkg-config \ 40 | rustc cargo rustfmt \ 41 | sudo \ 42 | && apt-get -y clean 43 | 44 | RUN ln -s /usr/bin/clang-${LLVM_VERSION} /usr/bin/clang && ln -s /usr/bin/llvm-strip-${LLVM_VERSION} /usr/bin/llvm-strip 45 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: libbpf-bootstrap build 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | 9 | jobs: 10 | build_libbpf_bootstrap: 11 | runs-on: ubuntu-latest 12 | strategy: 13 | fail-fast: false 14 | matrix: 15 | llvm: [14, 15, 16] 16 | steps: 17 | - uses: actions/checkout@v2 18 | with: 19 | submodules: recursive 20 | - name: Build container 21 | uses: docker/build-push-action@v3 22 | with: 23 | push: false 24 | build-args: LLVM_VERSION=${{ matrix.llvm }} 25 | file: ./.github/docker/Dockerfile.ubuntu 26 | tags: build_container 27 | - name: Build examples/c 28 | run: | 29 | docker run \ 30 | -v $(pwd):/libbpf-bootstrap \ 31 | build_container \ 32 | /bin/bash -c \ 33 | 'cd /libbpf-bootstrap/examples/c && make' 34 | - name: Build examples/rust 35 | run: | 36 | docker run \ 37 | -v $(pwd):/libbpf-bootstrap \ 38 | build_container \ 39 | /bin/bash -c \ 40 | 'cd /libbpf-bootstrap/examples/rust && cargo build' 41 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | /examples/c/build 3 | /examples/c/.xmake 4 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "libbpf"] 2 | path = libbpf 3 | url = https://github.com/libbpf/libbpf.git 4 | [submodule "bpftool"] 5 | path = bpftool 6 | url = https://github.com/libbpf/bpftool 7 | [submodule "blazesym"] 8 | path = blazesym 9 | url = https://github.com/libbpf/blazesym.git 10 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/LICENSE: -------------------------------------------------------------------------------- 1 | BSD 3-Clause License 2 | 3 | Copyright (c) 2020, Andrii Nakryiko 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | 1. Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | 12 | 2. Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | 3. Neither the name of the copyright holder nor the names of its 17 | contributors may be used to endorse or promote products derived from 18 | this software without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 23 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 24 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 25 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 26 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 27 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 28 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 29 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/c/.gitignore: -------------------------------------------------------------------------------- 1 | /.output 2 | /bootstrap 3 | /minimal 4 | /minimal_legacy 5 | /uprobe 6 | /kprobe 7 | /fentry 8 | /profile 9 | /usdt 10 | /sockfilter 11 | /tc 12 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/c/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause 2 | 3 | cmake_minimum_required(VERSION 3.16) 4 | project(examples) 5 | 6 | # Tell cmake where to find BpfObject module 7 | list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../tools/cmake) 8 | 9 | # Build vendored libbpf 10 | include(ExternalProject) 11 | ExternalProject_Add(libbpf 12 | PREFIX libbpf 13 | SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../libbpf/src 14 | CONFIGURE_COMMAND "" 15 | BUILD_COMMAND make 16 | BUILD_STATIC_ONLY=1 17 | OBJDIR=${CMAKE_CURRENT_BINARY_DIR}/libbpf/libbpf 18 | DESTDIR=${CMAKE_CURRENT_BINARY_DIR}/libbpf 19 | INCLUDEDIR= 20 | LIBDIR= 21 | UAPIDIR= 22 | install 23 | BUILD_IN_SOURCE TRUE 24 | INSTALL_COMMAND "" 25 | STEP_TARGETS build 26 | ) 27 | 28 | ExternalProject_Add(bpftool 29 | PREFIX bpftool 30 | SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../bpftool/src 31 | CONFIGURE_COMMAND "" 32 | BUILD_COMMAND make 33 | OUTPUT=${CMAKE_CURRENT_BINARY_DIR}/bpftool/ 34 | BUILD_IN_SOURCE TRUE 35 | INSTALL_COMMAND "" 36 | STEP_TARGETS build 37 | ) 38 | 39 | # Set BpfObject input parameters -- note this is usually not necessary unless 40 | # you're in a highly vendored environment (like libbpf-bootstrap) 41 | set(BPFOBJECT_BPFTOOL_EXE ${CMAKE_CURRENT_BINARY_DIR}/bpftool/bpftool) 42 | set(BPFOBJECT_VMLINUX_H ${CMAKE_CURRENT_SOURCE_DIR}/../../vmlinux/vmlinux.h) 43 | set(LIBBPF_INCLUDE_DIRS ${CMAKE_CURRENT_BINARY_DIR}/libbpf) 44 | set(LIBBPF_LIBRARIES ${CMAKE_CURRENT_BINARY_DIR}/libbpf/libbpf.a) 45 | find_package(BpfObject REQUIRED) 46 | 47 | # Create an executable for each application 48 | file(GLOB apps *.bpf.c) 49 | foreach(app ${apps}) 50 | get_filename_component(app_stem ${app} NAME_WE) 51 | 52 | # Build object skeleton and depend skeleton on libbpf build 53 | bpf_object(${app_stem} ${app_stem}.bpf.c) 54 | add_dependencies(${app_stem}_skel libbpf-build) 55 | 56 | add_executable(${app_stem} ${app_stem}.c) 57 | target_link_libraries(${app_stem} ${app_stem}_skel) 58 | endforeach() 59 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/c/bootstrap.h: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */ 2 | /* Copyright (c) 2020 Facebook */ 3 | #ifndef __BOOTSTRAP_H 4 | #define __BOOTSTRAP_H 5 | 6 | #define TASK_COMM_LEN 16 7 | #define MAX_FILENAME_LEN 127 8 | 9 | struct event { 10 | int pid; 11 | int ppid; 12 | unsigned exit_code; 13 | unsigned long long duration_ns; 14 | char comm[TASK_COMM_LEN]; 15 | char filename[MAX_FILENAME_LEN]; 16 | bool exit_event; 17 | }; 18 | 19 | #endif /* __BOOTSTRAP_H */ 20 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/c/fentry.bpf.c: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause 2 | /* Copyright (c) 2021 Sartura */ 3 | #include "vmlinux.h" 4 | #include 5 | #include 6 | 7 | char LICENSE[] SEC("license") = "Dual BSD/GPL"; 8 | 9 | SEC("fentry/do_unlinkat") 10 | int BPF_PROG(do_unlinkat, int dfd, struct filename *name) 11 | { 12 | pid_t pid; 13 | 14 | pid = bpf_get_current_pid_tgid() >> 32; 15 | bpf_printk("fentry: pid = %d, filename = %s\n", pid, name->name); 16 | return 0; 17 | } 18 | 19 | SEC("fexit/do_unlinkat") 20 | int BPF_PROG(do_unlinkat_exit, int dfd, struct filename *name, long ret) 21 | { 22 | pid_t pid; 23 | 24 | pid = bpf_get_current_pid_tgid() >> 32; 25 | bpf_printk("fexit: pid = %d, filename = %s, ret = %ld\n", pid, name->name, ret); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/c/fentry.c: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) 2 | /* Copyright (c) 2021 Sartura 3 | * Based on minimal.c by Facebook */ 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "fentry.skel.h" 13 | 14 | static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args) 15 | { 16 | return vfprintf(stderr, format, args); 17 | } 18 | 19 | static volatile sig_atomic_t stop; 20 | 21 | void sig_int(int signo) 22 | { 23 | stop = 1; 24 | } 25 | 26 | int main(int argc, char **argv) 27 | { 28 | struct fentry_bpf *skel; 29 | int err; 30 | 31 | libbpf_set_strict_mode(LIBBPF_STRICT_ALL); 32 | /* Set up libbpf errors and debug info callback */ 33 | libbpf_set_print(libbpf_print_fn); 34 | 35 | /* Open load and verify BPF application */ 36 | skel = fentry_bpf__open_and_load(); 37 | if (!skel) { 38 | fprintf(stderr, "Failed to open BPF skeleton\n"); 39 | return 1; 40 | } 41 | 42 | /* Attach tracepoint handler */ 43 | err = fentry_bpf__attach(skel); 44 | if (err) { 45 | fprintf(stderr, "Failed to attach BPF skeleton\n"); 46 | goto cleanup; 47 | } 48 | 49 | if (signal(SIGINT, sig_int) == SIG_ERR) { 50 | fprintf(stderr, "can't set signal handler: %s\n", strerror(errno)); 51 | goto cleanup; 52 | } 53 | 54 | printf("Successfully started! Please run `sudo cat /sys/kernel/debug/tracing/trace_pipe` " 55 | "to see output of the BPF programs.\n"); 56 | 57 | while (!stop) { 58 | fprintf(stderr, "."); 59 | sleep(1); 60 | } 61 | 62 | cleanup: 63 | fentry_bpf__destroy(skel); 64 | return -err; 65 | } 66 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/c/kprobe.bpf.c: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause 2 | /* Copyright (c) 2021 Sartura */ 3 | #include "vmlinux.h" 4 | #include 5 | #include 6 | #include 7 | 8 | char LICENSE[] SEC("license") = "Dual BSD/GPL"; 9 | 10 | SEC("kprobe/do_unlinkat") 11 | int BPF_KPROBE(do_unlinkat, int dfd, struct filename *name) 12 | { 13 | pid_t pid; 14 | const char *filename; 15 | 16 | pid = bpf_get_current_pid_tgid() >> 32; 17 | filename = BPF_CORE_READ(name, name); 18 | bpf_printk("KPROBE ENTRY pid = %d, filename = %s\n", pid, filename); 19 | return 0; 20 | } 21 | 22 | SEC("kretprobe/do_unlinkat") 23 | int BPF_KRETPROBE(do_unlinkat_exit, long ret) 24 | { 25 | pid_t pid; 26 | 27 | pid = bpf_get_current_pid_tgid() >> 32; 28 | bpf_printk("KPROBE EXIT: pid = %d, ret = %ld\n", pid, ret); 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/c/kprobe.c: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) 2 | /* Copyright (c) 2021 Sartura 3 | * Based on minimal.c by Facebook */ 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "kprobe.skel.h" 13 | 14 | static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args) 15 | { 16 | return vfprintf(stderr, format, args); 17 | } 18 | 19 | static volatile sig_atomic_t stop; 20 | 21 | static void sig_int(int signo) 22 | { 23 | stop = 1; 24 | } 25 | 26 | int main(int argc, char **argv) 27 | { 28 | struct kprobe_bpf *skel; 29 | int err; 30 | 31 | libbpf_set_strict_mode(LIBBPF_STRICT_ALL); 32 | /* Set up libbpf errors and debug info callback */ 33 | libbpf_set_print(libbpf_print_fn); 34 | 35 | /* Open load and verify BPF application */ 36 | skel = kprobe_bpf__open_and_load(); 37 | if (!skel) { 38 | fprintf(stderr, "Failed to open BPF skeleton\n"); 39 | return 1; 40 | } 41 | 42 | /* Attach tracepoint handler */ 43 | err = kprobe_bpf__attach(skel); 44 | if (err) { 45 | fprintf(stderr, "Failed to attach BPF skeleton\n"); 46 | goto cleanup; 47 | } 48 | 49 | if (signal(SIGINT, sig_int) == SIG_ERR) { 50 | fprintf(stderr, "can't set signal handler: %s\n", strerror(errno)); 51 | goto cleanup; 52 | } 53 | 54 | printf("Successfully started! Please run `sudo cat /sys/kernel/debug/tracing/trace_pipe` " 55 | "to see output of the BPF programs.\n"); 56 | 57 | while (!stop) { 58 | fprintf(stderr, "."); 59 | sleep(1); 60 | } 61 | 62 | cleanup: 63 | kprobe_bpf__destroy(skel); 64 | return -err; 65 | } 66 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/c/minimal.bpf.c: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause 2 | /* Copyright (c) 2020 Facebook */ 3 | #include 4 | #include 5 | 6 | char LICENSE[] SEC("license") = "Dual BSD/GPL"; 7 | 8 | int my_pid = 0; 9 | 10 | SEC("tp/syscalls/sys_enter_write") 11 | int handle_tp(void *ctx) 12 | { 13 | int pid = bpf_get_current_pid_tgid() >> 32; 14 | 15 | if (pid != my_pid) 16 | return 0; 17 | 18 | bpf_printk("BPF triggered from PID %d.\n", pid); 19 | 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/c/minimal.c: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) 2 | /* Copyright (c) 2020 Facebook */ 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include "minimal.skel.h" 8 | 9 | static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args) 10 | { 11 | return vfprintf(stderr, format, args); 12 | } 13 | 14 | int main(int argc, char **argv) 15 | { 16 | struct minimal_bpf *skel; 17 | int err; 18 | 19 | libbpf_set_strict_mode(LIBBPF_STRICT_ALL); 20 | /* Set up libbpf errors and debug info callback */ 21 | libbpf_set_print(libbpf_print_fn); 22 | 23 | /* Open BPF application */ 24 | skel = minimal_bpf__open(); 25 | if (!skel) { 26 | fprintf(stderr, "Failed to open BPF skeleton\n"); 27 | return 1; 28 | } 29 | 30 | /* ensure BPF program only handles write() syscalls from our process */ 31 | skel->bss->my_pid = getpid(); 32 | 33 | /* Load & verify BPF programs */ 34 | err = minimal_bpf__load(skel); 35 | if (err) { 36 | fprintf(stderr, "Failed to load and verify BPF skeleton\n"); 37 | goto cleanup; 38 | } 39 | 40 | /* Attach tracepoint handler */ 41 | err = minimal_bpf__attach(skel); 42 | if (err) { 43 | fprintf(stderr, "Failed to attach BPF skeleton\n"); 44 | goto cleanup; 45 | } 46 | 47 | printf("Successfully started! Please run `sudo cat /sys/kernel/debug/tracing/trace_pipe` " 48 | "to see output of the BPF programs.\n"); 49 | 50 | for (;;) { 51 | /* trigger our BPF program */ 52 | fprintf(stderr, "."); 53 | sleep(1); 54 | } 55 | 56 | cleanup: 57 | minimal_bpf__destroy(skel); 58 | return -err; 59 | } 60 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/c/minimal_legacy.bpf.c: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */ 2 | #define BPF_NO_GLOBAL_DATA 3 | #include 4 | #include 5 | #include 6 | 7 | typedef unsigned int u32; 8 | typedef int pid_t; 9 | 10 | char LICENSE[] SEC("license") = "Dual BSD/GPL"; 11 | 12 | /* Create an array with 1 entry instead of a global variable 13 | * which does not work with older kernels */ 14 | struct { 15 | __uint(type, BPF_MAP_TYPE_ARRAY); 16 | __uint(max_entries, 1); 17 | __type(key, u32); 18 | __type(value, pid_t); 19 | } my_pid_map SEC(".maps"); 20 | 21 | SEC("tp/syscalls/sys_enter_write") 22 | int handle_tp(void *ctx) 23 | { 24 | u32 index = 0; 25 | pid_t pid = bpf_get_current_pid_tgid() >> 32; 26 | pid_t *my_pid = bpf_map_lookup_elem(&my_pid_map, &index); 27 | 28 | if (!my_pid || *my_pid != pid) 29 | return 1; 30 | 31 | bpf_printk("BPF triggered from PID %d.\n", pid); 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/c/minimal_legacy.c: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */ 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include "minimal_legacy.skel.h" 7 | 8 | static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args) 9 | { 10 | return vfprintf(stderr, format, args); 11 | } 12 | 13 | int main(int argc, char **argv) 14 | { 15 | struct minimal_legacy_bpf *skel; 16 | int err; 17 | pid_t pid; 18 | unsigned index = 0; 19 | 20 | libbpf_set_strict_mode(LIBBPF_STRICT_ALL); 21 | /* Set up libbpf errors and debug info callback */ 22 | libbpf_set_print(libbpf_print_fn); 23 | 24 | /* Load and verify BPF application */ 25 | skel = minimal_legacy_bpf__open_and_load(); 26 | if (!skel) { 27 | fprintf(stderr, "Failed to open and load BPF skeleton\n"); 28 | return 1; 29 | } 30 | 31 | /* ensure BPF program only handles write() syscalls from our process */ 32 | pid = getpid(); 33 | err = bpf_map__update_elem(skel->maps.my_pid_map, &index, sizeof(index), &pid, sizeof(pid_t), BPF_ANY); 34 | if (err < 0) { 35 | fprintf(stderr, "Error updating map with pid: %s\n", strerror(err)); 36 | goto cleanup; 37 | } 38 | 39 | /* Attach tracepoint handler */ 40 | err = minimal_legacy_bpf__attach(skel); 41 | if (err) { 42 | fprintf(stderr, "Failed to attach BPF skeleton\n"); 43 | goto cleanup; 44 | } 45 | 46 | printf("Successfully started! Please run `sudo cat /sys/kernel/debug/tracing/trace_pipe` " 47 | "to see output of the BPF programs.\n"); 48 | 49 | for (;;) { 50 | /* trigger our BPF program */ 51 | fprintf(stderr, "."); 52 | sleep(1); 53 | } 54 | 55 | cleanup: 56 | minimal_legacy_bpf__destroy(skel); 57 | return -err; 58 | } 59 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/c/profile.bpf.c: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause 2 | /* Copyright (c) 2022 Meta Platforms, Inc. */ 3 | #include "vmlinux.h" 4 | #include 5 | #include 6 | #include 7 | 8 | #include "profile.h" 9 | 10 | char LICENSE[] SEC("license") = "Dual BSD/GPL"; 11 | 12 | struct { 13 | __uint(type, BPF_MAP_TYPE_RINGBUF); 14 | __uint(max_entries, 256 * 1024); 15 | } events SEC(".maps"); 16 | 17 | SEC("perf_event") 18 | int profile(void *ctx) 19 | { 20 | int pid = bpf_get_current_pid_tgid() >> 32; 21 | int cpu_id = bpf_get_smp_processor_id(); 22 | struct stacktrace_event *event; 23 | int cp; 24 | 25 | event = bpf_ringbuf_reserve(&events, sizeof(*event), 0); 26 | if (!event) 27 | return 1; 28 | 29 | event->pid = pid; 30 | event->cpu_id = cpu_id; 31 | 32 | if (bpf_get_current_comm(event->comm, sizeof(event->comm))) 33 | event->comm[0] = 0; 34 | 35 | event->kstack_sz = bpf_get_stack(ctx, event->kstack, sizeof(event->kstack), 0); 36 | 37 | event->ustack_sz = bpf_get_stack(ctx, event->ustack, sizeof(event->ustack), BPF_F_USER_STACK); 38 | 39 | bpf_ringbuf_submit(event, 0); 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/c/profile.h: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */ 2 | /* Copyright (c) 2022 Meta Platforms, Inc. */ 3 | #ifndef __PROFILE_H_ 4 | #define __PROFILE_H_ 5 | 6 | #ifndef TASK_COMM_LEN 7 | #define TASK_COMM_LEN 16 8 | #endif 9 | 10 | #ifndef MAX_STACK_DEPTH 11 | #define MAX_STACK_DEPTH 128 12 | #endif 13 | 14 | typedef __u64 stack_trace_t[MAX_STACK_DEPTH]; 15 | 16 | struct stacktrace_event { 17 | __u32 pid; 18 | __u32 cpu_id; 19 | char comm[TASK_COMM_LEN]; 20 | __s32 kstack_sz; 21 | __s32 ustack_sz; 22 | stack_trace_t kstack; 23 | stack_trace_t ustack; 24 | }; 25 | 26 | #endif /* __PROFILE_H_ */ 27 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/c/sockfilter.bpf.c: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause 2 | /* Copyright (c) 2022 Jacky Yin */ 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "sockfilter.h" 11 | 12 | #define IP_MF 0x2000 13 | #define IP_OFFSET 0x1FFF 14 | 15 | char LICENSE[] SEC("license") = "Dual BSD/GPL"; 16 | 17 | struct { 18 | __uint(type, BPF_MAP_TYPE_RINGBUF); 19 | __uint(max_entries, 256 * 1024); 20 | } rb SEC(".maps"); 21 | 22 | static inline int ip_is_fragment(struct __sk_buff *skb, __u32 nhoff) 23 | { 24 | __u16 frag_off; 25 | 26 | bpf_skb_load_bytes(skb, nhoff + offsetof(struct iphdr, frag_off), &frag_off, 2); 27 | frag_off = __bpf_ntohs(frag_off); 28 | return frag_off & (IP_MF | IP_OFFSET); 29 | } 30 | 31 | SEC("socket") 32 | int socket_handler(struct __sk_buff *skb) 33 | { 34 | struct so_event *e; 35 | __u8 verlen; 36 | __u16 proto; 37 | __u32 nhoff = ETH_HLEN; 38 | 39 | bpf_skb_load_bytes(skb, 12, &proto, 2); 40 | proto = __bpf_ntohs(proto); 41 | if (proto != ETH_P_IP) 42 | return 0; 43 | 44 | if (ip_is_fragment(skb, nhoff)) 45 | return 0; 46 | 47 | /* reserve sample from BPF ringbuf */ 48 | e = bpf_ringbuf_reserve(&rb, sizeof(*e), 0); 49 | if (!e) 50 | return 0; 51 | 52 | bpf_skb_load_bytes(skb, nhoff + offsetof(struct iphdr, protocol), &e->ip_proto, 1); 53 | 54 | if (e->ip_proto != IPPROTO_GRE) { 55 | bpf_skb_load_bytes(skb, nhoff + offsetof(struct iphdr, saddr), &(e->src_addr), 4); 56 | bpf_skb_load_bytes(skb, nhoff + offsetof(struct iphdr, daddr), &(e->dst_addr), 4); 57 | } 58 | 59 | bpf_skb_load_bytes(skb, nhoff + 0, &verlen, 1); 60 | bpf_skb_load_bytes(skb, nhoff + ((verlen & 0xF) << 2), &(e->ports), 4); 61 | e->pkt_type = skb->pkt_type; 62 | e->ifindex = skb->ifindex; 63 | bpf_ringbuf_submit(e, 0); 64 | 65 | return skb->len; 66 | } 67 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/c/sockfilter.h: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause 2 | /* Copyright (c) 2022 Jacky Yin */ 3 | #ifndef __SOCKFILTER_H 4 | #define __SOCKFILTER_H 5 | 6 | struct so_event { 7 | __be32 src_addr; 8 | __be32 dst_addr; 9 | union { 10 | __be32 ports; 11 | __be16 port16[2]; 12 | }; 13 | __u32 ip_proto; 14 | __u32 pkt_type; 15 | __u32 ifindex; 16 | }; 17 | 18 | #endif /* __SOCKFILTER_H */ 19 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/c/tc.bpf.c: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) 2 | /* Copyright (c) 2022 Hengqi Chen */ 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #define TC_ACT_OK 0 9 | #define ETH_P_IP 0x0800 /* Internet Protocol packet */ 10 | 11 | SEC("tc") 12 | int tc_ingress(struct __sk_buff *ctx) 13 | { 14 | void *data_end = (void *)(__u64)ctx->data_end; 15 | void *data = (void *)(__u64)ctx->data; 16 | struct ethhdr *l2; 17 | struct iphdr *l3; 18 | 19 | if (ctx->protocol != bpf_htons(ETH_P_IP)) 20 | return TC_ACT_OK; 21 | 22 | l2 = data; 23 | if ((void *)(l2 + 1) > data_end) 24 | return TC_ACT_OK; 25 | 26 | l3 = (struct iphdr *)(l2 + 1); 27 | if ((void *)(l3 + 1) > data_end) 28 | return TC_ACT_OK; 29 | 30 | bpf_printk("Got IP packet: tot_len: %d, ttl: %d", bpf_ntohs(l3->tot_len), l3->ttl); 31 | return TC_ACT_OK; 32 | } 33 | 34 | char __license[] SEC("license") = "GPL"; 35 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/c/uprobe.bpf.c: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause 2 | /* Copyright (c) 2020 Facebook */ 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | char LICENSE[] SEC("license") = "Dual BSD/GPL"; 9 | 10 | SEC("uprobe") 11 | int BPF_KPROBE(uprobe_add, int a, int b) 12 | { 13 | bpf_printk("uprobed_add ENTRY: a = %d, b = %d", a, b); 14 | return 0; 15 | } 16 | 17 | SEC("uretprobe") 18 | int BPF_KRETPROBE(uretprobe_add, int ret) 19 | { 20 | bpf_printk("uprobed_add EXIT: return = %d", ret); 21 | return 0; 22 | } 23 | 24 | SEC("uprobe//proc/self/exe:uprobed_sub") 25 | int BPF_KPROBE(uprobe_sub, int a, int b) 26 | { 27 | bpf_printk("uprobed_sub ENTRY: a = %d, b = %d", a, b); 28 | return 0; 29 | } 30 | 31 | SEC("uretprobe//proc/self/exe:uprobed_sub") 32 | int BPF_KRETPROBE(uretprobe_sub, int ret) 33 | { 34 | bpf_printk("uprobed_sub EXIT: return = %d", ret); 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/c/usdt.bpf.c: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) 2 | /* Copyright (c) 2022 Hengqi Chen */ 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | pid_t my_pid; 9 | 10 | SEC("usdt/libc.so.6:libc:setjmp") 11 | int BPF_USDT(usdt_auto_attach, void *arg1, int arg2, void *arg3) 12 | { 13 | pid_t pid = bpf_get_current_pid_tgid() >> 32; 14 | 15 | if (pid != my_pid) 16 | return 0; 17 | 18 | bpf_printk("USDT auto attach to libc:setjmp: arg1 = %lx, arg2 = %d, arg3 = %lx", arg1, arg2, arg3); 19 | return 0; 20 | } 21 | 22 | SEC("usdt") 23 | int BPF_USDT(usdt_manual_attach, void *arg1, int arg2, void *arg3) 24 | { 25 | bpf_printk("USDT manual attach to libc:setjmp: arg1 = %lx, arg2 = %d, arg3 = %lx", arg1, arg2, arg3); 26 | return 0; 27 | } 28 | 29 | char LICENSE[] SEC("license") = "Dual BSD/GPL"; 30 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/rust/.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/rust/Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [ 3 | "tracecon", 4 | "xdp", 5 | "profile", 6 | ] 7 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/rust/profile/.gitignore: -------------------------------------------------------------------------------- 1 | /src/bpf/.output 2 | /target 3 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/rust/profile/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "profile" 3 | version = "0.1.0" 4 | authors = ["Kuifeng Lee "] 5 | license = "GPL-2.0 OR BSD-3-Clause" 6 | 7 | [dependencies] 8 | libbpf-rs = "0.14.0" 9 | nix = "0.24.1" 10 | blazesym = { git = "https://github.com/libbpf/blazesym.git", features = ["cheader"] } 11 | libc = "*" 12 | clap = { version = "3.1.18", features = ["derive"] } 13 | 14 | [build-dependencies] 15 | libbpf-cargo = "0.9.3" 16 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/rust/profile/build.rs: -------------------------------------------------------------------------------- 1 | use std::fs::create_dir_all; 2 | use std::path::Path; 3 | 4 | extern crate libbpf_cargo; 5 | use libbpf_cargo::SkeletonBuilder; 6 | 7 | const SRC: &str = "./src/bpf/profile.bpf.c"; 8 | 9 | fn main() { 10 | // It's unfortunate we cannot use `OUT_DIR` to store the generated skeleton. 11 | // Reasons are because the generated skeleton contains compiler attributes 12 | // that cannot be `include!()`ed via macro. And we cannot use the `#[path = "..."]` 13 | // trick either because you cannot yet `concat!(env!("OUT_DIR"), "/skel.rs")` inside 14 | // the path attribute either (see https://github.com/rust-lang/rust/pull/83366). 15 | // 16 | // However, there is hope! When the above feature stabilizes we can clean this 17 | // all up. 18 | create_dir_all("./src/bpf/.output").unwrap(); 19 | let skel = Path::new("./src/bpf/.output/profile.skel.rs"); 20 | SkeletonBuilder::new(SRC) 21 | .generate(&skel) 22 | .expect("bpf compilation failed"); 23 | println!("cargo:rerun-if-changed={}", SRC); 24 | } 25 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/rust/profile/src/bpf/profile.bpf.c: -------------------------------------------------------------------------------- 1 | ../../../../c/profile.bpf.c -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/rust/profile/src/bpf/profile.h: -------------------------------------------------------------------------------- 1 | ../../../../c/profile.h -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/rust/profile/src/bpf/vmlinux.h: -------------------------------------------------------------------------------- 1 | ../../../../../vmlinux/vmlinux.h -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/rust/profile/src/syscall.rs: -------------------------------------------------------------------------------- 1 | extern crate libc; 2 | 3 | #[repr(C)] 4 | pub union sample_un { 5 | pub sample_period: u64, 6 | pub sample_freq: u64, 7 | } 8 | 9 | #[repr(C)] 10 | pub union wakeup_un { 11 | pub wakeup_events: u32, 12 | pub wakeup_atermark: u32, 13 | } 14 | 15 | #[repr(C)] 16 | pub union bp_1_un { 17 | pub bp_addr: u64, 18 | pub kprobe_func: u64, 19 | pub uprobe_path: u64, 20 | pub config1: u64, 21 | } 22 | 23 | #[repr(C)] 24 | pub union bp_2_un { 25 | pub bp_len: u64, 26 | pub kprobe_addr: u64, 27 | pub probe_offset: u64, 28 | pub config2: u64, 29 | } 30 | 31 | #[repr(C)] 32 | pub struct perf_event_attr { 33 | pub _type: u32, 34 | pub size: u32, 35 | pub config: u64, 36 | pub sample: sample_un, 37 | pub sample_type: u64, 38 | pub read_format: u64, 39 | pub flags: u64, 40 | pub wakeup: wakeup_un, 41 | pub bp_type: u32, 42 | pub bp_1: bp_1_un, 43 | pub bp_2: bp_2_un, 44 | pub branch_sample_type: u64, 45 | pub sample_regs_user: u64, 46 | pub sample_stack_user: u32, 47 | pub clockid: i32, 48 | pub sample_regs_intr: u64, 49 | pub aux_watermark: u32, 50 | pub sample_max_stack: u16, 51 | pub __reserved_2: u16, 52 | pub aux_sample_size: u32, 53 | pub __reserved_3: u32, 54 | } 55 | 56 | pub const PERF_TYPE_HARDWARE: u32 = 0; 57 | pub const PERF_COUNT_HW_CPU_CYCLES: u64 = 0; 58 | 59 | extern "C" { 60 | fn syscall(number: libc::c_long, ...) -> libc::c_long; 61 | } 62 | 63 | pub fn perf_event_open( 64 | hw_event: &perf_event_attr, 65 | pid: libc::pid_t, 66 | cpu: libc::c_int, 67 | group_fd: libc::c_int, 68 | flags: libc::c_ulong, 69 | ) -> libc::c_long { 70 | unsafe { 71 | syscall( 72 | libc::SYS_perf_event_open, 73 | hw_event as *const perf_event_attr, 74 | pid, 75 | cpu, 76 | group_fd, 77 | flags, 78 | ) 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/rust/tracecon/.gitignore: -------------------------------------------------------------------------------- 1 | /src/bpf/.output 2 | /target 3 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/rust/tracecon/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tracecon" 3 | version = "0.1.0" 4 | authors = ["Magnus Kulke "] 5 | edition = "2018" 6 | license = "GPL-2.0 OR BSD-3-Clause" 7 | 8 | [dependencies] 9 | anyhow = "1.0" 10 | libbpf-rs = "0.14.0" 11 | libc = "0.2" 12 | structopt = "0.3" 13 | ctrlc = "3.1" 14 | object = "0.25" 15 | plain = "0.2" 16 | 17 | [build-dependencies] 18 | libbpf-cargo = "0.9.3" 19 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/rust/tracecon/build.rs: -------------------------------------------------------------------------------- 1 | use std::fs::create_dir_all; 2 | use std::path::Path; 3 | 4 | use libbpf_cargo::SkeletonBuilder; 5 | 6 | const SRC: &str = "./src/bpf/tracecon.bpf.c"; 7 | 8 | fn main() { 9 | // It's unfortunate we cannot use `OUT_DIR` to store the generated skeleton. 10 | // Reasons are because the generated skeleton contains compiler attributes 11 | // that cannot be `include!()`ed via macro. And we cannot use the `#[path = "..."]` 12 | // trick either because you cannot yet `concat!(env!("OUT_DIR"), "/skel.rs")` inside 13 | // the path attribute either (see https://github.com/rust-lang/rust/pull/83366). 14 | // 15 | // However, there is hope! When the above feature stabilizes we can clean this 16 | // all up. 17 | create_dir_all("./src/bpf/.output").unwrap(); 18 | let skel = Path::new("./src/bpf/.output/tracecon.skel.rs"); 19 | SkeletonBuilder::new(SRC) 20 | .generate(&skel) 21 | .expect("bpf compilation failed"); 22 | println!("cargo:rerun-if-changed={}", SRC); 23 | } 24 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/rust/tracecon/src/bpf/vmlinux.h: -------------------------------------------------------------------------------- 1 | ../../../../../vmlinux/vmlinux.h -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/rust/xdp/.gitignore: -------------------------------------------------------------------------------- 1 | /src/bpf/.output 2 | /target 3 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/rust/xdp/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "xdp" 3 | version = "0.1.0" 4 | authors = ["Hengqi Chen "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | anyhow = "1.0" 11 | ctrlc = { version = "3.0", features = ["termination"] } 12 | libc = "0.2" 13 | libbpf-rs = "0.14.0" 14 | structopt = "0.3" 15 | 16 | [build-dependencies] 17 | libbpf-cargo = "0.9.3" 18 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/rust/xdp/build.rs: -------------------------------------------------------------------------------- 1 | use std::fs::create_dir_all; 2 | use std::path::Path; 3 | 4 | use libbpf_cargo::SkeletonBuilder; 5 | 6 | const SRC: &str = "./src/bpf/xdppass.bpf.c"; 7 | 8 | fn main() { 9 | // It's unfortunate we cannot use `OUT_DIR` to store the generated skeleton. 10 | // Reasons are because the generated skeleton contains compiler attributes 11 | // that cannot be `include!()`ed via macro. And we cannot use the `#[path = "..."]` 12 | // trick either because you cannot yet `concat!(env!("OUT_DIR"), "/skel.rs")` inside 13 | // the path attribute either (see https://github.com/rust-lang/rust/pull/83366). 14 | // 15 | // However, there is hope! When the above feature stabilizes we can clean this 16 | // all up. 17 | create_dir_all("./src/bpf/.output").unwrap(); 18 | let skel = Path::new("./src/bpf/.output/xdppass.skel.rs"); 19 | SkeletonBuilder::new(SRC).generate(&skel).unwrap(); 20 | println!("cargo:rerun-if-changed={}", SRC); 21 | } 22 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/rust/xdp/src/bpf/vmlinux.h: -------------------------------------------------------------------------------- 1 | ../../../../../vmlinux/vmlinux.h -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/rust/xdp/src/bpf/xdppass.bpf.c: -------------------------------------------------------------------------------- 1 | #include "vmlinux.h" 2 | #include 3 | 4 | SEC("xdp") 5 | int xdp_pass(struct xdp_md *ctx) 6 | { 7 | void *data = (void *)(long)ctx->data; 8 | void *data_end = (void *)(long)ctx->data_end; 9 | int pkt_sz = data_end - data; 10 | 11 | bpf_printk("packet size: %d", pkt_sz); 12 | return XDP_PASS; 13 | } 14 | 15 | char __license[] SEC("license") = "GPL"; 16 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/examples/rust/xdp/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::sync::atomic::{AtomicBool, Ordering}; 2 | use std::sync::Arc; 3 | use std::{thread, time}; 4 | 5 | use anyhow::{bail, Result}; 6 | use structopt::StructOpt; 7 | 8 | #[path = "bpf/.output/xdppass.skel.rs"] 9 | mod xdppass; 10 | use xdppass::*; 11 | 12 | #[derive(Debug, StructOpt)] 13 | struct Command { 14 | /// Interface index to attach XDP program 15 | #[structopt(default_value = "0")] 16 | ifindex: i32, 17 | } 18 | 19 | fn bump_memlock_rlimit() -> Result<()> { 20 | let rlimit = libc::rlimit { 21 | rlim_cur: 128 << 20, 22 | rlim_max: 128 << 20, 23 | }; 24 | 25 | if unsafe { libc::setrlimit(libc::RLIMIT_MEMLOCK, &rlimit) } != 0 { 26 | bail!("Failed to increase rlimit"); 27 | } 28 | 29 | Ok(()) 30 | } 31 | 32 | fn main() -> Result<()> { 33 | let opts = Command::from_args(); 34 | 35 | bump_memlock_rlimit()?; 36 | 37 | let skel_builder = XdppassSkelBuilder::default(); 38 | let open_skel = skel_builder.open()?; 39 | let mut skel = open_skel.load()?; 40 | let link = skel.progs_mut().xdp_pass().attach_xdp(opts.ifindex)?; 41 | skel.links = XdppassLinks { 42 | xdp_pass: Some(link), 43 | }; 44 | 45 | let running = Arc::new(AtomicBool::new(true)); 46 | let r = running.clone(); 47 | ctrlc::set_handler(move || { 48 | r.store(false, Ordering::SeqCst); 49 | })?; 50 | 51 | while running.load(Ordering::SeqCst) { 52 | eprint!("."); 53 | thread::sleep(time::Duration::from_secs(1)); 54 | } 55 | 56 | Ok(()) 57 | } 58 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/tools/cmake/FindLibBpf.cmake: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause 2 | 3 | find_path(LIBBPF_INCLUDE_DIRS 4 | NAMES 5 | bpf/bpf.h 6 | bpf/btf.h 7 | bpf/libbpf.h 8 | PATHS 9 | /usr/include 10 | /usr/local/include 11 | /opt/local/include 12 | /sw/include 13 | ENV CPATH) 14 | 15 | find_library(LIBBPF_LIBRARIES 16 | NAMES 17 | bpf 18 | PATHS 19 | /usr/lib 20 | /usr/local/lib 21 | /opt/local/lib 22 | /sw/lib 23 | ENV LIBRARY_PATH 24 | ENV LD_LIBRARY_PATH) 25 | 26 | include (FindPackageHandleStandardArgs) 27 | 28 | FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibBpf "Please install the libbpf development package" 29 | LIBBPF_LIBRARIES 30 | LIBBPF_INCLUDE_DIRS) 31 | 32 | mark_as_advanced(LIBBPF_INCLUDE_DIRS LIBBPF_LIBRARIES) 33 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/tools/gen_vmlinux_h.sh: -------------------------------------------------------------------------------- 1 | #/bin/sh 2 | 3 | $(dirname "$0")/bpftool btf dump file ${1:-/sys/kernel/btf/vmlinux} format c 4 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/vmlinux/arm64/vmlinux.h: -------------------------------------------------------------------------------- 1 | vmlinux_516.h -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/vmlinux/vmlinux.h: -------------------------------------------------------------------------------- 1 | x86/vmlinux_508.h -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-bootstrap/vmlinux/x86/vmlinux.h: -------------------------------------------------------------------------------- 1 | vmlinux_508.h -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/.gitattributes: -------------------------------------------------------------------------------- 1 | vmlinux*.h linguist-generated 2 | bpf_helper_defs.h linguist-generated 3 | bpf_helpers.h linguist-generated 4 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | strategy: 13 | fail-fast: false 14 | matrix: 15 | # Please adjust README when bumping version. 16 | rust: [stable, 1.59.0] 17 | steps: 18 | - uses: actions/checkout@v3 19 | - name: Install Rust 20 | uses: actions-rs/toolchain@v1.0.6 21 | with: 22 | profile: minimal 23 | toolchain: ${{ matrix.rust }} 24 | components: rustfmt, clippy 25 | override: true 26 | - name: Install deps 27 | run: sudo apt-get install -y clang-12 libelf-dev zlib1g-dev 28 | - name: Symlink clang 29 | run: sudo rm -f /bin/clang && sudo ln -s /usr/bin/clang-12 /bin/clang 30 | - name: Build 31 | run: cargo build --verbose --workspace --exclude runqslower 32 | - name: Build capable example with static libelf and libz 33 | run: RUSTFLAGS='-L /usr/lib/x86_64-linux-gnu' cargo b --package capable --features=static 34 | - name: Run tests 35 | # Skip BTF tests which require sudo 36 | # Skip BTF dump float test for now, we can enable it when we have access to clang 13+ 37 | run: cargo test --verbose --workspace --exclude runqslower -- --skip test_object --skip test_btf_dump_float --skip test_tc 38 | - name: Run BTF tests 39 | run: cd libbpf-rs && cargo test --verbose -- test_object test_tc 40 | - name: Run rustfmt 41 | run: cargo fmt --package libbpf-cargo libbpf-rs -- --check 42 | - name: Run clippy 43 | run: cargo clippy --tests -- -D warnings 44 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | target 4 | 5 | # These are backup files generated by rustfmt 6 | **/*.rs.bk 7 | 8 | #IDE files 9 | .idea -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to **libbpf-rs** 2 | 3 | ### Anyone is welcome to make **libbpf-rs** better! 4 | 5 | Thank you for wanting to contribute to **libbpf-rs**. We are delighted to have you. 6 | 7 | **libbpf-rs** is an open source project and we love receiving contributions from the 8 | community! There are many ways to contribute, such as improving the 9 | documentation, submitting bug reports and feature requests, reviewing code, 10 | answering questions on pull requests, and submitting code that can be merged into 11 | **libbpf-rs** itself. 12 | 13 | ## Code of Conduct 14 | 15 | **libbpf-rs** adopts and adheres to the Linux [Code of 16 | Conduct](https://www.kernel.org/doc/html/latest/process/code-of-conduct.html). 17 | 18 | ## Triaging Issues and Pull Requests 19 | 20 | One great way you can contribute to the project without writing any code is to 21 | help triage issues and pull requests as they come in. 22 | 23 | - Ask for more information if you believe the issue does not provide all the 24 | details required to solve it. 25 | - Flag issues that are stale or that should be closed. 26 | - Review code. 27 | 28 | ## Submitting a Pull Request 29 | 30 | Here are some suggested guidelines for a smooth experience: 31 | 32 | - **Pull requests should be against `master`.** 33 | All pull requests should be opened against the `master` branch. 34 | 35 | - **Keep your commits small.** 36 | If your changes are big (~300+ lines of diff), please break them down into 37 | smaller commits. Smaller commits are much easier to review and more likely 38 | to get merged in. Please make sure each commit is an isolated change (eg if 39 | the commit does 2 separate things, please split it). 40 | 41 | - **Use a descriptive title.** 42 | 43 | - **Include useful details in the commit messages.** 44 | Providing context helps reviewers understand the change and helps expedite 45 | feedback. Please provide a detailed enough description of (high-level) what 46 | the change does and why it is needed. 47 | 48 | - **Squash commits that address feedback.** 49 | Follow-up changes to the submitted commit should be amended to the commit, 50 | not pushed out as a separate commit. 51 | 52 | - **Run rustfmt before submitting.**. 53 | Running rustfmt (`cargo fmt`) will help fix any styling inconsistencies. 54 | It is checked by CI, but running rustfmt before submitting will help reduce 55 | churn for your pull request. 56 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [ 3 | "libbpf-cargo", 4 | "libbpf-rs", 5 | "examples/runqslower", 6 | "examples/bpf_query", 7 | "examples/capable", 8 | "examples/tc_port_whitelist", 9 | ] 10 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/LICENSE: -------------------------------------------------------------------------------- 1 | LGPL-2.1 OR BSD-2-Clause 2 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/LICENSE.BSD-2-Clause: -------------------------------------------------------------------------------- 1 | Valid-License-Identifier: BSD-2-Clause 2 | SPDX-URL: https://spdx.org/licenses/BSD-2-Clause.html 3 | Usage-Guide: 4 | To use the BSD 2-clause "Simplified" License put the following SPDX 5 | tag/value pair into a comment according to the placement guidelines in 6 | the licensing rules documentation: 7 | SPDX-License-Identifier: BSD-2-Clause 8 | License-Text: 9 | 10 | Copyright (c) . All rights reserved. 11 | 12 | Redistribution and use in source and binary forms, with or without 13 | modification, are permitted provided that the following conditions are met: 14 | 15 | 1. Redistributions of source code must retain the above copyright notice, 16 | this list of conditions and the following disclaimer. 17 | 18 | 2. Redistributions in binary form must reproduce the above copyright 19 | notice, this list of conditions and the following disclaimer in the 20 | documentation and/or other materials provided with the distribution. 21 | 22 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 23 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 25 | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 26 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 27 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 28 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 29 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 30 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 31 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 32 | POSSIBILITY OF SUCH DAMAGE. 33 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/README.md: -------------------------------------------------------------------------------- 1 | ![CI](https://github.com/libbpf/libbpf-rs/workflows/Rust/badge.svg?branch=master) 2 | [![rustc](https://img.shields.io/badge/rustc-1.59+-blue.svg)](https://blog.rust-lang.org/2022/02/24/Rust-1.59.0.html) 3 | 4 | WARNING: The API is not stable and is subject to breakage. Any breakage will 5 | include a minor version bump pre-1.0 and a major version bump post-1.0. 6 | [Semantic versioning](https://semver.org/) will be followed post-1.0 release. 7 | 8 | # libbpf-rs 9 | 10 | [![crates.io badge](https://img.shields.io/crates/v/libbpf-rs.svg)](https://crates.io/crates/libbpf-rs) 11 | 12 | Idiomatic rust wrapper around 13 | [libbpf](https://github.com/libbpf/libbpf) 14 | 15 | To use in your project, add into your `Cargo.toml`: 16 | 17 | ```toml 18 | [dependencies] 19 | libbpf-rs = "0.18" 20 | ``` 21 | 22 | See [full documentation here](https://docs.rs/libbpf-rs). 23 | 24 | # libbpf-cargo 25 | 26 | [![crates.io badge](https://img.shields.io/crates/v/libbpf-cargo.svg)](https://crates.io/crates/libbpf-cargo) 27 | 28 | Helps you build and develop eBPF programs with standard rust tooling 29 | 30 | To use in your project, add into your `Cargo.toml`: 31 | 32 | ```toml 33 | [build-dependencies] 34 | libbpf-cargo = "0.12" 35 | ``` 36 | 37 | See [full documentation here](https://docs.rs/libbpf-cargo). 38 | 39 | ## Contributing 40 | 41 | We welcome all contributions! Please see the [contributor's 42 | guide](CONTRIBUTING.md) for more information. 43 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/examples/bpf_query/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bpf_query" 3 | version = "0.1.0" 4 | authors = ["Daniel Xu "] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | libbpf-rs = { path = "../../libbpf-rs" } 9 | nix = { version = "0.24", default-features = false, features = ["net", "user"] } 10 | clap = { version = "3.1", default-features = false, features = ["std", "derive"] } 11 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/examples/bpf_query/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::process::exit; 2 | 3 | use clap::Parser; 4 | use libbpf_rs::query; 5 | use nix::unistd::Uid; 6 | 7 | /// Query the system about BPF-related information 8 | #[derive(Debug, Parser)] 9 | enum Command { 10 | /// Display information about progs 11 | Prog, 12 | /// Display information about maps 13 | Map, 14 | /// Display information about BTF 15 | Btf, 16 | /// Display information about links 17 | Link, 18 | } 19 | 20 | fn prog() { 21 | for prog in query::ProgInfoIter::default() { 22 | println!( 23 | "name={:<16} type={:<15} run_count={:<2} runtime_ns={}", 24 | prog.name, prog.ty, prog.run_cnt, prog.run_time_ns 25 | ); 26 | } 27 | } 28 | 29 | fn map() { 30 | for map in query::MapInfoIter::default() { 31 | println!("name={:<16} type={}", map.name, map.ty); 32 | } 33 | } 34 | 35 | fn btf() { 36 | for btf in query::BtfInfoIter::default() { 37 | println!("id={:4} size={}", btf.id, btf.btf_size); 38 | } 39 | } 40 | 41 | fn link() { 42 | for link in query::LinkInfoIter::default() { 43 | let link_type_str = match link.info { 44 | query::LinkTypeInfo::RawTracepoint(_) => "raw_tracepoint", 45 | query::LinkTypeInfo::Tracing(_) => "tracing", 46 | query::LinkTypeInfo::Cgroup(_) => "cgroup", 47 | query::LinkTypeInfo::Iter => "iter", 48 | query::LinkTypeInfo::NetNs(_) => "netns", 49 | query::LinkTypeInfo::Unknown => "unknown", 50 | }; 51 | 52 | println!( 53 | "id={:4} prog_id={:4} type={}", 54 | link.id, link.prog_id, link_type_str 55 | ); 56 | } 57 | } 58 | 59 | fn main() { 60 | if !Uid::effective().is_root() { 61 | eprintln!("Must run as root"); 62 | exit(1); 63 | } 64 | 65 | let opts = Command::parse(); 66 | 67 | match opts { 68 | Command::Prog => prog(), 69 | Command::Map => map(), 70 | Command::Btf => btf(), 71 | Command::Link => link(), 72 | }; 73 | } 74 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/examples/capable/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "capable" 3 | version = "0.1.0" 4 | authors = ["Devasia Thomas "] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | anyhow = "1.0" 9 | libbpf-rs = { path = "../../libbpf-rs" } 10 | libc = "0.2" 11 | phf = { version = "0.10", features = ["macros"] } 12 | plain = "0.2" 13 | time = { version = "0.3", features = ["formatting", "local-offset", "macros"]} 14 | clap = { version = "3.1", default-features = false, features = ["std", "derive"] } 15 | 16 | [build-dependencies] 17 | libbpf-cargo = { path = "../../libbpf-cargo" } 18 | 19 | [features] 20 | static = ["libbpf-rs/static"] 21 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/examples/capable/build.rs: -------------------------------------------------------------------------------- 1 | use libbpf_cargo::SkeletonBuilder; 2 | use std::{env, path::PathBuf}; 3 | 4 | const SRC: &str = "src/bpf/capable.bpf.c"; 5 | 6 | fn main() { 7 | let mut out = 8 | PathBuf::from(env::var_os("OUT_DIR").expect("OUT_DIR must be set in build script")); 9 | out.push("capable.skel.rs"); 10 | SkeletonBuilder::new() 11 | .source(SRC) 12 | .build_and_generate(&out) 13 | .unwrap(); 14 | println!("cargo:rerun-if-changed={}", SRC); 15 | } 16 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/examples/capable/src/bpf/capable.h: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */ 2 | 3 | #ifndef CAPABLE_CAPABLE_H 4 | #define CAPABLE_CAPABLE_H 5 | 6 | #define TASK_COMM_LEN 16 7 | #define BPF_MAX_STACK_DEPTH 127 8 | 9 | struct event { 10 | gid_t tgid; 11 | pid_t pid; 12 | uid_t uid; 13 | int cap; 14 | int audit; 15 | int insetid; 16 | u8 comm[TASK_COMM_LEN]; 17 | int kernel_stack_id; 18 | int user_stack_id; 19 | }; 20 | 21 | enum uniqueness { 22 | UNQ_OFF, UNQ_PID, UNQ_CGROUP 23 | }; 24 | 25 | #endif //CAPABLE_CAPABLE_H 26 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/examples/capable/src/bpf/vmlinux.h: -------------------------------------------------------------------------------- 1 | ../../../vmlinux_515.h -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/examples/runqslower/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "runqslower" 3 | version = "0.1.0" 4 | authors = ["Daniel Xu "] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | anyhow = "1.0" 9 | libbpf-rs = { path = "../../libbpf-rs" } 10 | libc = "0.2" 11 | plain = "0.2" 12 | time = { version = "0.3", features = ["formatting", "local-offset", "macros"]} 13 | clap = { version = "3.1", default-features = false, features = ["std", "derive"] } 14 | 15 | [build-dependencies] 16 | libbpf-cargo = { path = "../../libbpf-cargo" } 17 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/examples/runqslower/README.md: -------------------------------------------------------------------------------- 1 | # runqslower-rs 2 | 3 | `runqslower-rs` provides a canonical example on how to use `libbpf-cargo` and `libbpf-rs` 4 | effectively. 5 | 6 | --- 7 | 8 | To build the project: 9 | ```shell 10 | $ cd examples/runqslower 11 | $ cargo build 12 | $ sudo ../../target/debug/runqslower 1000 13 | Tracing run queue latency higher than 1000 us 14 | TIME COMM TID LAT(us) 15 | 13:40:58 WebExtensions 961211 1287 16 | 13:40:58 WebExtensions 961211 1516 17 | 13:40:58 Timer 961076 2255 18 | 13:40:58 AudioIPC0 1111261 2375 19 | 13:40:58 Gecko_IOThread 961074 2252 20 | 13:40:58 WebExtensions 961211 1030 21 | ^C 22 | ``` 23 | 24 | --- 25 | 26 | To generate an updated `vmlinux.h`: 27 | ```shell 28 | $ bpftool btf dump file /sys/kernel/btf/vmlinux format c > ./vmlinux.h 29 | ``` 30 | 31 | BTF might also be found at `/boot/vmlinux-$(uname -r)`, depending on which 32 | linux distribution you run. 33 | 34 | You can see if your kernel is compiled with BTF by running: 35 | ```shell 36 | $ zgrep CONFIG_DEBUG_INFO_BTF /proc/config.gz 37 | ``` 38 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/examples/runqslower/build.rs: -------------------------------------------------------------------------------- 1 | use libbpf_cargo::SkeletonBuilder; 2 | use std::{env, path::PathBuf}; 3 | 4 | const SRC: &str = "src/bpf/runqslower.bpf.c"; 5 | 6 | fn main() { 7 | let mut out = 8 | PathBuf::from(env::var_os("OUT_DIR").expect("OUT_DIR must be set in build script")); 9 | out.push("runqslower.skel.rs"); 10 | SkeletonBuilder::new() 11 | .source(SRC) 12 | .build_and_generate(&out) 13 | .unwrap(); 14 | println!("cargo:rerun-if-changed={}", SRC); 15 | } 16 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/examples/runqslower/src/bpf/runqslower.h: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */ 2 | #ifndef __RUNQSLOWER_H 3 | #define __RUNQSLOWER_H 4 | 5 | #define TASK_COMM_LEN 16 6 | 7 | struct event { 8 | u8 task[TASK_COMM_LEN]; 9 | __u64 delta_us; 10 | pid_t pid; 11 | }; 12 | 13 | #endif /* __RUNQSLOWER_H */ 14 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/examples/runqslower/src/bpf/vmlinux.h: -------------------------------------------------------------------------------- 1 | ../../../vmlinux_515.h -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/examples/tc_port_whitelist/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tc_whitelist_ports" 3 | version = "0.1.0" 4 | authors = ["Michael Mullin "] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | anyhow = "1.0" 9 | libbpf-rs = { path = "../../libbpf-rs" } 10 | libc = "0.2" 11 | plain = "0.2" 12 | nix = { version = "0.24", default-features = false, features = ["net", "user"] } 13 | clap = { version = "3.1", default-features = false, features = ["std", "derive"] } 14 | 15 | [build-dependencies] 16 | libbpf-cargo = { path = "../../libbpf-cargo" } 17 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/examples/tc_port_whitelist/build.rs: -------------------------------------------------------------------------------- 1 | use libbpf_cargo::SkeletonBuilder; 2 | use std::{env, path::PathBuf}; 3 | 4 | const SRC: &str = "src/bpf/tc.bpf.c"; 5 | 6 | fn main() { 7 | let mut out = 8 | PathBuf::from(env::var_os("OUT_DIR").expect("OUT_DIR must be set in build script")); 9 | out.push("tc.skel.rs"); 10 | SkeletonBuilder::new() 11 | .source(SRC) 12 | .build_and_generate(&out) 13 | .unwrap(); 14 | println!("cargo:rerun-if-changed={}", SRC); 15 | } 16 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/examples/tc_port_whitelist/src/bpf/vmlinux.h: -------------------------------------------------------------------------------- 1 | ../../../vmlinux_515.h -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-cargo/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "libbpf-cargo" 3 | description = "Cargo plugin to build bpf programs" 4 | repository = "https://github.com/libbpf/libbpf-rs" 5 | homepage = "https://github.com/libbpf/libbpf-rs" 6 | documentation = "https://docs.rs/crate/libbpf-cargo" 7 | readme = "../README.md" 8 | version = "0.13.1" 9 | authors = ["Daniel Xu "] 10 | edition = "2021" 11 | license = "LGPL-2.1 OR BSD-2-Clause" 12 | keywords = ["bpf", "ebpf", "libbpf"] 13 | 14 | [badges] 15 | maintenance = { status = "actively-developed" } 16 | 17 | # Crate is named libbpf-cargo to be consistent with libbpf-rs. 18 | # Binary must be named cargo-${SUBCOMMAND} to interop with cargo. 19 | [[bin]] 20 | name = "cargo-libbpf" 21 | path = "src/main.rs" 22 | 23 | [lib] 24 | path = "src/lib.rs" 25 | 26 | [features] 27 | # When turned on, link against system-installed libbpf instead of building 28 | # and linking against vendored libbpf sources 29 | novendor = ["libbpf-sys/novendor"] 30 | 31 | [dependencies] 32 | anyhow = "1.0" 33 | cargo_metadata = "0.14" 34 | libbpf-sys = { version = "1.0.3" } 35 | memmap2 = "0.5" 36 | num_enum = "0.5" 37 | regex = "1.6.0" 38 | scroll = "0.11" 39 | scroll_derive = "0.11" 40 | semver = "1.0" 41 | serde = { version = "1.0", features = ["derive"] } 42 | serde_json = "1.0" 43 | tempfile = "3.3" 44 | thiserror = "1.0" 45 | clap = { version = "3.1", default-features = false, features = ["std", "derive"] } 46 | 47 | [dev-dependencies] 48 | goblin = "0.4" 49 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-cargo/LICENSE: -------------------------------------------------------------------------------- 1 | ../LICENSE -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-cargo/LICENSE.BSD-2-Clause: -------------------------------------------------------------------------------- 1 | ../LICENSE.BSD-2-Clause -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-cargo/LICENSE.LPGL-2.1: -------------------------------------------------------------------------------- 1 | ../LICENSE.LPGL-2.1 -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-cargo/README.md: -------------------------------------------------------------------------------- 1 | ../README.md -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-cargo/src/btf/c_types.rs: -------------------------------------------------------------------------------- 1 | use scroll_derive::{IOread, Pread as DerivePread, Pwrite, SizeWith}; 2 | 3 | pub const BTF_MAGIC: u16 = 0xEB9F; 4 | pub const BTF_VERSION: u8 = 1; 5 | 6 | /// All offsets are in bytes relative to the end of this header 7 | #[repr(C)] 8 | #[derive(Debug, Clone, DerivePread, Pwrite, IOread, SizeWith)] 9 | pub struct btf_header { 10 | pub magic: u16, 11 | pub version: u8, 12 | pub flags: u8, 13 | pub hdr_len: u32, 14 | pub type_off: u32, 15 | pub type_len: u32, 16 | pub str_off: u32, 17 | pub str_len: u32, 18 | } 19 | 20 | #[repr(C)] 21 | #[derive(Debug, Clone, DerivePread, Pwrite, IOread, SizeWith)] 22 | pub struct btf_type { 23 | pub name_off: u32, 24 | pub info: u32, 25 | pub type_id: u32, 26 | } 27 | 28 | #[repr(C)] 29 | #[derive(Debug, Clone, DerivePread, Pwrite, IOread, SizeWith)] 30 | pub struct btf_enum { 31 | pub name_off: u32, 32 | pub val: i32, 33 | } 34 | 35 | #[repr(C)] 36 | #[derive(Debug, Clone, DerivePread, Pwrite, IOread, SizeWith)] 37 | pub struct btf_array { 38 | pub val_type_id: u32, 39 | pub idx_type_id: u32, 40 | pub nelems: u32, 41 | } 42 | 43 | #[repr(C)] 44 | #[derive(Debug, Clone, DerivePread, Pwrite, IOread, SizeWith)] 45 | pub struct btf_member { 46 | pub name_off: u32, 47 | pub type_id: u32, 48 | pub offset: u32, 49 | } 50 | 51 | #[repr(C)] 52 | #[derive(Debug, Clone, DerivePread, Pwrite, IOread, SizeWith)] 53 | pub struct btf_param { 54 | pub name_off: u32, 55 | pub type_id: u32, 56 | } 57 | 58 | #[repr(C)] 59 | #[derive(Debug, Clone, DerivePread, Pwrite, IOread, SizeWith)] 60 | pub struct btf_datasec_var { 61 | pub type_id: u32, 62 | pub offset: u32, 63 | pub size: u32, 64 | } 65 | 66 | #[repr(C)] 67 | #[derive(Debug, Clone, DerivePread, Pwrite, IOread, SizeWith)] 68 | pub struct btf_decl_tag { 69 | pub component_idx: i32, 70 | } 71 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-cargo/src/btf/mod.rs: -------------------------------------------------------------------------------- 1 | #[allow(clippy::module_inception)] 2 | pub mod btf; 3 | pub mod c_types; 4 | pub mod types; 5 | 6 | pub use btf::*; 7 | pub use types::*; 8 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-cargo/src/make.rs: -------------------------------------------------------------------------------- 1 | use std::path::PathBuf; 2 | use std::process::Command; 3 | 4 | use anyhow::{bail, Context, Result}; 5 | 6 | use crate::{build, gen}; 7 | 8 | pub fn make( 9 | debug: bool, 10 | manifest_path: Option<&PathBuf>, 11 | clang: Option<&PathBuf>, 12 | skip_clang_version_checks: bool, 13 | quiet: bool, 14 | cargo_build_args: Vec, 15 | rustfmt_path: Option<&PathBuf>, 16 | ) -> Result<()> { 17 | if !quiet { 18 | println!("Compiling BPF objects"); 19 | } 20 | build::build(debug, manifest_path, clang, skip_clang_version_checks) 21 | .context("Failed to compile BPF objects")?; 22 | 23 | if !quiet { 24 | println!("Generating skeletons"); 25 | } 26 | gen::gen(debug, manifest_path, None, rustfmt_path).context("Failed to generate skeletons")?; 27 | 28 | let mut cmd = Command::new("cargo"); 29 | cmd.arg("build"); 30 | if quiet { 31 | cmd.arg("--quiet"); 32 | } 33 | for arg in cargo_build_args { 34 | cmd.arg(arg); 35 | } 36 | 37 | let status = cmd.status().context("Failed to spawn child")?; 38 | if !status.success() { 39 | let reason = match status.code() { 40 | Some(rc) => format!("exit code {}", rc), 41 | None => "killed by signal".to_string(), 42 | }; 43 | 44 | bail!("Failed to `cargo build`: {}", reason); 45 | } 46 | 47 | Ok(()) 48 | } 49 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-rs/.cargo/config: -------------------------------------------------------------------------------- 1 | [target.x86_64-unknown-linux-gnu] 2 | runner = "sudo -E" 3 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-rs/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "libbpf-rs" 3 | description = "libbpf-rs is a safe, idiomatic, and opinionated wrapper around libbpf-sys" 4 | repository = "https://github.com/libbpf/libbpf-rs" 5 | homepage = "https://github.com/libbpf/libbpf-rs" 6 | readme = "../README.md" 7 | version = "0.19.1" 8 | authors = ["Daniel Xu "] 9 | edition = "2021" 10 | license = "LGPL-2.1 OR BSD-2-Clause" 11 | keywords = ["bpf", "ebpf", "libbpf"] 12 | 13 | [badges] 14 | maintenance = { status = "actively-developed" } 15 | 16 | [features] 17 | # When turned on, link against system-installed libbpf instead of building 18 | # and linking against vendored libbpf sources 19 | novendor = ["libbpf-sys/novendor"] 20 | static = ["libbpf-sys/static"] 21 | 22 | [dependencies] 23 | bitflags = "1.3" 24 | lazy_static = "1.4" 25 | libbpf-sys = { version = "1.0.3" } 26 | nix = { version = "0.24", default-features = false, features = ["net", "user"] } 27 | num_enum = "0.5" 28 | strum_macros = "0.23" 29 | thiserror = "1.0" 30 | vsprintf = "2.0" 31 | 32 | [dev-dependencies] 33 | libc = "0.2" 34 | log = "0.4" 35 | plain = "0.2.3" 36 | probe = "0.3" 37 | scopeguard = "1.1" 38 | serial_test = "0.5" 39 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-rs/LICENSE: -------------------------------------------------------------------------------- 1 | ../LICENSE -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-rs/LICENSE.BSD-2-Clause: -------------------------------------------------------------------------------- 1 | ../LICENSE.BSD-2-Clause -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-rs/LICENSE.LPGL-2.1: -------------------------------------------------------------------------------- 1 | ../LICENSE.LPGL-2.1 -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-rs/README.md: -------------------------------------------------------------------------------- 1 | ../README.md -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-rs/src/error.rs: -------------------------------------------------------------------------------- 1 | use std::result; 2 | 3 | use thiserror::Error; 4 | 5 | /// Canonical error type for this crate. 6 | #[derive(Error, Debug)] 7 | pub enum Error { 8 | #[error("System error, errno: {0}")] 9 | System(i32), 10 | #[error("Input input: {0}")] 11 | InvalidInput(String), 12 | #[error("Internal error: {0}")] 13 | Internal(String), 14 | } 15 | 16 | pub type Result = result::Result; 17 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-rs/src/iter.rs: -------------------------------------------------------------------------------- 1 | use nix::{errno, libc, unistd}; 2 | use std::io; 3 | 4 | use crate::*; 5 | 6 | /// Represents a bpf iterator for reading kernel data structures. This requires 7 | /// Linux 5.8. 8 | /// 9 | /// This implements [`std::io::Read`] for reading bytes from the iterator. 10 | /// Methods require working with raw bytes. You may find libraries such as 11 | /// [`plain`](https://crates.io/crates/plain) helpful. 12 | #[derive(Debug)] 13 | pub struct Iter { 14 | fd: i32, 15 | } 16 | 17 | impl Iter { 18 | pub fn new(link: &Link) -> Result { 19 | let link_fd = link.fd(); 20 | let fd = unsafe { libbpf_sys::bpf_iter_create(link_fd) }; 21 | if fd < 0 { 22 | return Err(Error::System(errno::errno())); 23 | } 24 | Ok(Self { fd }) 25 | } 26 | } 27 | 28 | impl io::Read for Iter { 29 | fn read(&mut self, buf: &mut [u8]) -> std::result::Result { 30 | let bytes_read = unsafe { libc::read(self.fd, buf.as_mut_ptr() as *mut _, buf.len()) }; 31 | if bytes_read < 0 { 32 | return Err(std::io::Error::last_os_error()); 33 | } 34 | Ok(bytes_read as usize) 35 | } 36 | } 37 | 38 | impl Drop for Iter { 39 | fn drop(&mut self) { 40 | let _ = unistd::close(self.fd); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-rs/tests/README.md: -------------------------------------------------------------------------------- 1 | # libbpf-rs tests 2 | 3 | libbpf-rs tests are designed to be independent of libbpf-cargo and underlying 4 | compiler versions. To that end, we check in pre-compiled bpf object files in 5 | `libbpf-rs/tests/bin`. To help with writing new tests, the original source 6 | code for the pre-compiled objects are placed in `libbpf-rs/tests/bin/src`. 7 | 8 | To regenerate the test bpf object files 9 | run bpf_object_regen.sh script via the command: 10 | $ ./bpf_object_regen.sh 11 | 12 | The script bpf_object_regen.sh depends on the following packages installed: 13 | 14 | bash 15 | bpftool (optional) 16 | clang 17 | libbpf 18 | 19 | Installation Instructions for common distributions 20 | 21 | Ubuntu 21.10+: (should work with 20.10+ (untested), 20.04 will not work!!) 22 | required: 23 | $ apt install bash clang libbpf-dev 24 | optional: 25 | $ apt install linux-tools-generic 26 | Note: bin/src/runqslower.bpf.c requires a vmlinux.h generated from kernel 5.14+ 27 | 28 | Debian 11+: 29 | required: 30 | $ apt install bash clang libbpf-dev 31 | optional: 32 | $ apt install bpftool 33 | Note: bin/src/runqslower.bpf.c requires a vmlinux.h generated from kernel 5.14+ 34 | Note: requires running with 35 | $ PATH=$PATH:/usr/sbin/ ./bpf_object_regen.sh -b ... 36 | 37 | Arch Linux: (tested as of 2021/12/16) 38 | required: 39 | $ pacman -S bash clang libbpf 40 | optional: 41 | $ pacman -S bpf 42 | 43 | Fedora 35+, Centos Stream 9: (should work with Fedora 34 (untested), RHEL 9 (untested)) 44 | required: 45 | $ dnf install bash clang libbpf-devel 46 | optional: 47 | $ dnf install bpftool 48 | 49 | Alma Linux 8.5+: (should work with Centos-Stream-8 (untested) and derivatives eg RHEL 8.5 (untested)) 50 | required: 51 | $ dnf install epel-release 52 | $ dnf --enablerepo=powertools install bash clang libbpf-devel 53 | optional: 54 | $ dnf install bpftool 55 | Note: bin/src/runqslower.bpf.c requires a vmlinux.h generated from kernel 5.14+ 56 | 57 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-rs/tests/bin/src/percpu_map.bpf.c: -------------------------------------------------------------------------------- 1 | #include "vmlinux.h" 2 | 3 | #include 4 | #include 5 | 6 | struct { 7 | __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY); 8 | __uint(key_size, sizeof(u32)); 9 | __uint(value_size, sizeof(u32)); 10 | __uint(max_entries, 1); 11 | } percpu_map SEC(".maps"); 12 | 13 | char _license[] SEC("license") = "GPL"; 14 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-rs/tests/bin/src/ringbuf.bpf.c: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-2.0 2 | // Copyright (c) 2021 William Findlay 3 | #include "vmlinux.h" 4 | #include 5 | 6 | struct { 7 | __uint(type, BPF_MAP_TYPE_RINGBUF); 8 | __uint(max_entries, 4096 /* one page */); 9 | } ringbuf1 SEC(".maps"); 10 | 11 | struct { 12 | __uint(type, BPF_MAP_TYPE_RINGBUF); 13 | __uint(max_entries, 4096 /* one page */); 14 | } ringbuf2 SEC(".maps"); 15 | 16 | SEC("tp/syscalls/sys_enter_getpid") 17 | int handle__sys_enter_getpid(void *ctx) 18 | { 19 | int *value; 20 | 21 | value = bpf_ringbuf_reserve(&ringbuf1, sizeof(int), 0); 22 | if (value) { 23 | *value = 1; 24 | bpf_ringbuf_submit(value, 0); 25 | } 26 | 27 | value = bpf_ringbuf_reserve(&ringbuf2, sizeof(int), 0); 28 | if (value) { 29 | *value = 2; 30 | bpf_ringbuf_submit(value, 0); 31 | } 32 | 33 | return 0; 34 | } 35 | 36 | char LICENSE[] SEC("license") = "GPL"; 37 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-rs/tests/bin/src/runqslower.h: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */ 2 | #ifndef __RUNQSLOWER_H 3 | #define __RUNQSLOWER_H 4 | 5 | #define TASK_COMM_LEN 16 6 | 7 | struct event { 8 | u8 task[TASK_COMM_LEN]; 9 | __u64 delta_us; 10 | pid_t pid; 11 | }; 12 | 13 | #endif /* __RUNQSLOWER_H */ 14 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-rs/tests/bin/src/taskiter.bpf.c: -------------------------------------------------------------------------------- 1 | #include "vmlinux.h" 2 | 3 | #include 4 | #include 5 | 6 | struct index_pid_pair { 7 | uint32_t i; 8 | pid_t pid; 9 | }; 10 | 11 | static uint32_t i = 0; 12 | 13 | SEC("iter/task") 14 | int dump_pid(struct bpf_iter__task *ctx) 15 | { 16 | struct seq_file *seq = ctx->meta->seq; 17 | struct task_struct *task = ctx->task; 18 | struct index_pid_pair p; 19 | 20 | if (!task) 21 | return 0; 22 | 23 | p.i = i++; 24 | p.pid = task->tgid; 25 | 26 | bpf_seq_write(seq, &p, sizeof(p)); 27 | return 0; 28 | } 29 | 30 | char _license[] SEC("license") = "GPL"; 31 | 32 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-rs/tests/bin/src/tc-unit.bpf.c: -------------------------------------------------------------------------------- 1 | #include "vmlinux.h" 2 | #include 3 | 4 | //#include 5 | #define TC_ACT_UNSPEC (-1) 6 | 7 | SEC("tc") 8 | int handle_tc(struct __sk_buff *skb) 9 | { 10 | return TC_ACT_UNSPEC; 11 | } 12 | 13 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-rs/tests/bin/src/usdt.bpf.c: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-2.0 2 | // Copyright (c) 2021 William Findlay 3 | #include "vmlinux.h" 4 | #include 5 | #include 6 | 7 | struct { 8 | __uint(type, BPF_MAP_TYPE_RINGBUF); 9 | __uint(max_entries, 4096 /* one page */); 10 | } ringbuf SEC(".maps"); 11 | 12 | SEC("usdt") 13 | int handle__usdt(void *ctx) 14 | { 15 | int *value; 16 | 17 | value = bpf_ringbuf_reserve(&ringbuf, sizeof(int), 0); 18 | if (value) { 19 | *value = 1; 20 | bpf_ringbuf_submit(value, 0); 21 | } 22 | 23 | return 0; 24 | } 25 | 26 | char LICENSE[] SEC("license") = "GPL"; 27 | -------------------------------------------------------------------------------- /ebpf-pod-resize-libbpf-rs-CO-RE/libbpf-rs/libbpf-rs/tests/bpf_object_regen.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | SRC=$(find bin/src/ -name "*.bpf.c") 4 | BPFTOOL="" 5 | 6 | function usage() { 7 | echo "Usage: ./bpf_object_regen.sh [OPTIONS]" 8 | echo " -b: use bpftool to generate bin/src/vmlinux.h" 9 | echo " default vmlinux.h from ../../examples/vmlinux_515.h" 10 | echo " -o [SCRIPT_NAME]: only compile one object defined by SCRIPT_NAME" 11 | echo "example: ./bpf_object_regen.sh -b -o bin/src/runqslower.bpf.c" 12 | exit 13 | } 14 | 15 | while [[ ! -z $1 ]]; do 16 | case "$1" in 17 | -b|--bpftool) 18 | BPFTOOL=$(which bpftool) 19 | if [[ -z $BPFTOOL ]]; then 20 | echo "No available bpftool: Please consult README.md or your distro's documentation" 21 | usage 22 | fi 23 | ;; 24 | -o|--only) 25 | SRC=$2 26 | if [[ -z $SRC ]]; then 27 | echo -e "No source files provided" 28 | usage 29 | fi 30 | shift 31 | ;; 32 | -h|--help) 33 | echo "bpf_object_regen.sh: Regenerate libbpf-rs/test bpf objects" 34 | usage 35 | ;; 36 | esac 37 | shift 38 | done 39 | 40 | function compile() { 41 | base=$(basename -- $file) 42 | objname="${base%.*}" 43 | objname+=".o" 44 | clang -g -O2 -target bpf -c $1 -o bin/$objname 45 | } 46 | 47 | if [[ ! -z $BPFTOOL ]]; then 48 | bpftool btf dump file /sys/kernel/btf/vmlinux format c > bin/src/vmlinux.h 49 | else 50 | cp ../../examples/vmlinux_515.h bin/src/vmlinux.h 51 | fi 52 | 53 | for file in $SRC 54 | do 55 | compile $file 56 | done 57 | 58 | rm bin/src/vmlinux.h 59 | -------------------------------------------------------------------------------- /ebpf-pod-resize/README.md: -------------------------------------------------------------------------------- 1 | # ebpf-pod-resize 2 | 3 | This code is meant to illustrate how eBPF can help proactively initiate in-place resize of pod resources 4 | for use cases such as the Remote Development Environment. The defining characteristic of such an use case 5 | is the spikes in resource needs. 6 | 7 | A reactive approach such as VPA is not the best option for such use case. eBPF can help resize the pod 8 | with significantly lower latency based on user specified conditions. 9 | 10 | NOTE: This code is for illustration purposes only and not meant for any production use. It was written 11 | to illustrate and demonstrate an idea. 12 | -------------------------------------------------------------------------------- /ebpf-pod-resize/bootstrap-ebpf-demo.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -x 2 | 3 | # Supported only for Ubuntu 20.04 LTS (may work with 22.04) 4 | 5 | cd $HOME 6 | mkdir -p $HOME/tmp 7 | cd $HOME/tmp 8 | 9 | # Install required packages 10 | apt-get update -y 11 | apt-get upgrade -y 12 | apt-get install -y build-essential jq curl wget vim 13 | 14 | # Install go 1.19.2 15 | if [[ "$(uname -m)" == "aarch64" ]]; then 16 | wget https://go.dev/dl/go1.19.2.linux-arm64.tar.gz 17 | tar -xf go1.19.2.linux-arm64.tar.gz 18 | mv go /usr/local/ 19 | else 20 | wget https://go.dev/dl/go1.19.2.linux-amd64.tar.gz 21 | tar -xf go1.19.2.linux-amd64.tar.gz 22 | mv go /usr/local/ 23 | fi 24 | 25 | # Install and configure containerd, crictl, kubectl 26 | curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add - 27 | echo "deb https://apt.kubernetes.io/ kubernetes-xenial main" | sudo tee /etc/apt/sources.list.d/kubernetes.list 28 | apt-get update -y && apt-get install -y containerd cri-tools kubectl kubernetes-cni 29 | cat > /etc/crictl.yaml << EOF 30 | runtime-endpoint: unix:///var/run/containerd/containerd.sock 31 | image-endpoint: unix:///var/run/containerd/containerd.sock 32 | timeout: 2 33 | debug: false 34 | pull-image-on-create: false 35 | EOF 36 | 37 | # Clone in-place resize k8s repo 38 | mkdir -p ~/go/src/k8s.io 39 | pushd ~/go/src/k8s.io 40 | git clone https://github.com/vinaykul/kubernetes k8s-pod-resize 41 | pushd ~/go/src/k8s.io/k8s-pod-resize 42 | git checkout restart-free-pod-vertical-scaling 43 | ./hack/install-etcd.sh 44 | 45 | # Clone and build cfssl 46 | export GOPATH=$HOME/go 47 | export GOROOT=/usr/local/go 48 | export PATH=$GOPATH/bin:$GOROOT/bin:$PATH 49 | mkdir -p ~/go/src/github.com/cloudflare 50 | pushd ~/go/src/github.com/cloudflare 51 | git clone https://github.com/cloudflare/cfssl 52 | cd cfssl 53 | make all 54 | cp bin/cfssl /usr/sbin/ 55 | cp bin/cfssljson /usr/sbin/ 56 | 57 | # Install bpftool 58 | apt-get update -y 59 | apt-get install -y linux-tools-common linux-tools-$(uname -r) 60 | 61 | set +x 62 | echo "Please add go root and go path to your .profile" 63 | echo " export GOPATH=$HOME/go" 64 | echo " export GOROOT=/usr/local/go" 65 | echo " export PATH=$GOPATH/bin:$GOROOT/bin:$PATH" 66 | -------------------------------------------------------------------------------- /ebpf-pod-resize/build-ebpf-pod-resize-docker-img-amd64.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -x 2 | 3 | docker rmi -f skiibum/ebpf-pod-resize-amd64:demo 4 | docker image build -t skiibum/ebpf-pod-resize-amd64:demo -f ebpf-pod-resize-demo.Dockerfile . 5 | -------------------------------------------------------------------------------- /ebpf-pod-resize/build-ebpf-pod-resize-docker-img.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -x 2 | 3 | docker rmi -f skiibum/ebpf-pod-resize:demo 4 | docker image build -t skiibum/ebpf-pod-resize:demo -f ebpf-pod-resize-demo.Dockerfile . 5 | -------------------------------------------------------------------------------- /ebpf-pod-resize/crictl.yaml: -------------------------------------------------------------------------------- 1 | runtime-endpoint: unix:///containerd/containerd.sock 2 | image-endpoint: unix:///containerd/containerd.sock 3 | timeout: 2 4 | debug: false 5 | pull-image-on-create: false 6 | -------------------------------------------------------------------------------- /ebpf-pod-resize/ebpf-pod-resize-demo.Dockerfile: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: MIT 2 | # Copyright (c) 2022 The Authors. 3 | 4 | # Authors: Vinay Kulkarni <@vinaykul> 5 | 6 | # Permission is hereby granted, free of charge, to any person obtaining a copy 7 | # of this software and associated documentation files (the "Software"), to deal 8 | # in the Software without restriction, including without limitation the rights 9 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | # copies of the Software, and to permit persons to whom the Software is 11 | # furnished to do so, subject to the following conditions:The above copyright 12 | # notice and this permission notice shall be included in all copies or 13 | # substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", 14 | # WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 15 | # TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 16 | # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE 17 | # FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 18 | # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR 19 | # THE USE OR OTHER DEALINGS IN THE SOFTWARE. 20 | 21 | FROM ubuntu:20.04 22 | RUN apt-get update -y 23 | RUN apt-get install -y sudo vim build-essential bpfcc-tools jq curl apt-transport-https python3 python3-pip 24 | RUN curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add - 25 | RUN echo "deb https://apt.kubernetes.io/ kubernetes-xenial main" | sudo tee /etc/apt/sources.list.d/kubernetes.list 26 | RUN apt-get update -y && apt-get install -y cri-tools 27 | RUN pip3 install --upgrade bcc kubernetes 28 | COPY crictl.yaml /etc/ 29 | COPY init-ebpf-pod-resize.sh podsnoop.py launch-ebpf-pod-resize.sh / 30 | CMD /launch-ebpf-pod-resize.sh 31 | -------------------------------------------------------------------------------- /ebpf-pod-resize/init-ebpf-pod-resize.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -xe 2 | 3 | apt-get update -y 4 | apt-get install -y linux-headers-$(uname -r) 5 | -------------------------------------------------------------------------------- /ebpf-pod-resize/kube-build-pod-amd64.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Pod 3 | metadata: 4 | name: kube-build-pod 5 | annotations: 6 | "ebpf-resize": '{ 7 | "cname": "kube-build-ctr", 8 | "commands": ["make"], 9 | "resize": "{\"requests\":{\"memory\":\"1Gi\"},\"limits\":{\"memory\":\"1Gi\"}}" 10 | }' 11 | spec: 12 | containers: 13 | - name: kube-build-ctr 14 | image: skiibum/kube-build:v1.25 15 | imagePullPolicy: IfNotPresent 16 | command: ["tail", "-f", "/dev/null"] 17 | resources: 18 | limits: 19 | cpu: "2" 20 | memory: "50Mi" 21 | requests: 22 | cpu: "1" 23 | memory: "50Mi" 24 | -------------------------------------------------------------------------------- /ebpf-pod-resize/kube-build-pod.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Pod 3 | metadata: 4 | name: kube-build-pod 5 | annotations: 6 | "ebpf-resize": '{ 7 | "cname": "kube-build-ctr", 8 | "commands": ["make"], 9 | "resize": "{\"requests\":{\"memory\":\"5Gi\"},\"limits\":{\"memory\":\"5Gi\"}}" 10 | }' 11 | spec: 12 | containers: 13 | - name: kube-build-ctr 14 | image: skiibum/kube-build-arm64:v1.25 15 | imagePullPolicy: IfNotPresent 16 | command: ["tail", "-f", "/dev/null"] 17 | resources: 18 | limits: 19 | cpu: "5" 20 | memory: "50Mi" 21 | requests: 22 | cpu: "4" 23 | memory: "50Mi" 24 | -------------------------------------------------------------------------------- /ebpf-pod-resize/launch-ebpf-pod-resize.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -xe 2 | 3 | python3 /podsnoop.py 4 | -------------------------------------------------------------------------------- /tc-vs-xdp-perf/Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # Build tc and xdp eBPF programs 3 | # Needs llvm, clang, bpfcc-tools, linux-headers-$(uname -r), libbpf-dev 4 | # NOTE: This Makefile has been tested only on Ubuntu 22.04 5 | # 6 | 7 | CLANG=clang 8 | CLANG_FLAGS=-g -O2 -Wall -target bpf 9 | CLANG_INCLUDES=/usr/include/$(shell uname -p)-linux-gnu/ 10 | BPFSRC=$(wildcard *.c) 11 | BPFOBJ=$(BPFSRC:.c=_bpf.o) 12 | DEFAULT_NIC=eth0 13 | 14 | .PHONY: bpf 15 | 16 | bpf: $(BPFOBJ) 17 | 18 | %_bpf.o: %.c 19 | $(CLANG) -I $(CLANG_INCLUDES) $(CLANG_FLAGS) -c $^ -o $@ 20 | 21 | clean: 22 | rm -f $(BPFOBJ) 23 | 24 | xdpgeneric: 25 | ip link set dev $(DEFAULT_NIC) xdpgeneric obj xdp_ingress_bpf.o sec xdpingress 26 | 27 | xdpgenericoff: 28 | ip link set dev $(DEFAULT_NIC) xdpgeneric off 29 | 30 | xdpdrv: 31 | ip link set dev $(DEFAULT_NIC) xdpdrv obj xdp_ingress_bpf.o sec xdpingress 32 | 33 | xdpdrvoff: 34 | ip link set dev $(DEFAULT_NIC) xdpdrv off 35 | 36 | xdpshow: 37 | ip link show dev $(DEFAULT_NIC) 38 | 39 | tcbpf: 40 | tc qdisc add dev $(DEFAULT_NIC) clsact || true 41 | tc filter add dev $(DEFAULT_NIC) ingress bpf da obj tc_ingress_bpf.o sec tcingress 42 | 43 | tcbpfoff: 44 | tc filter del dev $(DEFAULT_NIC) ingress 45 | 46 | tcbpfshow: 47 | tc filter show dev $(DEFAULT_NIC) ingress 48 | -------------------------------------------------------------------------------- /tc-vs-xdp-perf/tc_ingress.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #ifndef __section 5 | #define __section(NAME) \ 6 | __attribute__((section(NAME), used)) 7 | #endif 8 | 9 | __section("tcingress") 10 | int tc_ingress_noop(struct __sk_buff *skb) { 11 | return TC_ACT_OK; 12 | } 13 | 14 | char __license[] __section("license") = "GPL"; 15 | -------------------------------------------------------------------------------- /tc-vs-xdp-perf/xdp_ingress.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #ifndef __section 5 | #define __section(NAME) \ 6 | __attribute__((section(NAME), used)) 7 | #endif 8 | 9 | __section("xdpingress") 10 | int xdp_ingress_noop(struct xdp_md *ctx) { 11 | return XDP_PASS; 12 | } 13 | 14 | char __license[] __section("license") = "GPL"; 15 | --------------------------------------------------------------------------------