File: postpone.c

package info (click to toggle)
postpone 0.2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 68 kB
  • sloc: ansic: 315; makefile: 29
file content (406 lines) | stat: -rw-r--r-- 9,923 bytes parent folder | download
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
/*
 * Postpone a command if a lockfile exists, also avoid running multiple times.
 *
 * Copyright (C) 2007, 2011  Christoph Berg
 *
 * Based on code from:
 * Debian menu system -- update-menus
 * update-menus/update-menus.cc
 *
 * Copyright (C) 1996-2003  Joost Witteveen
 * Copyright (C) 2002-2004  Bill Allombert and Morten Brix Pedersen
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

#define _GNU_SOURCE

#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <libintl.h>
#include <locale.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>


#define DPKG_LOCKFILE "/var/lib/dpkg/lock"
#define DEBIAN_EXTRA_LOCKFILE "/var/lib/dpkg/postpone.lock"
#define MAXLOCKS 32
#define PACKAGE "postpone"
#define VERSION "0.1"
#define LOCALEDIR "/usr/share/locale"
#define _(x) (gettext (x))
#define perror(x) print (stderr, "%s: %s", (x), strerror(errno))

static int foreground = 0;
static int verbose = 0;
static char *postpone_lock = NULL;
static char *waitlist[MAXLOCKS];
static int n_waits = 0;
static char *extra_lock = NULL;
static char *output = NULL;
static int redirect_always = 0;
static int backgrounded = 0;

static void
print (FILE *f, const char *format, ...)
{
    static int opened = 0;
    va_list ap;
    va_start (ap, format);

    if (backgrounded) {
	if (!opened) {
	    openlog("postpone", LOG_PID, LOG_DAEMON);
	    opened = 1;
	}
	vsyslog (LOG_INFO, format, ap);
    } else {
	vfprintf (f, format, ap);
    }

    va_end (ap);
}

/* Try to create a lock file for this postpone task */
static int
get_lock (char *fname)
{
    int fd;

    if ((fd = open (fname, O_WRONLY|O_CREAT, 00644)) == -1) {
	print (stderr, _("open %s: %s\n"), fname, strerror (errno));
	exit (1);
    }

    if (flock (fd, LOCK_EX|LOCK_NB) == -1) {
	if (errno != EWOULDBLOCK && errno != EAGAIN) {
	    print (stderr, _("flock %s: %s\n"), fname, strerror (errno));
	    exit (1);
	}
	close (fd);
	return -1;
    }

    char buf[10];
    snprintf (buf, 10, "%d\n", getpid());
    if (write(fd, buf, strlen(buf)) < 1) {
	print (stderr, _("write %s: %s\n"), fname, strerror (errno));
	close (fd);
	return -1;
    }

    if (verbose > 1)
	print (stdout, _("Got lock on %s.\n"), fname);
    return fd; /* beware: might be 0 */
}

/* Try to remove postpone lock */
static void
remove_lock (char *fname)
{
    if (unlink (fname))
	perror (fname);
}

/* Check whether dpkg is locked
 * return 1 if DPKG_LOCKFILE is locked and we should wait
 * return 0 if we don't need to wait
 * when in doubt return 0 to avoid deadlocks.
 */
static int
wait_for_file (char *fname)
{
    int fd;
    struct flock fl;

    fl.l_type = F_WRLCK;
    fl.l_whence = SEEK_SET;
    fl.l_start = 0;
    fl.l_len = 0;
    fd = open(fname, O_RDWR|O_TRUNC, 0660);
    if (fd == -1) {
	/* Probably /var/lib/dpkg does not exist.
	 * Most probably dpkg is not running.
	 */
	if (verbose > 1)
	    print (stdout, _("%s does not exist. Good.\n"), fname);
	return 0;
    }
    if (fcntl(fd, F_GETLK, &fl) == -1)
    {
	/* Probably /var/lib/dpkg filesystem does not support
	 * locks.
	 */
	close (fd);
	if (verbose > 1)
	    print (stdout, _("Error while locking %s. Assuming this is a good sign.\n"), fname);
	return 0;
    }
    close (fd);

    if (verbose > 1) {
	if (fl.l_type == F_UNLCK)
	    print (stdout, _("%s is not locked. Good.\n"), fname);
	else
	    print (stdout, _("%s is locked. Waiting.\n"), fname);
    }
    return fl.l_type != F_UNLCK;
}

static int
wait_for_locks ()
{
    int i;
    for (i = 0; i < n_waits; i++) {
	int ret = wait_for_file (waitlist[i]);
	if (ret != 0) {
	    return 1;
	}
    }

    if (extra_lock) {
	int ret = get_lock (extra_lock);
	if (ret == -1) {
	    if (verbose > 1)
		print (stdout, _("Extra lock %s is not available. Waiting.\n"), extra_lock);
	    return 1;
	}
    }

    return 0; /* all locks available */
}

static int
run_command (char **argv, int foreground)
{
    int pid, status;
    int redirect = output && (!foreground || redirect_always);

    if ((pid = fork ()) == 0) { /* child */
	backgrounded = 1;

	if (redirect) {
	    int fd;
	    if (strlen (output) < 6 || strncmp (output + strlen (output) - 6, "XXXXXX", 6))
		fd = open (output, O_RDWR|O_CREAT|O_TRUNC, 0600);
	    else
		fd = mkstemp (output);
	    if (fd == -1) {
		perror (output);
	    }
	    dup2 (fd, 1);
	    dup2 (fd, 2);
	}

	if (verbose > 1)
	    print (stdout, _("Running %s\n"), argv[0]);

	execvp (argv[0], argv);
	perror (argv[0]);
	exit (1);
    }
    /* parent */

    if (pid == -1 ) {
	if (foreground)
	    perror ("fork");
	exit (1);
    }

    waitpid (pid, &status, 0);
    if (postpone_lock)
	remove_lock (postpone_lock);
    if (extra_lock)
	remove_lock (extra_lock);

    if (verbose > 1)
	print (stdout, _("Child %d exited\n"), pid);

    if (WIFEXITED (status))
	if (redirect && WEXITSTATUS (status) == 0)
	    unlink (output);
	return WEXITSTATUS (status);

    return 1;
}

static void
usage (FILE *f, int i)
{
    fprintf(f, _("Postpone schedules a command to be executed later when a lockfile disappears\n"
		 "Usage: postpone [-dfv] [-wlLoO FILE] command args...\n"
		 "-w --wait FILE [...]  wait for fcntl lock on FILE before running command\n"
		 "-l --lock FILE        create lockfile FILE, exit if it exists\n"
		 "                        use to avoid scheduling a command several times\n"
		 "-L --extra-lock FILE  extra lock to serialize different postponed commands\n"
		 "-d --debian           equivalent to --wait " DPKG_LOCKFILE "\n"
		 "                        --extra-lock " DEBIAN_EXTRA_LOCKFILE "\n"
		 "-o --output FILE      redirect stdout/stderr to FILE when in background\n"
		 "-O --all-output FILE  unconditionally redirect stdout/stderr to FILE\n"
		 "-f --foreground       do not detach while waiting for locks\n"
		 "-v --verbose          verbose operation, repeat for debugging output\n"
		 "   --help             print this help and exit\n"
		 "   --version          print version information and exit\n"
		 "   --version-string   print version string and exit\n"
		 ));
    exit (i);
}

static void
version (FILE *f, int i)
{
    fprintf(f, _("Postpone %s - schedule a task to be executed later when a lockfile disappears\n"
		 "Copyright (C) 1996-2003  Joost Witteveen\n"
		 "Copyright (C) 2002-2004  Bill Allombert and Morten Brix Pedersen\n"
		 "Copyright (C) 2007  Christoph Berg\n"), VERSION);
    exit (i);
}

static struct option long_options[] = {
  { "debian", no_argument, NULL, 'd' },
  { "foreground", no_argument, NULL, 'f' },
  { "help", no_argument, NULL, 'h' },
  { "lock", required_argument, NULL, 'l' },
  { "extra-lock", required_argument, NULL, 'L' },
  { "output", required_argument, NULL, 'o' },
  { "all-output", required_argument, NULL, 'O' },
  { "verbose", no_argument, NULL, 'v' },
  { "version", no_argument, NULL, 'V'},
  { "wait", required_argument, NULL, 'w' },
  { "version-string", no_argument, NULL, 'X'},
  { NULL, 0, NULL, 0 } };

/* Parse command line parameters */
static void
parse_params(int argc, char **argv)
{
    while(1) {
	int c = getopt_long (argc, argv, "+dfl:L:o:O:vw:", long_options, NULL);
	if (c == -1)
	    break;
	switch(c) {
	    case 'd':
		if (n_waits < MAXLOCKS)
		    waitlist[n_waits++] = DPKG_LOCKFILE;
		extra_lock = DEBIAN_EXTRA_LOCKFILE;
		break;
	    case 'f':
		foreground = 1;
		break;
	    case 'h':
		usage (stdout, 0);
	    case 'l':
		postpone_lock = strdup (optarg);
		break;
	    case 'L':
		extra_lock = strdup (optarg);
		break;
	    case 'O':
		redirect_always = 1;
		/* FALLTHROUGH */
	    case 'o':
		output = strdup (optarg);
		break;
	    case 'v':
		verbose++;
		break;
	    case 'V':
		version (stdout, 0);
	    case 'w':
		if (n_waits < MAXLOCKS)
		    waitlist[n_waits++] = strdup (optarg);
		break;
	    case 'X':
		puts (VERSION);
		exit (0);
	    /* ignore unknown options for easier compatibility with future versions */
	}
    }
}

int main (int argc, char **argv)
{
    int lock = -1, pid, i;

    setlocale (LC_ALL, "");
    bindtextdomain (PACKAGE, LOCALEDIR);
    textdomain (PACKAGE);

    parse_params (argc, argv);

    if (optind >= argc) {
	usage (stderr, 1);
    }

    if (postpone_lock)
	if ((lock = get_lock (postpone_lock)) == -1) {
	    if (verbose)
		print (stdout, _("%s is already running in background.\n"), argv[optind]);
	    exit (0);
	}

    if (wait_for_locks () == 0) {
	if (verbose > 1)
	    print (stdout, _("No locks to wait for, running in foreground now.\n"));
	return run_command (argv + optind, 1);
    }

    if (verbose > 1) {
	print (stdout, _("Waiting for lock on"));
	for (i = 0; i < n_waits; i++)
	    print (stdout, " %s", waitlist[i]);
	if (extra_lock)
	    print (stdout, " %s", extra_lock);
	print (stdout, ".\n");
    }

    if (!foreground) {
	if ((pid = fork ()) > 0) { /* parent */
	    if (verbose)
		print (stdout, _("Running %s in background.\n"), argv[optind]);
	    exit (0);
	} else if (pid == -1) {
	    if (postpone_lock)
		remove_lock (postpone_lock);
	    perror ("fork");
	    exit (1);
	}
	/* child */

	backgrounded = 1;

	/* Close all fds except the lock fd for daemon mode */
	for (i = 0; i < 32; i++) {
	    if (i != lock)
		close (i);
	}
    }

    /* wait for dpkg/other locks */
    do {
	sleep (2);
    } while (wait_for_locks ());

    return run_command (argv + optind, foreground);
}

/* vim:sw=4:
 */