about summary refs log tree commit diff
path: root/nq.c
blob: 511728740cb156cebc6721a1b98808dcc9b33cbf (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
/*
 * nq CMD... - run CMD... in background and in order, saving output to ,* files
 *
 * - requires POSIX.1-2008
 * - enforcing order works like this:
 *   - every job has a flock(2)ed 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,
 * Christian Neukirchen <chneukirchen@gmail.com>
 * has waived all copyright and related or neighboring rights to this work.
 * http://creativecommons.org/publicdomain/zero/1.0/
*/

#define _POSIX_C_SOURCE 200809L

#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 <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

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

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

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[])
{
	int dirfd, lockfd;
	int pipefd[2];
	char lockfile[32];
	pid_t child;
	struct timeval started;
	struct dirent *ent;

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

	if (argc <= 1) {
		swrite(2, "usage: nq CMD...\n");
		exit(1);
	}

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

	dirfd = open(path, O_RDONLY);
	if (dirfd < 0) {
		perror("dir open");
		exit(111);
	}

	pipe(pipefd);

	/* 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.  */
		sprintf(lockfile, ",%011lx.%d", ms, child);
		dprintf(1, "%s\n", lockfile);
		close(0);
		close(1);

		/* 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.  */
	sprintf(lockfile, ".,%011lx.%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);

	write_execline(lockfd, argc, argv);

	DIR *dir = fdopendir(dirfd);
	if (!dir) {
		perror("fdopendir");
		exit(111);
	}

again:
	while ((ent = readdir(dir))) {
		if (ent->d_name[0] == ',' &&
		    strcmp(ent->d_name, lockfile+1) < 0) {
			int f = openat(dirfd, ent->d_name, O_RDWR);
    
			if (flock(f, LOCK_EX | LOCK_NB) == -1 &&
			    errno == EWOULDBLOCK) {
				flock(f, LOCK_EX);   /* sit it out.  */

				close(f);
				rewinddir(dir);
				goto again;
			}
    
			fchmod(f, 0600);
			close(f);
		}
	}

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

	/* ready to run.  */

	swrite(lockfd, "\n\n");
	fchmod(lockfd, 0700);
  
	dup2(lockfd, 2);
	dup2(lockfd, 1);
	close(lockfd);

	execvp(argv[1], argv+1);

	perror("execvp");
	return 222;
}