summary refs log tree commit diff
path: root/nq.c
blob: fd51d5bd76a8502076165ecbe177bea9ca05b8b6 (plain) (blame)
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
/*
 * nq CMD... - run CMD... in background and in order, saving output
 * -w ...  wait for all jobs/listed jobs queued so far to finish
 * -t ...  exit 0 if no (listed) job needs waiting
 * -q      quiet, do not output job id
 *
 * - requires POSIX.1-2008 and having flock(2)
 * - enforcing order works like this:
 *   - every job has a flock(2)ed output file ala ",TIMESTAMP.PID"
 *   - every job starts only after all earlier flock(2)ed files finished
 *   - the lock is released when job terminates
 *   - no sub-second file system time stamps are required, jobs are started
 *     with millisecond precision
 * - we try hard to make the currently running ,* file have +x bit
 * - you can re-queue jobs using "sh ,jobid"
 *
 * To the extent possible under law, Leah Neukirchen <leah@vuxu.org>
 * has waived all copyright and related or neighboring rights to this work.
 * http://creativecommons.org/publicdomain/zero/1.0/
*/

/* for FreeBSD.  */
#define _WITH_DPRINTF

#if defined(__sun) && defined(__SVR4) && !defined(HAVE_DPRINTF)
#define NEED_DPRINTF
#endif

#include <sys/file.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>

#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#ifdef NEED_DPRINTF
#include <stdarg.h>
static int
dprintf(int fd, const char *fmt, ...)
{
	char buf[128];  // good enough for usage in nq
	va_list ap;
	int r;

	va_start(ap, fmt);
	r = vsnprintf(buf, sizeof buf, fmt, ap);
	va_end(ap);
	if (r >= 0 && r < sizeof buf)
		return write(fd, buf, r);
	return -1;
}
#endif

static void
swrite(int fd, char *str)
{
	size_t l = strlen(str);

	if (write(fd, str, l) != l) {
		perror("write");
		exit(222);
	}
}

static void
write_execline(int fd, int argc, char *argv[])
{
	int i;
	char *s;

	swrite(fd, "exec");

	for (i = 0; i < argc; i++) {
		swrite(fd, " '");
		for (s = argv[i]; *s; s++) {
			if (*s == '\'')
				swrite(fd, "'\\''");
			else
				write(fd, s, 1);
		}
		swrite(fd, "'");
	}
}

int
main(int argc, char *argv[])
{
	int64_t ms;
	int dirfd = 0, lockfd = 0, opt = 0, qflag = 0, tflag = 0, wflag = 0;
	int pipefd[2];
	char lockfile[64];
	pid_t child;
	struct timeval started;
	struct dirent *ent;
	DIR *dir;

	/* timestamp is milliseconds since epoch.  */
	gettimeofday(&started, NULL);
	ms = (int64_t)started.tv_sec*1000 + started.tv_usec/1000;

	while ((opt = getopt(argc, argv, "+hqtw")) != -1) {
		switch (opt) {
		case 'w':
			wflag = 1;
			break;
		case 't':
			tflag = 1;
			break;
                case 'q':
			qflag = 1;
			break;
		case 'h':
		default:
			goto usage;
		}
	}

	if (argc <= 1) {
usage:
		swrite(2, "usage: nq [-q] [-w ... | -t ... | CMD...]\n");
		exit(1);
	}

	char *path = getenv("NQDIR");
	if (!path)
		path = ".";

	if (mkdir(path, 0777) < 0) {
		if (errno != EEXIST) {
			perror("mkdir");
			exit(111);
		}
	}

#ifdef O_DIRECTORY
	dirfd = open(path, O_RDONLY | O_DIRECTORY);
#else
	dirfd = open(path, O_RDONLY);
#endif
	if (dirfd < 0) {
		perror("dir open");
		exit(111);
	}

	if (tflag || wflag) {
		snprintf(lockfile, sizeof lockfile,
		    ".,%011" PRIx64 ".%d", ms, getpid());
		goto wait;
	}

	if (pipe(pipefd) < 0) {
		perror("pipe");
		exit(111);
	};

	/* first fork, parent exits to run in background.  */
	child = fork();
	if (child == -1) {
		perror("fork");
		exit(111);
	}
	else if (child > 0) {
		char c;

		/* wait until child has backgrounded.  */
		close(pipefd[1]);
		read(pipefd[0], &c, 1);

		exit(0);
	}

	close(pipefd[0]);

	/* second fork, child later execs the job, parent collects status.  */
	child = fork();
	if (child == -1) {
		perror("fork");
		exit(111);
	}
	else if (child > 0) {
		int status;

		/* output expected lockfile name.  */
		snprintf(lockfile, sizeof lockfile,
		    ",%011" PRIx64 ".%d", ms, child);
		if (!qflag)
			dprintf(1, "%s\n", lockfile);
		close(0);
		close(1);
		close(2);

		/* signal parent to exit.  */
		close(pipefd[1]);

		wait(&status);

		lockfd = openat(dirfd, lockfile, O_RDWR | O_APPEND);
		if (lockfd < 0) {
			perror("open");
			exit(222);
		}

		fchmod(lockfd, 0600);
		if (WIFEXITED(status))
			dprintf(lockfd, "\n[exited with status %d.]\n",
			    WEXITSTATUS(status));
		else
			dprintf(lockfd, "\n[killed by signal %d.]\n",
			    WTERMSIG(status));

		exit(0);
	}

	close(pipefd[1]);

	/* create and lock lockfile.  since this cannot be done in one step,
	   use a different filename first.  */
	snprintf(lockfile, sizeof lockfile,
	    ".,%011" PRIx64 ".%d", ms, getpid());
	lockfd = openat(dirfd, lockfile,
	    O_CREAT | O_EXCL | O_RDWR | O_APPEND, 0600);
	if (lockfd < 0) {
		perror("open");
		exit(222);
	}
	if (flock(lockfd, LOCK_EX) < 0) {
		perror("flock");
		exit(222);
	}

	/* drop leading '.' */
	renameat(dirfd, lockfile, dirfd, lockfile+1);

	/* block until rename is committed */
	fsync(dirfd);

	write_execline(lockfd, argc, argv);

	if (dup2(lockfd, 2) < 0 ||
	    dup2(lockfd, 1) < 0) {
		perror("dup2");
		exit(222);
	}

wait:
	if ((tflag || wflag) && argc - optind > 0) {
		/* wait for files passed as command line arguments.  */

		int i;
		for (i = optind; i < argc; i++) {
			int fd;

			if (strchr(argv[i], '/'))
				fd = open(argv[i], O_RDWR);
			else
				fd = openat(dirfd, argv[i], O_RDWR);
			if (fd < 0)
				continue;

			if (flock(fd, LOCK_EX | LOCK_NB) == -1 &&
			    errno == EWOULDBLOCK) {
				if (tflag)
					exit(1);
				flock(fd, LOCK_EX);   /* sit it out.  */
			}

			fchmod(fd, 0600);
			close(fd);
		}
	} else {
		dir = fdopendir(dirfd);
		if (!dir) {
			perror("fdopendir");
			exit(111);
		}

again:
		while ((ent = readdir(dir))) {
			/* wait for all ,* files.  */

			if (ent->d_name[0] == ',' &&
			    strcmp(ent->d_name, lockfile+1) < 0) {
				int fd;

				fd = openat(dirfd, ent->d_name, O_RDWR);
				if (fd < 0)
					continue;

				if (flock(fd, LOCK_EX | LOCK_NB) == -1 &&
				    errno == EWOULDBLOCK) {
					if (tflag)
						exit(1);
					flock(fd, LOCK_EX);   /* sit it out.  */

					close(fd);
					rewinddir(dir);
					goto again;
				}

				fchmod(fd, 0600);
				close(fd);
			}
		}

		closedir(dir);		/* closes dirfd too.  */
	}

	if (tflag || wflag)
		exit(0);

	/* ready to run.  */

	swrite(lockfd, "\n\n");
	fchmod(lockfd, 0700);

	close(lockfd);

	setenv("NQJOBID", lockfile+1, 1);
	setsid();
	execvp(argv[optind], argv+optind);

	perror("execvp");
	return 222;
}