nvtop icon indicating copy to clipboard operation
nvtop copied to clipboard

Feature request: Collumn for process container name

Open sammcj opened this issue 2 years ago • 2 comments
trafficstars

It would be awesome if nvtop had a collumn that displayed the name of the container or namespace that processes were running within.

This would help corrlate GPU utilisation to running containers.

Thanks and keep up the great work!


(Somewhat related https://github.com/bcicen/ctop/issues/344)

sammcj avatar Nov 14 '23 21:11 sammcj

I guess that it's hard for a process to know if it's running in a VM/container. Maybe add a column showing the hostname of the machine which is probably the cleanest way to show that information?

Syllo avatar Feb 23 '24 14:02 Syllo

Hmm I wonder if the cgroup path could be used?

I don’t really know C but a certain large language model suggested something like this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFFER_SIZE 1024

// Function to trim newline character from strings
void trim_newline(char* string) {
    if (string == NULL) return;
    char* newline = strchr(string, '\n');
    if (newline) *newline = 0;
}

// Function to get the container name from cgroup file
void get_container_name_from_pid(int pid, char* container_name, int max_len) {
    char path[BUFFER_SIZE];
    char buffer[BUFFER_SIZE];
    FILE* file;
    snprintf(path, sizeof(path), "/proc/%d/cgroup", pid);

    if ((file = fopen(path, "r")) == NULL) {
        perror("Error opening cgroup file");
        strcpy(container_name, "");
        return;
    }

    while (fgets(buffer, sizeof(buffer), file) != NULL) {
        // Docker containers are usually identified by "docker" in the cgroup path
        if (strstr(buffer, "/docker/") != NULL) {
            char* start = strrchr(buffer, '/');
            if (start != NULL) {
                start++; // Move past the '/'
                trim_newline(start);
                strncpy(container_name, start, max_len);
                fclose(file);
                return;
            }
        }
    }

    // If we reach here, no container name was found
    strcpy(container_name, "");
    fclose(file);
}

int main(int argc, char* argv[]) {
    if (argc < 2) {
        printf("Usage: %s <pid>\n", argv[0]);
        return 1;
    }

    int pid = atoi(argv[1]);
    char container_name[BUFFER_SIZE];
    get_container_name_from_pid(pid, container_name, sizeof(container_name));

    if (strlen(container_name) > 0) {
        printf("Container name: %s\n", container_name);
    } else {
        printf("The PID %d is not running in a Docker container.\n", pid);
    }

    return 0;
}

sammcj avatar Feb 23 '24 21:02 sammcj