Docker Community Forums

Share and learn in the Docker community.

Using perf_event_open to monitor Docker containers


(Mmb2018) #1

Hello,
I wrote a program in C to retrieve performance events such as cpu-cycles of Docker containers. I mean, a user space program at host level (host level monitoring, not inside docker). I give pid of the docker container as pid entry of perf_event_open() , However, I have always 0 as returned value. I have tested the program for other non-docker pids for example firefox and it works very well.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/perf_event.h>
#include <asm/unistd.h>
static long perf_event_open(struct perf_event_attr *hw_event, pid_t pid, int cpu, int group_fd, unsigned long flags)
{
int ret;
ret = syscall(__NR_perf_event_open, hw_event, pid, cpu,
group_fd, flags);
return ret;
}
int
main(int argc, char **argv)
{
struct perf_event_attr pe;
long long count;
int fd;
fd = open("/sys/fs/cgroup/perf_event/docker/f42c13cd9dd700544fe670e30d0b3216bdceaf01ddc370405618fdecfd10b26d", O_RDONLY);
if (fd == -1)
return 0;
memset(&pe, 0, sizeof(struct perf_event_attr));
pe.type = PERF_TYPE_HARDWARE;
pe.size = sizeof(struct perf_event_attr);
pe.config = PERF_COUNT_HW_CPU_CYCLES;
pe.disabled = 1;
pe.exclude_kernel = 0;
pe.exclude_hv = 0;
fd = perf_event_open(&pe, fd, -1, -1, PERF_FLAG_PID_CGROUP);
if (fd == -1) {
fprintf(stderr, “Error opening leader %llx\n”, pe.config);
exit(EXIT_FAILURE);
}
ioctl(fd, PERF_EVENT_IOC_RESET, 0);
ioctl(fd, PERF_EVENT_IOC_ENABLE, 0);
usleep(100);
ioctl(fd, PERF_EVENT_IOC_DISABLE, 0);
read(fd, &count, sizeof(long long));
printf(“Used %lld instructions\n”, count);
close(fd);

I set PERF_FLAG_PID_CGROUP as flag, nothing changes!
According to the Man page of perf_event_open(), I also give the fd opened on the directory of docker container in groupfs. Doesn’t work !

Would you please help me to solve the problem? Thanks

OS: Ubuntu 16.04

Kernel: 4.15.0-041500-generic

Architecture: X86_64

Discussion on Stackoverflow: