Просмотр исходного кода

feat(cgroups.plugin): add filtering by cgroups names and improve renaming in k8s (#12778)

Ilya Mashchenko 2 лет назад
Родитель
Сommit
ad476d9f66

+ 154 - 126
collectors/cgroups.plugin/README.md

@@ -7,30 +7,28 @@ custom_edit_url: https://github.com/netdata/netdata/edit/master/collectors/cgrou
 
 You can monitor containers and virtual machines using **cgroups**.
 
-cgroups (or control groups), are a Linux kernel feature that provides accounting and resource usage limiting for processes. When cgroups are bundled with namespaces (i.e. isolation), they form what we usually call **containers**.
+cgroups (or control groups), are a Linux kernel feature that provides accounting and resource usage limiting for
+processes. When cgroups are bundled with namespaces (i.e. isolation), they form what we usually call **containers**.
 
-cgroups are hierarchical, meaning that cgroups can contain child cgroups, which can contain more cgroups, etc. All accounting is reported (and resource usage limits are applied) also in a hierarchical way.
+cgroups are hierarchical, meaning that cgroups can contain child cgroups, which can contain more cgroups, etc. All
+accounting is reported (and resource usage limits are applied) also in a hierarchical way.
 
-To visualize cgroup metrics Netdata provides configuration for cherry picking the cgroups of interest. By default (without any configuration) Netdata should pick **systemd services**, all kinds of **containers** (lxc, docker, etc) and **virtual machines** spawn by managers that register them with cgroups (qemu, libvirt, etc).
+To visualize cgroup metrics Netdata provides configuration for cherry picking the cgroups of interest. By default (
+without any configuration) Netdata should pick **systemd services**, all kinds of **containers** (lxc, docker, etc)
+and **virtual machines** spawn by managers that register them with cgroups (qemu, libvirt, etc).
 
-## configuring Netdata for cgroups
+## Configuring Netdata for cgroups
 
-For each cgroup available in the system, Netdata provides this configuration:
-
-```
-[plugin:cgroups]
-    enable cgroup XXX = yes | no
-```
-
-But it also provides a few patterns to provide a sane default (`yes` or `no`).
-
-Below we see, how this works.
+In general, no additional settings are required. Netdata discovers all available cgroups on the host system and
+collects their metrics.
 
 ### how Netdata finds the available cgroups
 
-Linux exposes resource usage reporting and provides dynamic configuration for cgroups, using virtual files (usually) under `/sys/fs/cgroup`. Netdata reads `/proc/self/mountinfo` to detect the exact mount point of cgroups. Netdata also allows manual configuration of this mount point, using these settings:
+Linux exposes resource usage reporting and provides dynamic configuration for cgroups, using virtual files (usually)
+under `/sys/fs/cgroup`. Netdata reads `/proc/self/mountinfo` to detect the exact mount point of cgroups. Netdata also
+allows manual configuration of this mount point, using these settings:
 
-```
+```text
 [plugin:cgroups]
 	check for new cgroups every = 10
 	path to /sys/fs/cgroup/cpuacct = /sys/fs/cgroup/cpuacct
@@ -43,83 +41,104 @@ Netdata rescans these directories for added or removed cgroups every `check for
 
 ### hierarchical search for cgroups
 
-Since cgroups are hierarchical, for each of the directories shown above, Netdata walks through the subdirectories recursively searching for cgroups (each subdirectory is another cgroup).
+Since cgroups are hierarchical, for each of the directories shown above, Netdata walks through the subdirectories
+recursively searching for cgroups (each subdirectory is another cgroup).
 
-To provide a sane default for this setting, Netdata uses the following pattern list (patterns starting with `!` give a negative match and their order is important: the first matching a path will be used):
+To provide a sane default for this setting, Netdata uses the following pattern list (patterns starting with `!` give a
+negative match and their order is important: the first matching a path will be used):
 
-```
+```text
 [plugin:cgroups]
 	search for cgroups in subpaths matching =  !*/init.scope  !*-qemu  !/init.scope  !/system  !/systemd  !/user  !/user.slice  *
 ```
 
-So, we disable checking for **child cgroups** in systemd internal cgroups ([systemd services are monitored by Netdata](#monitoring-systemd-services)), user cgroups (normally used for desktop and remote user sessions), qemu virtual machines (child cgroups of virtual machines) and `init.scope`. All others are enabled.
+So, we disable checking for **child cgroups** in systemd internal
+cgroups ([systemd services are monitored by Netdata](#monitoring-systemd-services)), user cgroups (normally used for
+desktop and remote user sessions), qemu virtual machines (child cgroups of virtual machines) and `init.scope`. All
+others are enabled.
 
 ### unified cgroups (cgroups v2) support
 
-Basic unified cgroups metrics are supported. To use them instead of v1 cgroups add:
+Netdata automatically detects cgroups version. If detection fails Netdata assumes v1.
+To switch to v2 manually add:
 
-```
+```text
 [plugin:cgroups]
 	use unified cgroups = yes
 	path to unified cgroups = /sys/fs/cgroup
 ```
 
-Unified cgroups use same name pattern matching as v1 cgroups. `cgroup_enable_systemd_services_detailed_memory` is currently unsupported when using unified cgroups.
+Unified cgroups use same name pattern matching as v1 cgroups. `cgroup_enable_systemd_services_detailed_memory` is
+currently unsupported when using unified cgroups.
 
 ### enabled cgroups
 
-To check if the cgroup is enabled, Netdata uses this setting:
+To provide a sane default, Netdata uses the
+following [pattern list](https://learn.netdata.cloud/docs/agent/libnetdata/simple_pattern):
 
-```
-[plugin:cgroups]
-	enable cgroup NAME = yes | no
-```
+- checks the pattern against the path of the cgroup
 
-To provide a sane default, Netdata uses the following pattern list (it checks the pattern against the path of the cgroup):
+  ```text
+  [plugin:cgroups]
+  	enable by default cgroups matching =  !*/init.scope  *.scope  !*/vcpu*  !*/emulator  !*.mount  !*.partition  !*.service  !*.slice  !*.swap  !*.user  !/  !/docker  !/libvirt  !/lxc  !/lxc/*/ns  !/lxc/*/ns/*  !/machine  !/qemu  !/system  !/systemd  !/user  *
+  ```
 
-```
-[plugin:cgroups]
-	enable by default cgroups matching =  !*/init.scope  *.scope  !*/vcpu*  !*/emulator  !*.mount  !*.partition  !*.service  !*.slice  !*.swap  !*.user  !/  !/docker  !/libvirt  !/lxc  !/lxc/*/ns  !/lxc/*/ns/*  !/machine  !/qemu  !/system  !/systemd  !/user  *
-```
-
-The above provides the default `yes` or `no` setting for the cgroup. However, there is an additional step. In many cases the cgroups found in the `/sys/fs/cgroup` hierarchy are just random numbers and in many cases these numbers are ephemeral: they change across reboots or sessions.
+- checks the pattern against the name of the cgroup (as you see it on the dashboard)
 
-So, we need to somehow map the paths of the cgroups to names, to provide consistent Netdata configuration (i.e. there is no point to say `enable cgroup 1234 = yes | no`, if `1234` is a random number that changes over time - we need a name for the cgroup first, so that `enable cgroup NAME = yes | no` will be consistent).
+  ```text
+  [plugin:cgroups]
+  	enable by default cgroups names matching = *
+  ```
 
-For this mapping Netdata provides 2 configuration options:
+Renaming is configured with the following options:
 
-```
+```text
 [plugin:cgroups]
 	run script to rename cgroups matching =  *.scope  *docker*  *lxc*  *qemu*  !/  !*.mount  !*.partition  !*.service  !*.slice  !*.swap  !*.user  *
 	script to get cgroup names = /usr/libexec/netdata/plugins.d/cgroup-name.sh
 ```
 
-The whole point for the additional pattern list, is to limit the number of times the script will be called. Without this pattern list, the script might be called thousands of times, depending on the number of cgroups available in the system.
+The whole point for the additional pattern list, is to limit the number of times the script will be called. Without this
+pattern list, the script might be called thousands of times, depending on the number of cgroups available in the system.
 
-The above pattern list is matched against the path of the cgroup. For matched cgroups, Netdata calls the script [cgroup-name.sh](https://raw.githubusercontent.com/netdata/netdata/master/collectors/cgroups.plugin/cgroup-name.sh.in) to get its name. This script queries `docker`, `kubectl`, `podman`, or applies heuristics to find give a name for the cgroup.
+The above pattern list is matched against the path of the cgroup. For matched cgroups, Netdata calls the
+script [cgroup-name.sh](https://raw.githubusercontent.com/netdata/netdata/master/collectors/cgroups.plugin/cgroup-name.sh)
+to get its name. This script queries `docker`, `kubectl`, `podman`, or applies heuristics to find give a name for the
+cgroup.
 
 #### Note on Podman container names
 
-Podman's security model is a lot more restrictive than Docker's, so Netdata will not be able to detect container names out of the box unless they were started by the same user as Netdata itself.
+Podman's security model is a lot more restrictive than Docker's, so Netdata will not be able to detect container names
+out of the box unless they were started by the same user as Netdata itself.
 
-If Podman is used in "rootful" mode, it's also possible to use `podman system service` to grant Netdata access to container names. To do this, ensure `podman system service` is running and Netdata has access to `/run/podman/podman.sock` (the default permissions as specified by upstream are `0600`, with owner `root`, so you will have to adjust the configuration).
+If Podman is used in "rootful" mode, it's also possible to use `podman system service` to grant Netdata access to
+container names. To do this, ensure `podman system service` is running and Netdata has access
+to `/run/podman/podman.sock` (the default permissions as specified by upstream are `0600`, with owner `root`, so you
+will have to adjust the configuration).
 
-[docker-socket-proxy](https://github.com/Tecnativa/docker-socket-proxy) can also be used to give Netdata restricted access to the socket. Note that `PODMAN_HOST` in Netdata's environment should be set to the proxy's URL in this case.
+[docker-socket-proxy](https://github.com/Tecnativa/docker-socket-proxy) can also be used to give Netdata restricted
+access to the socket. Note that `PODMAN_HOST` in Netdata's environment should be set to the proxy's URL in this case.
 
 ### charts with zero metrics
 
-By default, Netdata will enable monitoring metrics only when they are not zero. If they are constantly zero they are ignored. Metrics that will start having values, after Netdata is started, will be detected and charts will be automatically added to the dashboard (a refresh of the dashboard is needed for them to appear though). Set `yes` for a chart instead of `auto` to enable it permanently. For example:
+By default, Netdata will enable monitoring metrics only when they are not zero. If they are constantly zero they are
+ignored. Metrics that will start having values, after Netdata is started, will be detected and charts will be
+automatically added to the dashboard (a refresh of the dashboard is needed for them to appear though). Set `yes` for a
+chart instead of `auto` to enable it permanently. For example:
 
-```
+```text
 [plugin:cgroups]
 	enable memory (used mem including cache) = yes
 ```
 
-You can also set the `enable zero metrics` option to `yes` in the `[global]` section which enables charts with zero metrics for all internal Netdata plugins.
+You can also set the `enable zero metrics` option to `yes` in the `[global]` section which enables charts with zero
+metrics for all internal Netdata plugins.
 
 ### alarms
 
-CPU and memory limits are watched and used to rise alarms. Memory usage for every cgroup is checked against `ram` and `ram+swap` limits. CPU usage for every cgroup is checked against `cpuset.cpus` and `cpu.cfs_period_us` + `cpu.cfs_quota_us` pair assigned for the cgroup. Configuration for the alarms is available in `health.d/cgroups.conf` file.
+CPU and memory limits are watched and used to rise alarms. Memory usage for every cgroup is checked against `ram`
+and `ram+swap` limits. CPU usage for every cgroup is checked against `cpuset.cpus` and `cpu.cfs_period_us` + `cpu.cfs_quota_us` pair assigned for the cgroup. Configuration for the alarms is available in `health.d/cgroups.conf`
+file.
 
 ## Monitoring systemd services
 
@@ -129,47 +148,48 @@ Netdata monitors **systemd services**. Example:
 
 Support per distribution:
 
-|system|systemd services<br/>charts shown|`tree`<br/>`/sys/fs/cgroup`|comments|
-|:----:|:-------------------------------:|:-------------------------:|:-------|
-|Arch Linux|YES|||
-|Gentoo|NO||can be enabled, see below|
-|Ubuntu 16.04 LTS|YES|||
-|Ubuntu 16.10|YES|[here](http://pastebin.com/PiWbQEXy)||
-|Fedora 25|YES|[here](http://pastebin.com/ax0373wF)||
-|Debian 8|NO||can be enabled, see below|
-|AMI|NO|[here](http://pastebin.com/FrxmptjL)|not a systemd system|
-|CentOS 7.3.1611|NO|[here](http://pastebin.com/SpzgezAg)|can be enabled, see below|
+|      system      | charts shown |        `/sys/fs/cgroup` tree         | comments                  |
+|:----------------:|:------------:|:------------------------------------:|:--------------------------|
+|    Arch Linux    |     YES      |                                      |                           |
+|      Gentoo      |      NO      |                                      | can be enabled, see below |
+| Ubuntu 16.04 LTS |     YES      |                                      |                           |
+|   Ubuntu 16.10   |     YES      | [here](http://pastebin.com/PiWbQEXy) |                           |
+|    Fedora 25     |     YES      | [here](http://pastebin.com/ax0373wF) |                           |
+|     Debian 8     |      NO      |                                      | can be enabled, see below |
+|       AMI        |      NO      | [here](http://pastebin.com/FrxmptjL) | not a systemd system      |
+| CentOS 7.3.1611  |      NO      | [here](http://pastebin.com/SpzgezAg) | can be enabled, see below |
 
 ### Monitored systemd service metrics
 
-- CPU utilization
-- Used memory
-- RSS memory
-- Mapped memory
-- Cache memory
-- Writeback memory
-- Memory minor page faults
-- Memory major page faults
-- Memory charging activity
-- Memory uncharging activity
-- Memory limit failures
-- Swap memory used
-- Disk read bandwidth
-- Disk write bandwidth
-- Disk read operations
-- Disk write operations
-- Throttle disk read bandwidth
-- Throttle disk write bandwidth
-- Throttle disk read operations
-- Throttle disk write operations
-- Queued disk read operations
-- Queued disk write operations
-- Merged disk read operations
-- Merged disk write operations
+- CPU utilization
+- Used memory
+- RSS memory
+- Mapped memory
+- Cache memory
+- Writeback memory
+- Memory minor page faults
+- Memory major page faults
+- Memory charging activity
+- Memory uncharging activity
+- Memory limit failures
+- Swap memory used
+- Disk read bandwidth
+- Disk write bandwidth
+- Disk read operations
+- Disk write operations
+- Throttle disk read bandwidth
+- Throttle disk write bandwidth
+- Throttle disk read operations
+- Throttle disk write operations
+- Queued disk read operations
+- Queued disk write operations
+- Merged disk read operations
+- Merged disk write operations
 
 ### how to enable cgroup accounting on systemd systems that is by default disabled
 
-You can verify there is no accounting enabled, by running `systemd-cgtop`. The program will show only resources for cgroup `/`, but all services will show nothing.
+You can verify there is no accounting enabled, by running `systemd-cgtop`. The program will show only resources for
+cgroup `/`, but all services will show nothing.
 
 To enable cgroup accounting, execute this:
 
@@ -179,7 +199,7 @@ sed -e 's|^#Default\(.*\)Accounting=.*$|Default\1Accounting=yes|g' /etc/systemd/
 
 To see the changes it made, run this:
 
-```
+```sh
 # diff /etc/systemd/system.conf /tmp/system.conf
 40,44c40,44
 < #DefaultCPUAccounting=no
@@ -205,21 +225,25 @@ sudo cp /tmp/system.conf /etc/systemd/system.conf
 sudo systemctl daemon-reexec
 ```
 
-(`systemctl daemon-reload` does not reload the configuration of the server - so you have to execute `systemctl daemon-reexec`).
+(`systemctl daemon-reload` does not reload the configuration of the server - so you have to
+execute `systemctl daemon-reexec`).
 
-Now, when you run `systemd-cgtop`, services will start reporting usage (if it does not, restart a service - any service - to wake it up). Refresh your Netdata dashboard, and you will have the charts too.
+Now, when you run `systemd-cgtop`, services will start reporting usage (if it does not, restart any service to wake it up). Refresh your Netdata dashboard, and you will have the charts too.
 
-In case memory accounting is missing, you will need to enable it at your kernel, by appending the following kernel boot options and rebooting:
+In case memory accounting is missing, you will need to enable it at your kernel, by appending the following kernel boot
+options and rebooting:
 
-```
+```sh
 cgroup_enable=memory swapaccount=1
 ```
 
-You can add the above, directly at the `linux` line in your `/boot/grub/grub.cfg` or appending them to the `GRUB_CMDLINE_LINUX` in `/etc/default/grub` (in which case you will have to run `update-grub` before rebooting). On DigitalOcean debian images you may have to set it at `/etc/default/grub.d/50-cloudimg-settings.cfg`.
+You can add the above, directly at the `linux` line in your `/boot/grub/grub.cfg` or appending them to
+the `GRUB_CMDLINE_LINUX` in `/etc/default/grub` (in which case you will have to run `update-grub` before rebooting). On
+DigitalOcean debian images you may have to set it at `/etc/default/grub.d/50-cloudimg-settings.cfg`.
 
 Which systemd services are monitored by Netdata is determined by the following pattern list:
 
-```
+```text
 [plugin:cgroups]
 	cgroups to match as systemd services =  !/system.slice/*/*.service  /system.slice/*.service
 ```
@@ -228,53 +252,57 @@ Which systemd services are monitored by Netdata is determined by the following p
 
 ## Monitoring ephemeral containers
 
-Netdata monitors containers automatically when it is installed at the host, or when it is installed in a container that has access to the `/proc` and `/sys` filesystems of the host.
+Netdata monitors containers automatically when it is installed at the host, or when it is installed in a container that
+has access to the `/proc` and `/sys` filesystems of the host.
 
 Netdata prior to v1.6 had 2 issues when such containers were monitored:
 
-1.  network interface alarms where triggering when containers were stopped
+1. network interface alarms where triggering when containers were stopped
 
-2.  charts were never cleaned up, so after some time dozens of containers were showing up on the dashboard, and they were occupying memory.
+2. charts were never cleaned up, so after some time dozens of containers were showing up on the dashboard, and they were
+   occupying memory.
 
 ### the current Netdata
 
 network interfaces and cgroups (containers) are now self-cleaned.
 
-So, when a network interface or container stops, Netdata might log a few errors in error.log complaining about files it cannot find, but immediately:
+So, when a network interface or container stops, Netdata might log a few errors in error.log complaining about files it
+cannot find, but immediately:
 
-1.  it will detect this is a removed container or network interface
-2.  it will freeze/pause all alarms for them
-3.  it will mark their charts as obsolete
-4.  obsolete charts are not be offered on new dashboard sessions (so hit F5 and the charts are gone)
-5.  existing dashboard sessions will continue to see them, but of course they will not refresh
-6.  obsolete charts will be removed from memory, 1 hour after the last user viewed them (configurable with `[global].cleanup obsolete charts after seconds = 3600` (at `netdata.conf`).
-7.  when obsolete charts are removed from memory they are also deleted from disk (configurable with `[global].delete obsolete charts files = yes`)
+1. it will detect this is a removed container or network interface
+2. it will freeze/pause all alarms for them
+3. it will mark their charts as obsolete
+4. obsolete charts are not be offered on new dashboard sessions (so hit F5 and the charts are gone)
+5. existing dashboard sessions will continue to see them, but of course they will not refresh
+6. obsolete charts will be removed from memory, 1 hour after the last user viewed them (configurable
+   with `[global].cleanup obsolete charts after seconds = 3600` (at `netdata.conf`).
+7. when obsolete charts are removed from memory they are also deleted from disk (configurable
+   with `[global].delete obsolete charts files = yes`)
 
 ### Monitored container metrics
 
-- CPU usage
-- CPU usage within the limits
-- CPU usage per core
-- Memory usage
-- Writeback memory
-- Memory activity
-- Memory page faults
-- Used memory
-- Used RAM within the limits
-- Memory utilization
-- Memory limit failures
-- I/O bandwidth (all disks)
-- Serviced I/O operations (all disks)
-- Throttle I/O bandwidth (all disks)
-- Throttle serviced I/O operations (all disks)
-- Queued I/O operations (all disks)
-- Merged I/O operations (all disks)
-- CPU pressure
-- Memory pressure
-- Memory full pressure
-- I/O pressure
-- I/O full pressure
-  
-Network interfaces are monitored by means of the [proc plugin](/collectors/proc.plugin/README.md#monitored-network-interface-metrics).
-
-
+- CPU usage
+- CPU usage within the limits
+- CPU usage per core
+- Memory usage
+- Writeback memory
+- Memory activity
+- Memory page faults
+- Used memory
+- Used RAM within the limits
+- Memory utilization
+- Memory limit failures
+- I/O bandwidth (all disks)
+- Serviced I/O operations (all disks)
+- Throttle I/O bandwidth (all disks)
+- Throttle serviced I/O operations (all disks)
+- Queued I/O operations (all disks)
+- Merged I/O operations (all disks)
+- CPU pressure
+- Memory pressure
+- Memory full pressure
+- I/O pressure
+- I/O full pressure
+
+Network interfaces are monitored by means of
+the [proc plugin](/collectors/proc.plugin/README.md#monitored-network-interface-metrics).

+ 133 - 77
collectors/cgroups.plugin/cgroup-name.sh

@@ -114,6 +114,31 @@ function add_lbl_prefix() {
   echo "${new_labels:0:-1}" # trim last ','
 }
 
+function k8s_is_pause_container() {
+  local cgroup_path="${1}"
+
+  local file
+  if [ -d "${NETDATA_HOST_PREFIX}/sys/fs/cgroup/cpuacct" ]; then
+    file="${NETDATA_HOST_PREFIX}/sys/fs/cgroup/cpuacct/$cgroup_path/cgroup.procs"
+  else
+    file="${NETDATA_HOST_PREFIX}/sys/fs/cgroup/$cgroup_path/cgroup.procs"
+  fi
+
+  [ ! -f "$file" ] && return 1
+
+  local procs
+  IFS= read -rd' ' procs 2>/dev/null <"$file"
+  #shellcheck disable=SC2206
+  procs=($procs)
+
+  [ "${#procs[@]}" -ne 1 ] && return 1
+
+  IFS= read -r comm 2>/dev/null <"/proc/${procs[0]}/comm"
+
+  [ "$comm" == "pause" ]
+  return
+}
+
 # k8s_get_kubepod_name resolves */kubepods/* cgroup name.
 # pod level cgroup name format: 'pod_<namespace>_<pod_name>'
 # container level cgroup name format: 'cntr_<namespace>_<pod_name>_<container_name>'
@@ -151,7 +176,8 @@ function k8s_get_kubepod_name() {
   # - replaces '.' with '-'
 
   local fn="${FUNCNAME[0]}"
-  local id="${1}"
+  local cgroup_path="${1}"
+  local id="${2}"
 
   if [[ ! $id =~ ^kubepods ]]; then
     warning "${fn}: '${id}' is not kubepod cgroup."
@@ -195,82 +221,95 @@ function k8s_get_kubepod_name() {
   [ -n "$pod_uid" ] && info "${fn}: cgroup '$id' is a pod(uid:$pod_uid)"
   [ -n "$cntr_id" ] && info "${fn}: cgroup '$id' is a container(id:$cntr_id)"
 
+  if [ -n "$cntr_id" ] && k8s_is_pause_container "$cgroup_path"; then
+    return 1
+  fi
+
   if ! command -v jq > /dev/null 2>&1; then
     warning "${fn}: 'jq' command not available."
     return 1
   fi
 
-  local kube_system_ns
-  local tmp_kube_system_ns_file="${TMPDIR:-"/tmp/"}netdata-cgroups-kube-system-ns"
-  [ -f "$tmp_kube_system_ns_file" ] && kube_system_ns=$(cat "$tmp_kube_system_ns_file" 2> /dev/null)
+  local tmp_kube_system_ns_uid_file="${TMPDIR:-"/tmp"}/netdata-cgroups-kubesystem-uid"
+  local tmp_kube_containers_file="${TMPDIR:-"/tmp"}/netdata-cgroups-containers"
+
+  local kube_system_uid
+  local labels
 
-  local pods
-  if [ -n "${KUBERNETES_SERVICE_HOST}" ] && [ -n "${KUBERNETES_PORT_443_TCP_PORT}" ]; then
-    local token header host url
-    token="$(< /var/run/secrets/kubernetes.io/serviceaccount/token)"
-    header="Authorization: Bearer $token"
-    host="$KUBERNETES_SERVICE_HOST:$KUBERNETES_PORT_443_TCP_PORT"
+  if [ -n "$cntr_id" ] &&
+    [ -f "$tmp_kube_system_ns_uid_file" ] &&
+    [ -f "$tmp_kube_containers_file" ] &&
+    labels=$(grep "$cntr_id" "$tmp_kube_containers_file" 2>/dev/null); then
+    IFS= read -r kube_system_uid 2>/dev/null <"$tmp_kube_system_ns_uid_file"
+  else
+    IFS= read -r kube_system_uid 2>/dev/null <"$tmp_kube_system_ns_uid_file"
+    local kube_system_ns
+    local pods
+    if [ -n "${KUBERNETES_SERVICE_HOST}" ] && [ -n "${KUBERNETES_PORT_443_TCP_PORT}" ]; then
+      local token header host url
+      token="$(</var/run/secrets/kubernetes.io/serviceaccount/token)"
+      header="Authorization: Bearer $token"
+      host="$KUBERNETES_SERVICE_HOST:$KUBERNETES_PORT_443_TCP_PORT"
+
+      if [ -z "$kube_system_uid" ]; then
+        url="https://$host/api/v1/namespaces/kube-system"
+        # FIX: check HTTP response code
+        if ! kube_system_ns=$(curl -sSk -H "$header" "$url" 2>&1); then
+          warning "${fn}: error on curl '${url}': ${kube_system_ns}."
+        fi
+      fi
 
-    if [ -z "$kube_system_ns" ]; then
-      url="https://$host/api/v1/namespaces/kube-system"
+      url="https://$host/api/v1/pods"
+      [ -n "$MY_NODE_NAME" ] && url+="?fieldSelector=spec.nodeName==$MY_NODE_NAME"
       # FIX: check HTTP response code
-      if ! kube_system_ns=$(curl -sSk -H "$header" "$url" 2>&1); then
-        warning "${fn}: error on curl '${url}': ${kube_system_ns}."
-      else
-        echo "$kube_system_ns" > "$tmp_kube_system_ns_file" 2> /dev/null
+      if ! pods=$(curl -sSk -H "$header" "$url" 2>&1); then
+        warning "${fn}: error on curl '${url}': ${pods}."
+        return 1
+      fi
+    elif ps -C kubelet >/dev/null 2>&1 && command -v kubectl >/dev/null 2>&1; then
+      if [ -z "$kube_system_uid" ]; then
+        if ! kube_system_ns=$(kubectl get namespaces kube-system -o json 2>&1); then
+          warning "${fn}: error on 'kubectl': ${kube_system_ns}."
+        fi
       fi
-    fi
 
-    url="https://$host/api/v1/pods"
-    [ -n "$MY_NODE_NAME" ] && url+="?fieldSelector=spec.nodeName==$MY_NODE_NAME"
-    # FIX: check HTTP response code
-    if ! pods=$(curl -sSk -H "$header" "$url" 2>&1); then
-      warning "${fn}: error on curl '${url}': ${pods}."
+      [[ -z ${KUBE_CONFIG+x} ]] && KUBE_CONFIG="/etc/kubernetes/admin.conf"
+      if ! pods=$(kubectl --kubeconfig="$KUBE_CONFIG" get pods --all-namespaces -o json 2>&1); then
+        warning "${fn}: error on 'kubectl': ${pods}."
+        return 1
+      fi
+    else
+      warning "${fn}: not inside the k8s cluster and 'kubectl' command not available."
       return 1
     fi
-  elif ps -C kubelet > /dev/null 2>&1 && command -v kubectl > /dev/null 2>&1; then
-    if [ -z "$kube_system_ns" ]; then
-      if ! kube_system_ns=$(kubectl get namespaces kube-system -o json 2>&1); then
-        warning "${fn}: error on 'kubectl': ${kube_system_ns}."
-      else
-        echo "$kube_system_ns" > "$tmp_kube_system_ns_file" 2> /dev/null
-      fi
+
+    if [ -n "$kube_system_ns" ] && ! kube_system_uid=$(jq -r '.metadata.uid' <<<"$kube_system_ns" 2>&1); then
+      warning "${fn}: error on 'jq' parse kube_system_ns: ${kube_system_uid}."
     fi
 
-    [[ -z ${KUBE_CONFIG+x} ]] && KUBE_CONFIG="/etc/kubernetes/admin.conf"
-    if ! pods=$(kubectl --kubeconfig="$KUBE_CONFIG" get pods --all-namespaces -o json 2>&1); then
-      warning "${fn}: error on 'kubectl': ${pods}."
+    local jq_filter
+    jq_filter+='.items[] | "'
+    jq_filter+='namespace=\"\(.metadata.namespace)\",'
+    jq_filter+='pod_name=\"\(.metadata.name)\",'
+    jq_filter+='pod_uid=\"\(.metadata.uid)\",'
+    #jq_filter+='\(.metadata.labels | to_entries | map("pod_label_"+.key+"=\""+.value+"\"") | join(",") | if length > 0 then .+"," else . end)'
+    jq_filter+='\((.metadata.ownerReferences[]? | select(.controller==true) | "controller_kind=\""+.kind+"\",controller_name=\""+.name+"\",") // "")'
+    jq_filter+='node_name=\"\(.spec.nodeName)\",'
+    jq_filter+='" + '
+    jq_filter+='(.status.containerStatuses[]? | "'
+    jq_filter+='container_name=\"\(.name)\",'
+    jq_filter+='container_id=\"\(.containerID)\"'
+    jq_filter+='") | '
+    jq_filter+='sub("(docker|cri-o|containerd)://";"")' # containerID: docker://a346da9bc0e3eaba6b295f64ac16e02f2190db2cef570835706a9e7a36e2c722
+
+    local containers
+    if ! containers=$(jq -r "${jq_filter}" <<<"$pods" 2>&1); then
+      warning "${fn}: error on 'jq' parse pods: ${containers}."
       return 1
     fi
-  else
-    warning "${fn}: not inside the k8s cluster and 'kubectl' command not available."
-    return 1
-  fi
 
-  local kube_system_uid
-  if [ -n "$kube_system_ns" ] && ! kube_system_uid=$(jq -r '.metadata.uid' <<< "$kube_system_ns" 2>&1); then
-    warning "${fn}: error on 'jq' parse kube_system_ns: ${kube_system_uid}."
-  fi
-
-  local jq_filter
-  jq_filter+='.items[] | "'
-  jq_filter+='namespace=\"\(.metadata.namespace)\",'
-  jq_filter+='pod_name=\"\(.metadata.name)\",'
-  jq_filter+='pod_uid=\"\(.metadata.uid)\",'
-  #jq_filter+='\(.metadata.labels | to_entries | map("pod_label_"+.key+"=\""+.value+"\"") | join(",") | if length > 0 then .+"," else . end)'
-  jq_filter+='\((.metadata.ownerReferences[]? | select(.controller==true) | "controller_kind=\""+.kind+"\",controller_name=\""+.name+"\",") // "")'
-  jq_filter+='node_name=\"\(.spec.nodeName)\",'
-  jq_filter+='" + '
-  jq_filter+='(.status.containerStatuses[]? | "'
-  jq_filter+='container_name=\"\(.name)\",'
-  jq_filter+='container_id=\"\(.containerID)\"'
-  jq_filter+='") | '
-  jq_filter+='sub("(docker|cri-o|containerd)://";"")' # containerID: docker://a346da9bc0e3eaba6b295f64ac16e02f2190db2cef570835706a9e7a36e2c722
-
-  local containers
-  if ! containers=$(jq -r "${jq_filter}" <<< "$pods" 2>&1); then
-    warning "${fn}: error on 'jq' parse pods: ${containers}."
-    return 1
+    [ -n "$kube_system_ns" ] && [ -n "$kube_system_uid" ] && echo "$kube_system_uid" >"$tmp_kube_system_ns_uid_file" 2>/dev/null
+    echo "$containers" >"$tmp_kube_containers_file" 2>/dev/null
   fi
 
   local qos_class
@@ -282,9 +321,8 @@ function k8s_get_kubepod_name() {
 
   # available labels:
   # namespace, pod_name, pod_uid, container_name, container_id, node_name
-  local labels
   if [ -n "$cntr_id" ]; then
-    if labels=$(grep "$cntr_id" <<< "$containers" 2> /dev/null); then
+    if [ -n "$labels" ] || labels=$(grep "$cntr_id" <<< "$containers" 2> /dev/null); then
       labels+=',kind="container"'
       labels+=",qos_class=\"$qos_class\""
       [ -n "$kube_system_uid" ] && [ "$kube_system_uid" != "null" ] && labels+=",cluster_id=\"$kube_system_uid\""
@@ -294,6 +332,8 @@ function k8s_get_kubepod_name() {
       name+="_$(get_lbl_val "$labels" container_name)"
       labels=$(add_lbl_prefix "$labels" "k8s_")
       name+=" $labels"
+    else
+      return 2
     fi
   elif [ -n "$pod_uid" ]; then
     if labels=$(grep "$pod_uid" -m 1 <<< "$containers" 2> /dev/null); then
@@ -306,6 +346,8 @@ function k8s_get_kubepod_name() {
       name+="_$(get_lbl_val "$labels" pod_name)"
       labels=$(add_lbl_prefix "$labels" "k8s_")
       name+=" $labels"
+    else 
+      return 2
     fi
   fi
 
@@ -322,15 +364,13 @@ function k8s_get_kubepod_name() {
 
 function k8s_get_name() {
   local fn="${FUNCNAME[0]}"
-  local id="${1}"
-
-  NAME=$(k8s_get_kubepod_name "$id")
+  local cgroup_path="${1}"
+  local id="${2}"
 
-  if [ -z "${NAME}" ]; then
-    warning "${fn}: cannot find the name of cgroup with id '${id}'. Setting name to ${id} and disabling it."
-    NAME="${id}"
-    NAME_NOT_FOUND=3
-  else
+  NAME=$(k8s_get_kubepod_name "$cgroup_path" "$id")
+ 
+  case "$?" in
+  0)
     NAME="k8s_${NAME}"
 
     local name labels
@@ -341,7 +381,19 @@ function k8s_get_name() {
     else
       info "${fn}: cgroup '${id}' has chart name '${NAME}'"
     fi
-  fi
+    EXIT_CODE=$EXIT_SUCCESS
+    ;;
+  2)
+    warning "${fn}: cannot find the name of cgroup with id '${id}'. Setting name to ${id} and asking for retry."
+    NAME="${id}"
+    EXIT_CODE=$EXIT_RETRY
+    ;;
+  *)
+    warning "${fn}: cannot find the name of cgroup with id '${id}'. Setting name to ${id} and disabling it."
+    NAME="${id}"
+    EXIT_CODE=$EXIT_DISABLE
+    ;;
+  esac
 }
 
 function docker_get_name() {
@@ -353,7 +405,7 @@ function docker_get_name() {
   fi
   if [ -z "${NAME}" ]; then
     warning "cannot find the name of docker container '${id}'"
-    NAME_NOT_FOUND=2
+    EXIT_CODE=$EXIT_RETRY
     NAME="${id:0:12}"
   else
     info "docker container '${id}' is named '${NAME}'"
@@ -378,7 +430,7 @@ function podman_get_name() {
 
   if [ -z "${NAME}" ]; then
     warning "cannot find the name of podman container '${id}'"
-    NAME_NOT_FOUND=2
+    EXIT_CODE=$EXIT_RETRY
     NAME="${id:0:12}"
   else
     info "podman container '${id}' is named '${NAME}'"
@@ -398,8 +450,12 @@ function podman_validate_id() {
 
 DOCKER_HOST="${DOCKER_HOST:=/var/run/docker.sock}"
 PODMAN_HOST="${PODMAN_HOST:=/run/podman/podman.sock}"
-CGROUP="${1}"
-NAME_NOT_FOUND=0
+CGROUP_PATH="${1}" # the path as it is (e.g. '/docker/efcf4c409')
+CGROUP="${2}"      # the modified path (e.g. 'docker_efcf4c409')
+EXIT_SUCCESS=0
+EXIT_RETRY=2
+EXIT_DISABLE=3
+EXIT_CODE=$EXIT_SUCCESS
 NAME=
 
 # -----------------------------------------------------------------------------
@@ -410,7 +466,7 @@ fi
 
 if [ -z "${NAME}" ]; then
   if [[ ${CGROUP} =~ ^.*kubepods.* ]]; then
-    k8s_get_name "${CGROUP}"
+    k8s_get_name "${CGROUP_PATH}" "${CGROUP}"
   fi
 fi
 
@@ -481,4 +537,4 @@ fi
 info "cgroup '${CGROUP}' is called '${NAME}'"
 echo "${NAME}"
 
-exit ${NAME_NOT_FOUND}
+exit ${EXIT_CODE}

Разница между файлами не показана из-за своего большого размера
+ 481 - 330
collectors/cgroups.plugin/sys_fs_cgroup.c


+ 1 - 1
collectors/cgroups.plugin/sys_fs_cgroup.h

@@ -39,6 +39,6 @@ typedef struct netdata_ebpf_cgroup_shm {
 
 #include "../proc.plugin/plugin_proc.h"
 
-extern char *parse_k8s_data(struct label **labels, char *data);
+extern char *k8s_parse_resolved_name(struct label **labels, char *data);
 
 #endif //NETDATA_SYS_FS_CGROUP_H

+ 4 - 4
collectors/cgroups.plugin/tests/test_cgroups_plugin.c

@@ -8,7 +8,7 @@ int netdata_zero_metrics_enabled = 1;
 struct config netdata_config;
 char *netdata_configured_primary_plugins_dir = NULL;
 
-static void test_parse_k8s_data(void **state)
+static void test_k8s_parse_resolved_name(void **state)
 {
     UNUSED(state);
 
@@ -89,7 +89,7 @@ static void test_parse_k8s_data(void **state)
             expect_value(__wrap_add_label_to_list, label_source, LABEL_SOURCE_KUBERNETES);    
         }
 
-        char *name = parse_k8s_data(&labels, data);
+        char *name = k8s_parse_resolved_name(&labels, data);
 
         assert_string_equal(name, test_data[i].name);
         assert_ptr_equal(labels, 0xff);
@@ -101,10 +101,10 @@ static void test_parse_k8s_data(void **state)
 int main(void)
 {
     const struct CMUnitTest tests[] = {
-        cmocka_unit_test(test_parse_k8s_data),
+        cmocka_unit_test(test_k8s_parse_resolved_name),
     };
 
-    int test_res = cmocka_run_group_tests_name("test_parse_k8s_data", tests, NULL, NULL);
+    int test_res = cmocka_run_group_tests_name("test_k8s_parse_resolved_name", tests, NULL, NULL);
 
     return test_res;
 }

Некоторые файлы не были показаны из-за большого количества измененных файлов