0
|
1 /*
|
|
2 lock.c
|
|
3
|
|
4 $Id: lock.c 3 2000-01-04 11:35:42Z enz $
|
|
5 */
|
|
6
|
|
7 #include "lock.h"
|
|
8 #include <errno.h>
|
|
9 #include <ctype.h>
|
|
10 #include <sys/types.h>
|
|
11 #include <sys/stat.h>
|
|
12 #include <fcntl.h>
|
|
13 #include <time.h>
|
|
14 #include <unistd.h>
|
|
15 #include "config.h"
|
|
16 #include "log.h"
|
|
17 #include "database.h"
|
|
18 #include "group.h"
|
|
19 #include "request.h"
|
|
20
|
|
21 struct Lock
|
|
22 {
|
|
23 int lockFd;
|
|
24 Str lockFile;
|
|
25 } lock = { -1, "" };
|
|
26
|
|
27
|
|
28 #ifdef DEBUG
|
|
29 static Bool
|
|
30 testLock( void )
|
|
31 {
|
|
32 return ( lock.lockFd != -1 );
|
|
33 }
|
|
34 #endif
|
|
35
|
|
36 static Bool
|
|
37 waitLock( void )
|
|
38 {
|
|
39 int fd;
|
|
40 struct flock l;
|
|
41
|
|
42 ASSERT( ! testLock() );
|
|
43 Log_dbg( "Waiting for lock ..." );
|
|
44 snprintf( lock.lockFile, MAXCHAR, "%s/lock/global", Cfg_spoolDir() );
|
|
45 if ( ( fd = open( lock.lockFile, O_WRONLY | O_CREAT, 0644 ) ) < 0 )
|
|
46 {
|
|
47 Log_err( "Cannot open %s (%s)", lock.lockFile, strerror( errno ) );
|
|
48 return FALSE;
|
|
49 }
|
|
50 l.l_type = F_WRLCK;
|
|
51 l.l_start = 0;
|
|
52 l.l_whence = SEEK_SET;
|
|
53 l.l_len = 0;
|
|
54 if ( fcntl( fd, F_SETLKW, &l ) < 0 )
|
|
55 {
|
|
56 Log_err( "Cannot lock %s: %s", lock.lockFile, strerror( errno ) );
|
|
57 return FALSE;
|
|
58 }
|
|
59 lock.lockFd = fd;
|
|
60 Log_dbg( "Lock successful" );
|
|
61 return TRUE;
|
|
62 }
|
|
63
|
|
64 static void
|
|
65 releaseLock( void )
|
|
66 {
|
|
67 struct flock l;
|
|
68
|
|
69 ASSERT( testLock() );
|
|
70 l.l_type = F_UNLCK;
|
|
71 l.l_start = 0;
|
|
72 l.l_whence = SEEK_SET;
|
|
73 l.l_len = 0;
|
|
74 if ( fcntl( lock.lockFd, F_SETLK, &l ) < 0 )
|
|
75 Log_err( "Cannot release %s: %s", lock.lockFile,
|
|
76 strerror( errno ) );
|
|
77 close( lock.lockFd );
|
|
78 lock.lockFd = -1;
|
|
79 Log_dbg( "Releasing lock" );
|
|
80 }
|
|
81
|
|
82
|
|
83 /* Open all databases and set global lock. */
|
|
84 Bool
|
|
85 Lock_openDatabases( void )
|
|
86 {
|
|
87 if ( ! waitLock() )
|
|
88 {
|
|
89 Log_err( "Could not get write lock" );
|
|
90 return FALSE;
|
|
91 }
|
|
92 if ( ! Db_open() )
|
|
93 {
|
|
94 Log_err( "Could not open database" );
|
|
95 releaseLock();
|
|
96 return FALSE;
|
|
97 }
|
|
98 if ( ! Grp_open() )
|
|
99 {
|
|
100 Log_err( "Could not open groupinfo" );
|
|
101 Db_close();
|
|
102 releaseLock();
|
|
103 return FALSE;
|
|
104 }
|
|
105 if ( ! Req_open() )
|
|
106 {
|
|
107 Log_err( "Could not initialize request database" );
|
|
108 Grp_close();
|
|
109 Db_close();
|
|
110 releaseLock();
|
|
111 return FALSE;
|
|
112 }
|
|
113
|
|
114 return TRUE;
|
|
115 }
|
|
116
|
|
117
|
|
118 /* Close all databases and release global lock. */
|
|
119 void
|
|
120 Lock_closeDatabases( void )
|
|
121 {
|
|
122 Grp_close();
|
|
123 Db_close();
|
|
124 Req_close();
|
|
125 releaseLock();
|
|
126 }
|