Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 /* procacct.c
0003  *
0004  * Demonstrator of fetching resource data on task exit, as a way
0005  * to accumulate accurate program resource usage statistics, without
0006  * prior identification of the programs. For that, the fields for
0007  * device and inode of the program executable binary file are also
0008  * extracted in addition to the command string.
0009  *
0010  * The TGID together with the PID and the AGROUP flag allow
0011  * identification of threads in a process and single-threaded processes.
0012  * The ac_tgetime field gives proper whole-process walltime.
0013  *
0014  * Written (changed) by Thomas Orgis, University of Hamburg in 2022
0015  *
0016  * This is a cheap derivation (inheriting the style) of getdelays.c:
0017  *
0018  * Utility to get per-pid and per-tgid delay accounting statistics
0019  * Also illustrates usage of the taskstats interface
0020  *
0021  * Copyright (C) Shailabh Nagar, IBM Corp. 2005
0022  * Copyright (C) Balbir Singh, IBM Corp. 2006
0023  * Copyright (c) Jay Lan, SGI. 2006
0024  */
0025 
0026 #include <stdio.h>
0027 #include <stdlib.h>
0028 #include <errno.h>
0029 #include <unistd.h>
0030 #include <poll.h>
0031 #include <string.h>
0032 #include <fcntl.h>
0033 #include <sys/types.h>
0034 #include <sys/stat.h>
0035 #include <sys/socket.h>
0036 #include <sys/wait.h>
0037 #include <signal.h>
0038 
0039 #include <linux/genetlink.h>
0040 #include <linux/acct.h>
0041 #include <linux/taskstats.h>
0042 #include <linux/kdev_t.h>
0043 
0044 /*
0045  * Generic macros for dealing with netlink sockets. Might be duplicated
0046  * elsewhere. It is recommended that commercial grade applications use
0047  * libnl or libnetlink and use the interfaces provided by the library
0048  */
0049 #define GENLMSG_DATA(glh)   ((void *)(NLMSG_DATA(glh) + GENL_HDRLEN))
0050 #define GENLMSG_PAYLOAD(glh)    (NLMSG_PAYLOAD(glh, 0) - GENL_HDRLEN)
0051 #define NLA_DATA(na)        ((void *)((char *)(na) + NLA_HDRLEN))
0052 #define NLA_PAYLOAD(len)    (len - NLA_HDRLEN)
0053 
0054 #define err(code, fmt, arg...)          \
0055     do {                    \
0056         fprintf(stderr, fmt, ##arg);    \
0057         exit(code);         \
0058     } while (0)
0059 
0060 int rcvbufsz;
0061 char name[100];
0062 int dbg;
0063 int print_delays;
0064 int print_io_accounting;
0065 int print_task_context_switch_counts;
0066 
0067 #define PRINTF(fmt, arg...) {           \
0068         if (dbg) {          \
0069             printf(fmt, ##arg); \
0070         }               \
0071     }
0072 
0073 /* Maximum size of response requested or message sent */
0074 #define MAX_MSG_SIZE    1024
0075 /* Maximum number of cpus expected to be specified in a cpumask */
0076 #define MAX_CPUS    32
0077 
0078 struct msgtemplate {
0079     struct nlmsghdr n;
0080     struct genlmsghdr g;
0081     char buf[MAX_MSG_SIZE];
0082 };
0083 
0084 char cpumask[100+6*MAX_CPUS];
0085 
0086 static void usage(void)
0087 {
0088     fprintf(stderr, "procacct [-v] [-w logfile] [-r bufsize] [-m cpumask]\n");
0089     fprintf(stderr, "  -v: debug on\n");
0090 }
0091 
0092 /*
0093  * Create a raw netlink socket and bind
0094  */
0095 static int create_nl_socket(int protocol)
0096 {
0097     int fd;
0098     struct sockaddr_nl local;
0099 
0100     fd = socket(AF_NETLINK, SOCK_RAW, protocol);
0101     if (fd < 0)
0102         return -1;
0103 
0104     if (rcvbufsz)
0105         if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF,
0106                 &rcvbufsz, sizeof(rcvbufsz)) < 0) {
0107             fprintf(stderr, "Unable to set socket rcv buf size to %d\n",
0108                 rcvbufsz);
0109             goto error;
0110         }
0111 
0112     memset(&local, 0, sizeof(local));
0113     local.nl_family = AF_NETLINK;
0114 
0115     if (bind(fd, (struct sockaddr *) &local, sizeof(local)) < 0)
0116         goto error;
0117 
0118     return fd;
0119 error:
0120     close(fd);
0121     return -1;
0122 }
0123 
0124 
0125 static int send_cmd(int sd, __u16 nlmsg_type, __u32 nlmsg_pid,
0126          __u8 genl_cmd, __u16 nla_type,
0127          void *nla_data, int nla_len)
0128 {
0129     struct nlattr *na;
0130     struct sockaddr_nl nladdr;
0131     int r, buflen;
0132     char *buf;
0133 
0134     struct msgtemplate msg;
0135 
0136     msg.n.nlmsg_len = NLMSG_LENGTH(GENL_HDRLEN);
0137     msg.n.nlmsg_type = nlmsg_type;
0138     msg.n.nlmsg_flags = NLM_F_REQUEST;
0139     msg.n.nlmsg_seq = 0;
0140     msg.n.nlmsg_pid = nlmsg_pid;
0141     msg.g.cmd = genl_cmd;
0142     msg.g.version = 0x1;
0143     na = (struct nlattr *) GENLMSG_DATA(&msg);
0144     na->nla_type = nla_type;
0145     na->nla_len = nla_len + 1 + NLA_HDRLEN;
0146     memcpy(NLA_DATA(na), nla_data, nla_len);
0147     msg.n.nlmsg_len += NLMSG_ALIGN(na->nla_len);
0148 
0149     buf = (char *) &msg;
0150     buflen = msg.n.nlmsg_len;
0151     memset(&nladdr, 0, sizeof(nladdr));
0152     nladdr.nl_family = AF_NETLINK;
0153     while ((r = sendto(sd, buf, buflen, 0, (struct sockaddr *) &nladdr,
0154                sizeof(nladdr))) < buflen) {
0155         if (r > 0) {
0156             buf += r;
0157             buflen -= r;
0158         } else if (errno != EAGAIN)
0159             return -1;
0160     }
0161     return 0;
0162 }
0163 
0164 
0165 /*
0166  * Probe the controller in genetlink to find the family id
0167  * for the TASKSTATS family
0168  */
0169 static int get_family_id(int sd)
0170 {
0171     struct {
0172         struct nlmsghdr n;
0173         struct genlmsghdr g;
0174         char buf[256];
0175     } ans;
0176 
0177     int id = 0, rc;
0178     struct nlattr *na;
0179     int rep_len;
0180 
0181     strcpy(name, TASKSTATS_GENL_NAME);
0182     rc = send_cmd(sd, GENL_ID_CTRL, getpid(), CTRL_CMD_GETFAMILY,
0183             CTRL_ATTR_FAMILY_NAME, (void *)name,
0184             strlen(TASKSTATS_GENL_NAME)+1);
0185     if (rc < 0)
0186         return 0;   /* sendto() failure? */
0187 
0188     rep_len = recv(sd, &ans, sizeof(ans), 0);
0189     if (ans.n.nlmsg_type == NLMSG_ERROR ||
0190         (rep_len < 0) || !NLMSG_OK((&ans.n), rep_len))
0191         return 0;
0192 
0193     na = (struct nlattr *) GENLMSG_DATA(&ans);
0194     na = (struct nlattr *) ((char *) na + NLA_ALIGN(na->nla_len));
0195     if (na->nla_type == CTRL_ATTR_FAMILY_ID)
0196         id = *(__u16 *) NLA_DATA(na);
0197 
0198     return id;
0199 }
0200 
0201 #define average_ms(t, c) (t / 1000000ULL / (c ? c : 1))
0202 
0203 static void print_procacct(struct taskstats *t)
0204 {
0205     /* First letter: T is a mere thread, G the last in a group, U  unknown. */
0206     printf(
0207         "%c pid=%lu tgid=%lu uid=%lu wall=%llu gwall=%llu cpu=%llu vmpeak=%llu rsspeak=%llu dev=%lu:%lu inode=%llu comm=%s\n"
0208     ,   t->version >= 12 ? (t->ac_flag & AGROUP ? 'P' : 'T') : '?'
0209     ,   (unsigned long)t->ac_pid
0210     ,   (unsigned long)(t->version >= 12 ? t->ac_tgid : 0)
0211     ,   (unsigned long)t->ac_uid
0212     ,   (unsigned long long)t->ac_etime
0213     ,   (unsigned long long)(t->version >= 12 ? t->ac_tgetime : 0)
0214     ,   (unsigned long long)(t->ac_utime+t->ac_stime)
0215     ,   (unsigned long long)t->hiwater_vm
0216     ,   (unsigned long long)t->hiwater_rss
0217     ,   (unsigned long)(t->version >= 12 ? MAJOR(t->ac_exe_dev) : 0)
0218     ,   (unsigned long)(t->version >= 12 ? MINOR(t->ac_exe_dev) : 0)
0219     ,   (unsigned long long)(t->version >= 12 ? t->ac_exe_inode : 0)
0220     ,   t->ac_comm
0221     );
0222 }
0223 
0224 void handle_aggr(int mother, struct nlattr *na, int fd)
0225 {
0226     int aggr_len = NLA_PAYLOAD(na->nla_len);
0227     int len2 = 0;
0228     pid_t rtid = 0;
0229 
0230     na = (struct nlattr *) NLA_DATA(na);
0231     while (len2 < aggr_len) {
0232         switch (na->nla_type) {
0233         case TASKSTATS_TYPE_PID:
0234             rtid = *(int *) NLA_DATA(na);
0235             PRINTF("PID\t%d\n", rtid);
0236             break;
0237         case TASKSTATS_TYPE_TGID:
0238             rtid = *(int *) NLA_DATA(na);
0239             PRINTF("TGID\t%d\n", rtid);
0240             break;
0241         case TASKSTATS_TYPE_STATS:
0242             if (mother == TASKSTATS_TYPE_AGGR_PID)
0243                 print_procacct((struct taskstats *) NLA_DATA(na));
0244             if (fd) {
0245                 if (write(fd, NLA_DATA(na), na->nla_len) < 0)
0246                     err(1, "write error\n");
0247             }
0248             break;
0249         case TASKSTATS_TYPE_NULL:
0250             break;
0251         default:
0252             fprintf(stderr, "Unknown nested nla_type %d\n",
0253                 na->nla_type);
0254             break;
0255         }
0256         len2 += NLA_ALIGN(na->nla_len);
0257         na = (struct nlattr *)((char *)na +
0258                          NLA_ALIGN(na->nla_len));
0259     }
0260 }
0261 
0262 int main(int argc, char *argv[])
0263 {
0264     int c, rc, rep_len, aggr_len, len2;
0265     int cmd_type = TASKSTATS_CMD_ATTR_UNSPEC;
0266     __u16 id;
0267     __u32 mypid;
0268 
0269     struct nlattr *na;
0270     int nl_sd = -1;
0271     int len = 0;
0272     pid_t tid = 0;
0273 
0274     int fd = 0;
0275     int write_file = 0;
0276     int maskset = 0;
0277     char *logfile = NULL;
0278     int containerset = 0;
0279     char *containerpath = NULL;
0280     int cfd = 0;
0281     int forking = 0;
0282     sigset_t sigset;
0283 
0284     struct msgtemplate msg;
0285 
0286     while (!forking) {
0287         c = getopt(argc, argv, "m:vr:");
0288         if (c < 0)
0289             break;
0290 
0291         switch (c) {
0292         case 'w':
0293             logfile = strdup(optarg);
0294             printf("write to file %s\n", logfile);
0295             write_file = 1;
0296             break;
0297         case 'r':
0298             rcvbufsz = atoi(optarg);
0299             printf("receive buf size %d\n", rcvbufsz);
0300             if (rcvbufsz < 0)
0301                 err(1, "Invalid rcv buf size\n");
0302             break;
0303         case 'm':
0304             strncpy(cpumask, optarg, sizeof(cpumask));
0305             cpumask[sizeof(cpumask) - 1] = '\0';
0306             maskset = 1;
0307             break;
0308         case 'v':
0309             printf("debug on\n");
0310             dbg = 1;
0311             break;
0312         default:
0313             usage();
0314             exit(-1);
0315         }
0316     }
0317     if (!maskset) {
0318         maskset = 1;
0319         strncpy(cpumask, "1", sizeof(cpumask));
0320         cpumask[sizeof(cpumask) - 1] = '\0';
0321     }
0322     printf("cpumask %s maskset %d\n", cpumask, maskset);
0323 
0324     if (write_file) {
0325         fd = open(logfile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
0326         if (fd == -1) {
0327             perror("Cannot open output file\n");
0328             exit(1);
0329         }
0330     }
0331 
0332     nl_sd = create_nl_socket(NETLINK_GENERIC);
0333     if (nl_sd < 0)
0334         err(1, "error creating Netlink socket\n");
0335 
0336     mypid = getpid();
0337     id = get_family_id(nl_sd);
0338     if (!id) {
0339         fprintf(stderr, "Error getting family id, errno %d\n", errno);
0340         goto err;
0341     }
0342     PRINTF("family id %d\n", id);
0343 
0344     if (maskset) {
0345         rc = send_cmd(nl_sd, id, mypid, TASKSTATS_CMD_GET,
0346                   TASKSTATS_CMD_ATTR_REGISTER_CPUMASK,
0347                   &cpumask, strlen(cpumask) + 1);
0348         PRINTF("Sent register cpumask, retval %d\n", rc);
0349         if (rc < 0) {
0350             fprintf(stderr, "error sending register cpumask\n");
0351             goto err;
0352         }
0353     }
0354 
0355     do {
0356         rep_len = recv(nl_sd, &msg, sizeof(msg), 0);
0357         PRINTF("received %d bytes\n", rep_len);
0358 
0359         if (rep_len < 0) {
0360             fprintf(stderr, "nonfatal reply error: errno %d\n",
0361                 errno);
0362             continue;
0363         }
0364         if (msg.n.nlmsg_type == NLMSG_ERROR ||
0365             !NLMSG_OK((&msg.n), rep_len)) {
0366             struct nlmsgerr *err = NLMSG_DATA(&msg);
0367 
0368             fprintf(stderr, "fatal reply error,  errno %d\n",
0369                 err->error);
0370             goto done;
0371         }
0372 
0373         PRINTF("nlmsghdr size=%zu, nlmsg_len=%d, rep_len=%d\n",
0374                sizeof(struct nlmsghdr), msg.n.nlmsg_len, rep_len);
0375 
0376 
0377         rep_len = GENLMSG_PAYLOAD(&msg.n);
0378 
0379         na = (struct nlattr *) GENLMSG_DATA(&msg);
0380         len = 0;
0381         while (len < rep_len) {
0382             len += NLA_ALIGN(na->nla_len);
0383             int mother = na->nla_type;
0384 
0385             PRINTF("mother=%i\n", mother);
0386             switch (na->nla_type) {
0387             case TASKSTATS_TYPE_AGGR_PID:
0388             case TASKSTATS_TYPE_AGGR_TGID:
0389                 /* For nested attributes, na follows */
0390                 handle_aggr(mother, na, fd);
0391                 break;
0392             default:
0393                 fprintf(stderr, "Unexpected nla_type %d\n",
0394                     na->nla_type);
0395             case TASKSTATS_TYPE_NULL:
0396                 break;
0397             }
0398             na = (struct nlattr *) (GENLMSG_DATA(&msg) + len);
0399         }
0400     } while (1);
0401 done:
0402     if (maskset) {
0403         rc = send_cmd(nl_sd, id, mypid, TASKSTATS_CMD_GET,
0404                   TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK,
0405                   &cpumask, strlen(cpumask) + 1);
0406         printf("Sent deregister mask, retval %d\n", rc);
0407         if (rc < 0)
0408             err(rc, "error sending deregister cpumask\n");
0409     }
0410 err:
0411     close(nl_sd);
0412     if (fd)
0413         close(fd);
0414     if (cfd)
0415         close(cfd);
0416     return 0;
0417 }