nvml-sys 0.0.6

A low-level FFI wrapper around the Persistent Memory Development Kit, PMDK (formerly NVML) and its libraries, including libpmem, libpmemobj and others. Currently tracks master after version 1.3.1.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
/*
 * Copyright 2016-2017, Intel Corporation
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in
 *       the documentation and/or other materials provided with the
 *       distribution.
 *
 *     * Neither the name of the copyright holder nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * ctrld.c -- simple application which helps running tests on remote node.
 *
 * XXX - wait_port is not supported on FreeBSD because there are currently
 *       no test cases that require it.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <dirent.h>
#include <signal.h>
#include <limits.h>
#include <sys/queue.h>
#include <sys/types.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdarg.h>

#include "os.h"

#ifdef __FreeBSD__
#include "signals_freebsd.h"
#else
#include "signals_linux.h"
#endif

#define APP_NAME "ctrld"
#define BUFF_SIZE 4096

#define S_MINUTE	(60)		/* seconds in one minute */
#define S_HOUR		(60 * 60)	/* seconds in one hour */
#define S_DAY		(60 * 60 * 24)	/* seconds in one day */

static FILE *log_fh;

static void
log_err(const char *file, int lineno, const char *fmt, ...)
{
	FILE *fh = log_fh ? log_fh : stderr;
	va_list ap;
	fprintf(fh, "[%s:%d] ", file, lineno);

	char *prefix = "";
	char *errstr = "";
	if (*fmt == '!') {
		fmt++;
		prefix = ": ";
		errstr = strerror(errno);
	}

	va_start(ap, fmt);
	vfprintf(fh, fmt, ap);
	va_end(ap);

	fprintf(fh, "%s%s\n", prefix, errstr);
	fflush(fh);
}

#define CTRLD_LOG(...) log_err(__FILE__, __LINE__, __VA_ARGS__)

struct inode_item {
	LIST_ENTRY(inode_item) next;
	unsigned long inode;
};

struct inodes {
	LIST_HEAD(inode_items, inode_item) head;
};

/*
 * usage -- print usage and exit with failure code
 */
static void
usage(void)
{
	CTRLD_LOG("usage: %s <pid file> <cmd> [<arg>]", APP_NAME);
	CTRLD_LOG("commands:");
	CTRLD_LOG("  exe <command> [<args...>] -- "
			"run specified command");
	CTRLD_LOG("  run  <timeout> <command> [<args...>] -- "
			"run specified command with given timeout");
	CTRLD_LOG("  wait [<timeout>]                     -- "
			"wait for command");
#ifndef __FreeBSD_
	CTRLD_LOG("  wait_port <port>                     -- "
			"wait until a port is opened");
#endif
	CTRLD_LOG("  kill <signal>                        -- "
			"send a signal to command");
	exit(EXIT_FAILURE);
}

/*
 * alloc_argv -- allocate NULL terminated list of arguments at specified offset
 */
static char **
alloc_argv(unsigned argc, char *argv[], unsigned off)
{
	if (argc < off)
		return NULL;

	unsigned nargc = argc - off;
	char **nargv = malloc((nargc + 1) * sizeof(char *));
	if (!nargv)
		return NULL;

	for (unsigned i = 0; i < nargc; i++)
		nargv[i] = argv[i + off];

	nargv[nargc] = NULL;

	return nargv;
}

/*
 * do_run_or_exe -- execute the 'run' or the 'exe' command
 *
 * if timeout is equal to 0 cmd will be just executed (the 'exe' command)
 * otherwise it will be run and wait with timeout (the 'run' command)
 */
static int
do_run_or_exe(const char *pid_file, char *cmd, char *argv[], unsigned timeout)
{
	int rv = -1;

	FILE *fh = os_fopen(pid_file, "w+");
	if (!fh) {
		CTRLD_LOG("!%s", pid_file);
		return -1;
	}

	int fd = fileno(fh);
	if (fd == -1) {
		CTRLD_LOG("!fileno");
		goto err;
	}

	if (os_flock(fd, LOCK_EX | LOCK_NB)) {
		CTRLD_LOG("!flock");
		goto err;
	}

	if (timeout != 0) {
		if (daemon(1, 0)) {
			CTRLD_LOG("!daemon");
			goto err;
		}
	}

	int child = fork();
	switch (child) {
	case -1:
		CTRLD_LOG("!fork");
		fprintf(fh, "-1r%d", errno);
		goto err;
	case 0:
		execvp(cmd, argv);
		CTRLD_LOG("!execvp(%s)", cmd);
		goto err;
	default:
		break;
	}

	if (fprintf(fh, "%d", child) < 0) {
		CTRLD_LOG("!fprintf");
		goto err;
	}

	if (fflush(fh)) {
		CTRLD_LOG("!fflush");
		goto err;
	}

	int child_timeout = -1;
	if (timeout != 0) {
		child_timeout = fork();
		switch (child_timeout) {
		case -1:
			CTRLD_LOG("!fork");
			fprintf(fh, "-1r%d", errno);
			goto err;
		case 0:
			fclose(fh);
			sleep(timeout);
			return 0;
		default:
			break;
		}
	}

	int ret = 0;
	int pid = wait(&ret);
	if (pid == child) {
		if (timeout != 0) {
			/* kill the timeout child */
			kill(child_timeout, SIGTERM);
		}

		if (WIFSIGNALED(ret)) {
			ret = 128 + WTERMSIG(ret);
		} else {
			ret = WEXITSTATUS(ret);
		}

		if (fseek(fh, 0, SEEK_SET)) {
			CTRLD_LOG("!fseek");
			goto err;
		}

		if (os_ftruncate(fileno(fh), 0)) {
			CTRLD_LOG("!ftruncate");
			goto err;
		}

		fprintf(fh, "%dr%d", child, ret);

	} else if (timeout != 0 && pid == child_timeout) {
		CTRLD_LOG("run: timeout");
		if (kill(child, SIGTERM) && errno != ESRCH) {
			CTRLD_LOG("!kill");
			goto err;
		}
		CTRLD_LOG("run: process '%s' killed (PID %i)", cmd, child);
	} else {
		CTRLD_LOG("!wait");
		goto err;
	}

	rv = 0;
err:
	fclose(fh);
	return rv;
}

/*
 * do_wait -- execute the 'wait' command
 */
static int
do_wait(char *pid_file, int timeout)
{
	int fd = os_open(pid_file, O_RDONLY);
	if (fd < 0) {
		perror(pid_file);
		return 1;
	}

	int ret;

	int t = 0;
	while ((timeout == -1 || t < timeout) &&
		os_flock(fd, LOCK_EX | LOCK_NB)) {
		sleep(1);
		t++;
	}

	FILE *fh = os_fdopen(fd, "r");
	if (!fh) {
		CTRLD_LOG("!fdopen");
		ret = 1;
		goto err;
	}

	pid_t pid;
	char r;
	int n = fscanf(fh, "%d%c%d", &pid, &r, &ret);
	if (n < 0) {
		CTRLD_LOG("!fscanf");
		ret = 1;
		goto err;
	}

	if (n == 2 || (n == 3 && r != 'r')) {
		CTRLD_LOG("invalid format of PID file");
		ret = 1;
		goto err;
	}

	if (n == 1) {
		if (timeout >= 0) {
			ret = -1;
			goto err;
		} else {
			CTRLD_LOG("missing return value");
			ret = 1;
			goto err;
		}
	}

err:
	os_close(fd);
	fclose(fh);
	return ret;
}

/*
 * do_kill -- execute the 'kill' command
 */
static int
do_kill(char *pid_file, int signo)
{
	FILE *fh = os_fopen(pid_file, "r");
	if (!fh) {
		CTRLD_LOG("!%s", pid_file);
		return 1;
	}

	int ret;
	pid_t pid;
	int n = fscanf(fh, "%d", &pid);
	if (n == 0) {
		ret = 0;
		goto out;
	}

	/* do not fail if such process already does not exist */
	if (kill(pid, signo) && errno != ESRCH) {
		CTRLD_LOG("!kill");
		ret = 1;
		goto out;
	}

	ret = 0;
out:
	fclose(fh);
	return ret;
}

#ifndef __FreeBSD__	/* XXX wait_port support */
/*
 * contains_inode -- check if list contains specified inode
 */
static int
contains_inode(struct inodes *inodes, unsigned long inode)
{
	struct inode_item *inode_item;
	LIST_FOREACH(inode_item, &inodes->head, next) {
		if (inode_item->inode == inode)
			return 1;
	}

	return 0;
}

/*
 * has_port_inode -- check if /proc/net/tcp has an entry with specified
 * port and inode
 */
static int
has_port_inode(unsigned short port, struct inodes *inodes)
{
	/* format of /proc/net/tcp entries */
	const char *tcp_fmt =
		"%*d: "
		"%*64[0-9A-Fa-f]:%X "
		"%*64[0-9A-Fa-f]:%*X "
		"%*X %*lX:%*lX %*X:%*lX "
		"%*lX %*d %*d %lu %*s\n";

	char buff[BUFF_SIZE];

	FILE *fh = os_fopen("/proc/net/tcp", "r");
	if (!fh) {
		CTRLD_LOG("!%s", "/proc/net/tcp");
		return -1;
	}

	int ret;
	/* read heading */
	char *s = fgets(buff, 4096, fh);
	if (!s) {
		ret = -1;
		goto out;
	}

	while (1) {
		s = fgets(buff, 4096, fh);
		if (!s)
			break;

		/* read port number and inode number */
		unsigned p;
		unsigned long inode;
		if (sscanf(s, tcp_fmt, &p, &inode) != 2) {
			ret = -1;
			goto out;
		}

		/*
		 * if port matches and inode is on a list
		 * the process has this port opened
		 */
		if (p == port && contains_inode(inodes, inode)) {
			ret = 1;
			goto out;
		}
	}

	ret = 0;

out:
	fclose(fh);
	return ret;
}

/*
 * get_inodes -- get list of inodes
 */
static int
get_inodes(pid_t pid, struct inodes *inodes)
{
	char path[PATH_MAX];
	char link[PATH_MAX];

	/* set a path to opened files of specified process */
	if (snprintf(path, PATH_MAX, "/proc/%d/fd", pid) < 0) {
		CTRLD_LOG("!snprintf");
		return -1;
	}

	int ret;

	/* open dir with all opened files */
	DIR *d = opendir(path);
	if (!d) {
		CTRLD_LOG("!%s", path);
		ret = -1;
		goto out_dir;
	}

	/* read all directory entries */
	struct dirent *dent;
	while ((dent = readdir(d)) != NULL) {
		/* create a full path to file */
		if (snprintf(path, PATH_MAX,
			"/proc/%d/fd/%s", pid, dent->d_name) < 0) {
			CTRLD_LOG("!snprintf");
			ret = -1;
			goto out_dir;
		}

		/* read symbolic link */
		ssize_t sret = readlink(path, link, PATH_MAX - 1);
		if (sret <= 0)
			continue;
		link[sret] = '\0';

		/* check if this is a socket, read inode number if so */
		unsigned long inode;
		if (sscanf(link, "socket:[%lu]", &inode) != 1)
			continue;

		/* add inode to a list */
		struct inode_item *inode_item = malloc(sizeof(*inode_item));
		if (!inode_item) {
			CTRLD_LOG("!malloc inode item");
			exit(1);
		}

		inode_item->inode = inode;
		LIST_INSERT_HEAD(&inodes->head, inode_item, next);

	}

	ret = 0;
out_dir:
	closedir(d);
	return ret;
}

/*
 * clear_inodes -- clear list of inodes
 */
static void
clear_inodes(struct inodes *inodes)
{
	while (!LIST_EMPTY(&inodes->head)) {
		struct inode_item *inode_item = LIST_FIRST(&inodes->head);
		LIST_REMOVE(inode_item, next);
		free(inode_item);
	}
}

/*
 * has_port -- check if process has the specified tcp port opened
 */
static int
has_port(pid_t pid, unsigned short port)
{
	struct inodes inodes;
	memset(&inodes, 0, sizeof(inodes));

	int ret = get_inodes(pid, &inodes);
	if (ret < 0)
		return -1;

	if (!LIST_EMPTY(&inodes.head)) {
		ret = has_port_inode(port, &inodes);
		clear_inodes(&inodes);
	}

	return ret;
}

/*
 * do_wait_port -- wait until process opens a specified tcp port
 */
static int
do_wait_port(char *pid_file, unsigned short port)
{
	FILE *fh = os_fopen(pid_file, "r");
	if (!fh) {
		CTRLD_LOG("!%s", pid_file);
		return 1;
	}

	int ret;

	pid_t pid;
	char r;
	int n = fscanf(fh, "%d%c%d", &pid, &r, &ret);
	if (n < 0) {
		CTRLD_LOG("!fscanf");
		ret = 1;
		goto err;
	}

	if (n == 2 || (n == 3 && r != 'r')) {
		CTRLD_LOG("invalid format of PID file");
		ret = 1;
		goto err;
	}

	if (n == 3) {
		CTRLD_LOG("process already terminated");
		ret = 1;
		goto err;
	}

	int hp;
	do {
		hp = has_port(pid, port);
		if (hp < 0) {
			ret = 1;
			goto err;
		}
	} while (!hp);

	return 0;
err:
	fclose(fh);
	return -1;
}
#endif	/* __FreeBSD__ wait_port support */

/*
 * convert_signal_name -- convert a signal name to a signal number
 */
static int
convert_signal_name(const char *signal_name)
{
	for (int sig = SIGHUP; sig <= SIGNALMAX; sig++)
		if (strcmp(signal_name, signal2str[sig]) == 0)
			return sig;
	return -1;
}

/*
 * log_run -- print run command with arguments
 */
static void
log_run(const char *pid_file, char *cmd, char *argv[])
{
	char buff[BUFF_SIZE];
	buff[0] = '\0';
	size_t cnt = 0;
	size_t i = 0;
	char *arg = argv[0];
	while (arg) {
		ssize_t ret = snprintf(&buff[cnt], BUFF_SIZE - cnt,
				" %s", arg);
		if (ret < 0) {
			CTRLD_LOG("!snprintf");
			exit(EXIT_FAILURE);
		}

		cnt += (size_t)ret;

		i++;
		arg = argv[i];
	}

	CTRLD_LOG("run %s%s", pid_file, buff);
}

/*
 * convert_timeout -- convert a floating point number with an optional suffix
 *                    to unsigned integer: 's' for seconds (the default),
 *                    'm' for minutes, 'h' for hours or 'd' for days.
 */
static unsigned
convert_timeout(char *str)
{
	char *endptr;
	float ftimeout = strtof(str, &endptr);
	switch (*endptr) {
	case 'm':
		ftimeout *= S_MINUTE;
		break;
	case 'h':
		ftimeout *= S_HOUR;
		break;
	case 'd':
		ftimeout *= S_DAY;
		break;
	}
	return (unsigned)ftimeout;
}

int
main(int argc, char *argv[])
{
	if (argc < 3)
		usage();

	int ret = 0;
	char *pid_file = argv[1];
	char *cmd = argv[2];

	char buff[BUFF_SIZE];
	if (snprintf(buff, BUFF_SIZE, "%s.%s.%s.log",
			pid_file, cmd, APP_NAME) < 0) {
		perror("snprintf");
		return -1;
	}

	log_fh = os_fopen(buff, "a");
	if (!log_fh) {
		perror(buff);
		return -1;
	}

	if (strcmp(cmd, "exe") == 0) {
		if (argc < 4)
			usage();

		char *command = argv[3];
		char **nargv = alloc_argv((unsigned)argc, argv, 3);
		if (!nargv) {
			CTRLD_LOG("!get_argv");
			return 1;
		}

		log_run(pid_file, command, nargv);
		ret = do_run_or_exe(pid_file, command, nargv, 0 /* timeout */);

		free(nargv);
	} else if (strcmp(cmd, "run") == 0) {
		if (argc < 5)
			usage();

		unsigned timeout = convert_timeout(argv[3]);
		char *command = argv[4];
		char **nargv = alloc_argv((unsigned)argc, argv, 4);
		if (!nargv) {
			CTRLD_LOG("!get_argv");
			return 1;
		}

		log_run(pid_file, command, nargv);
		ret = do_run_or_exe(pid_file, command, nargv, timeout);

		free(nargv);
	} else if (strcmp(cmd, "wait") == 0) {
		if (argc != 3 && argc != 4)
			usage();

		int timeout = -1;
		if (argc == 4)
			timeout = atoi(argv[3]);

		CTRLD_LOG("wait %s %d", pid_file, timeout);
		ret = do_wait(pid_file, timeout);
	} else if (strcmp(cmd, "kill") == 0) {
		if (argc != 4)
			usage();

		int signo = atoi(argv[3]);
		if (signo == 0) {
			signo = convert_signal_name(argv[3]);
			if (signo == -1) {
				CTRLD_LOG("Invalid signal name or number"
						" (%s)", argv[3]);
				return 1;
			}
		}

		CTRLD_LOG("kill %s %s", pid_file, argv[3]);
		ret = do_kill(pid_file, signo);
#ifndef __FreeBSD__
	} else if (strcmp(cmd, "wait_port") == 0) {
		if (argc != 4)
			usage();

		unsigned short port = (unsigned short)atoi(argv[3]);

		CTRLD_LOG("wait_port %s %u", pid_file, port);
		ret = do_wait_port(pid_file, port);
#endif
	} else {
		usage();
	}

	return ret;
}