2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
10 #include <afsconfig.h>
11 #include <afs/param.h>
19 #include <afs/afsutil.h>
20 #include <afs/cellconfig.h>
22 #define UBIK_INTERNALS
27 * This module is responsible for determining when the system has
28 * recovered to the point that it can handle new transactions. It
29 * replays logs, polls to determine the current dbase after a crash,
30 * and distributes the new database to the others.
32 * The sync site associates a version number with each database. It
33 * broadcasts the version associated with its current dbase in every
34 * one of its beacon messages. When the sync site send a dbase to a
35 * server, it also sends the db's version. A non-sync site server can
36 * tell if it has the right dbase version by simply comparing the
37 * version from the beacon message \p uvote_dbVersion with the version
38 * associated with the database \p ubik_dbase->version. The sync site
39 * itself simply has one counter to keep track of all of this (again
40 * \p ubik_dbase->version).
42 * sync site: routine called when the sync site loses its quorum; this
43 * procedure is called "up" from the beacon package. It resyncs the
44 * dbase and nudges the recovery daemon to try to propagate out the
45 * changes. It also resets the recovery daemon's state, since
46 * recovery must potentially find a new dbase to propagate out. This
47 * routine should not do anything with variables used by non-sync site
52 * if this flag is set, then ubik will use only the primary address
53 * (the address specified in the CellServDB) to contact other
54 * ubik servers. Ubik recovery will not try opening connections
55 * to the alternate interface addresses.
57 int ubikPrimaryAddrOnly;
60 urecovery_ResetState(void)
63 #if !defined(AFS_PTHREAD_ENV)
64 /* No corresponding LWP_WaitProcess found anywhere for this -- klm */
65 LWP_NoYieldSignal(&urecovery_state);
73 * routine called when a non-sync site server goes down; restarts recovery
74 * process to send missing server the new db when it comes back up for
75 * non-sync site servers.
77 * \note This routine should not do anything with variables used by non-sync site servers.
80 urecovery_LostServer(struct ubik_server *ts)
82 ubeacon_ReinitServer(ts);
83 #if !defined(AFS_PTHREAD_ENV)
84 /* No corresponding LWP_WaitProcess found anywhere for this -- klm */
85 LWP_NoYieldSignal(&urecovery_state);
91 * return true iff we have a current database (called by both sync
92 * sites and non-sync sites) How do we determine this? If we're the
93 * sync site, we wait until recovery has finished fetching and
94 * re-labelling its dbase (it may still be trying to propagate it out
95 * to everyone else; that's THEIR problem). If we're not the sync
96 * site, then we must have a dbase labelled with the right version,
97 * and we must have a currently-good sync site.
100 urecovery_AllBetter(struct ubik_dbase *adbase, int areadAny)
104 ubik_dprint_25("allbetter checking\n");
109 if (ubik_dbase->version.epoch > 1)
110 rcode = 1; /* Happy with any good version of database */
113 /* Check if we're sync site and we've got the right data */
114 else if (ubeacon_AmSyncSite() && (urecovery_state & UBIK_RECHAVEDB)) {
118 /* next, check if we're aux site, and we've ever been sent the
119 * right data (note that if a dbase update fails, we won't think
120 * that the sync site is still the sync site, 'cause it won't talk
121 * to us until a timeout period has gone by. When we recover, we
122 * leave this clear until we get a new dbase */
123 else if (uvote_HaveSyncAndVersion(ubik_dbase->version)) {
127 ubik_dprint_25("allbetter: returning %d\n", rcode);
132 * \brief abort all transactions on this database
135 urecovery_AbortAll(struct ubik_dbase *adbase)
137 struct ubik_trans *tt;
138 for (tt = adbase->activeTrans; tt; tt = tt->next) {
145 * \brief this routine aborts the current remote transaction, if any, if the tid is wrong
148 urecovery_CheckTid(struct ubik_tid *atid, int abortalways)
150 if (ubik_currentTrans) {
151 /* there is remote write trans, see if we match, see if this
152 * is a new transaction */
153 if (atid->epoch != ubik_currentTrans->tid.epoch
154 || atid->counter > ubik_currentTrans->tid.counter || abortalways) {
155 /* don't match, abort it */
156 /* If the thread is not waiting for lock - ok to end it */
157 if (ubik_currentTrans->locktype != LOCKWAIT) {
158 udisk_end(ubik_currentTrans);
160 ubik_currentTrans = (struct ubik_trans *)0;
169 * log format is defined here, and implicitly in disk.c
171 * 4 byte opcode, followed by parameters, each 4 bytes long. All integers
172 * are in logged in network standard byte order, in case we want to move logs
173 * from machine-to-machine someday.
175 * Begin transaction: opcode \n
176 * Commit transaction: opcode, version (8 bytes) \n
177 * Truncate file: opcode, file number, length \n
178 * Abort transaction: opcode \n
179 * Write data: opcode, file, position, length, <length> data bytes \n
181 * A very simple routine, it just replays the log. Note that this is a new-value only log, which
182 * implies that no uncommitted data is written to the dbase: one writes data to the log, including
183 * the commit record, then we allow data to be written through to the dbase. In our particular
184 * implementation, once a transaction is done, we write out the pages to the database, so that
185 * our buffer package doesn't have to know about stable and uncommitted data in the memory buffers:
186 * any changed data while there is an uncommitted write transaction can be zapped during an
187 * abort and the remaining dbase on the disk is exactly the right dbase, without having to read
191 ReplayLog(struct ubik_dbase *adbase)
194 afs_int32 code, tpos;
196 afs_int32 len, thisSize, tfile, filePos;
198 afs_int32 syncFile = -1;
199 afs_int32 data[1024];
201 /* read the lock twice, once to see whether we have a transaction to deal
202 * with that committed, (theoretically, we should support more than one
203 * trans in the log at once, but not yet), and once replaying the
207 /* for now, assume that all ops in log pertain to one transaction; see if there's a commit */
210 (*adbase->read) (adbase, LOGFILE, (char *)&opcode, tpos,
212 if (code != sizeof(afs_int32))
214 opcode = ntohl(opcode);
215 if (opcode == LOGNEW) {
216 /* handle begin trans */
217 tpos += sizeof(afs_int32);
218 } else if (opcode == LOGABORT)
220 else if (opcode == LOGEND) {
223 } else if (opcode == LOGTRUNCATE) {
226 (*adbase->read) (adbase, LOGFILE, (char *)buffer, tpos,
227 2 * sizeof(afs_int32));
228 if (code != 2 * sizeof(afs_int32))
229 break; /* premature eof or io error */
230 tpos += 2 * sizeof(afs_int32);
231 } else if (opcode == LOGDATA) {
234 (*adbase->read) (adbase, LOGFILE, (char *)buffer, tpos,
235 3 * sizeof(afs_int32));
236 if (code != 3 * sizeof(afs_int32))
238 /* otherwise, skip over the data bytes, too */
239 tpos += ntohl(buffer[2]) + 3 * sizeof(afs_int32);
241 ubik_print("corrupt log opcode (%d) at position %d\n", opcode,
243 break; /* corrupt log! */
247 /* actually do the replay; log should go all the way through the commit record, since
248 * we just read it above. */
254 (*adbase->read) (adbase, LOGFILE, (char *)&opcode, tpos,
256 if (code != sizeof(afs_int32))
258 opcode = ntohl(opcode);
259 if (opcode == LOGNEW) {
260 /* handle begin trans */
261 tpos += sizeof(afs_int32);
262 } else if (opcode == LOGABORT)
263 panic("log abort\n");
264 else if (opcode == LOGEND) {
265 struct ubik_version version;
268 (*adbase->read) (adbase, LOGFILE, (char *)buffer, tpos,
269 2 * sizeof(afs_int32));
270 if (code != 2 * sizeof(afs_int32))
272 version.epoch = ntohl(buffer[0]);
273 version.counter = ntohl(buffer[1]);
274 code = (*adbase->setlabel) (adbase, 0, &version);
277 ubik_print("Successfully replayed log for interrupted "
278 "transaction; db version is now %ld.%ld\n",
279 (long) version.epoch, (long) version.counter);
281 break; /* all done now */
282 } else if (opcode == LOGTRUNCATE) {
285 (*adbase->read) (adbase, LOGFILE, (char *)buffer, tpos,
286 2 * sizeof(afs_int32));
287 if (code != 2 * sizeof(afs_int32))
288 break; /* premature eof or io error */
289 tpos += 2 * sizeof(afs_int32);
291 (*adbase->truncate) (adbase, ntohl(buffer[0]),
295 } else if (opcode == LOGDATA) {
298 (*adbase->read) (adbase, LOGFILE, (char *)buffer, tpos,
299 3 * sizeof(afs_int32));
300 if (code != 3 * sizeof(afs_int32))
302 tpos += 3 * sizeof(afs_int32);
303 /* otherwise, skip over the data bytes, too */
304 len = ntohl(buffer[2]); /* total number of bytes to copy */
305 filePos = ntohl(buffer[1]);
306 tfile = ntohl(buffer[0]);
307 /* try to minimize file syncs */
308 if (syncFile != tfile) {
310 code = (*adbase->sync) (adbase, syncFile);
318 thisSize = (len > sizeof(data) ? sizeof(data) : len);
319 /* copy sizeof(data) buffer bytes at a time */
321 (*adbase->read) (adbase, LOGFILE, (char *)data, tpos,
323 if (code != thisSize)
326 (*adbase->write) (adbase, tfile, (char *)data, filePos,
328 if (code != thisSize)
335 ubik_print("corrupt log opcode (%d) at position %d\n",
337 break; /* corrupt log! */
342 code = (*adbase->sync) (adbase, syncFile);
346 ubik_print("Log read error on pass 2\n");
351 /* now truncate the log, we're done with it */
352 code = (*adbase->truncate) (adbase, LOGFILE, 0);
357 * Called at initialization to figure out version of the dbase we really have.
359 * This routine is called after replaying the log; it reads the restored labels.
362 InitializeDB(struct ubik_dbase *adbase)
366 code = (*adbase->getlabel) (adbase, 0, &adbase->version);
368 /* try setting the label to a new value */
370 adbase->version.epoch = 1; /* value for newly-initialized db */
371 adbase->version.counter = 1;
372 code = (*adbase->setlabel) (adbase, 0, &adbase->version);
374 /* failed, try to set it back */
375 adbase->version.epoch = 0;
376 adbase->version.counter = 0;
377 (*adbase->setlabel) (adbase, 0, &adbase->version);
379 #ifdef AFS_PTHREAD_ENV
380 CV_BROADCAST(&adbase->version_cond);
382 LWP_NoYieldSignal(&adbase->version);
390 * \brief initialize the local ubik_dbase
392 * We replay the logs and then read the resulting file to figure out what version we've really got.
395 urecovery_Initialize(struct ubik_dbase *adbase)
400 code = ReplayLog(adbase);
403 code = InitializeDB(adbase);
410 * \brief Main interaction loop for the recovery manager
412 * The recovery light-weight process only runs when you're the
413 * synchronization site. It performs the following tasks, if and only
414 * if the prerequisite tasks have been performed successfully (it
415 * keeps track of which ones have been performed in its bit map,
416 * \p urecovery_state).
418 * First, it is responsible for probing that all servers are up. This
419 * is the only operation that must be performed even if this is not
420 * yet the sync site, since otherwise this site may not notice that
421 * enough other machines are running to even elect this guy to be the
424 * After that, the recovery process does nothing until the beacon and
425 * voting modules manage to get this site elected sync site.
427 * After becoming sync site, recovery first attempts to find the best
428 * database available in the network (it must do this in order to
429 * ensure finding the latest committed data). After finding the right
430 * database, it must fetch this dbase to the sync site.
432 * After fetching the dbase, it relabels it with a new version number,
433 * to ensure that everyone recognizes this dbase as the most recent
436 * One the dbase has been relabelled, this machine can start handling
437 * requests. However, the recovery module still has one more task:
438 * propagating the dbase out to everyone who is up in the network.
441 urecovery_Interact(void *dummy)
443 afs_int32 code, tcode;
444 struct ubik_server *bestServer = NULL;
445 struct ubik_server *ts;
446 int dbok, doingRPC, now;
447 afs_int32 lastProbeTime;
448 /* if we're the sync site, the best db version we've found yet */
449 static struct ubik_version bestDBVersion;
450 struct ubik_version tversion;
452 int length, tlen, offset, file, nbytes;
453 struct rx_call *rxcall;
455 struct ubik_stat ubikstat;
456 struct in_addr inAddr;
462 afs_pthread_setname_self("recovery");
464 /* otherwise, begin interaction */
468 /* Run through this loop every 4 seconds */
471 #ifdef AFS_PTHREAD_ENV
472 select(0, 0, 0, 0, &tv);
474 IOMGR_Select(0, 0, 0, 0, &tv);
477 ubik_dprint("recovery running in state %x\n", urecovery_state);
479 /* Every 30 seconds, check all the down servers and mark them
480 * as up if they respond. When a server comes up or found to
481 * not be current, then re-find the the best database and
484 if ((now = FT_ApproxTime()) > 30 + lastProbeTime) {
486 for (ts = ubik_servers, doingRPC = 0; ts; ts = ts->next) {
497 urecovery_state &= ~UBIK_RECFOUNDDB;
504 urecovery_state &= ~UBIK_RECFOUNDDB;
510 now = FT_ApproxTime();
514 /* Mark whether we are the sync site */
516 if (!ubeacon_AmSyncSite()) {
517 urecovery_state &= ~UBIK_RECSYNCSITE;
519 continue; /* nothing to do */
521 urecovery_state |= UBIK_RECSYNCSITE;
523 /* If a server has just come up or if we have not found the
524 * most current database, then go find the most current db.
526 if (!(urecovery_state & UBIK_RECFOUNDDB)) {
528 bestServer = (struct ubik_server *)0;
529 bestDBVersion.epoch = 0;
530 bestDBVersion.counter = 0;
531 for (ts = ubik_servers; ts; ts = ts->next) {
535 continue; /* don't bother with these guys */
541 code = DISK_GetVersion(ts->disk_rxcid, &ts->version);
544 /* perhaps this is the best version */
545 if (vcmp(ts->version, bestDBVersion) > 0) {
546 /* new best version */
547 bestDBVersion = ts->version;
552 /* take into consideration our version. Remember if we,
553 * the sync site, have the best version. Also note that
554 * we may need to send the best version out.
557 if (vcmp(ubik_dbase->version, bestDBVersion) >= 0) {
558 bestDBVersion = ubik_dbase->version;
559 bestServer = (struct ubik_server *)0;
560 urecovery_state |= UBIK_RECHAVEDB;
562 /* Clear the flag only when we know we have to retrieve
563 * the db. Because urecovery_AllBetter() looks at it.
565 urecovery_state &= ~UBIK_RECHAVEDB;
567 urecovery_state |= UBIK_RECFOUNDDB;
568 urecovery_state &= ~UBIK_RECSENTDB;
570 if (!(urecovery_state & UBIK_RECFOUNDDB)) {
572 continue; /* not ready */
575 /* If we, the sync site, do not have the best db version, then
576 * go and get it from the server that does.
578 if ((urecovery_state & UBIK_RECHAVEDB) || !bestServer) {
579 urecovery_state |= UBIK_RECHAVEDB;
581 /* we don't have the best version; we should fetch it. */
582 urecovery_AbortAll(ubik_dbase);
584 /* Rx code to do the Bulk fetch */
588 rxcall = rx_NewCall(bestServer->disk_rxcid);
590 ubik_print("Ubik: Synchronize database with server %s\n",
591 afs_inet_ntoa_r(bestServer->addr[0], hoststr));
594 code = StartDISK_GetFile(rxcall, file);
596 ubik_dprint("StartDiskGetFile failed=%d\n", code);
599 nbytes = rx_Read(rxcall, (char *)&length, sizeof(afs_int32));
600 length = ntohl(length);
601 if (nbytes != sizeof(afs_int32)) {
602 ubik_dprint("Rx-read length error=%d\n", code = BULK_ERROR);
607 /* give invalid label during file transit */
610 code = (*ubik_dbase->setlabel) (ubik_dbase, file, &tversion);
613 ubik_dprint("setlabel io error=%d\n", code);
616 snprintf(pbuffer, sizeof(pbuffer), "%s.DB%s%d.TMP",
617 ubik_dbase->pathName, (file<0)?"SYS":"",
618 (file<0)?-file:file);
619 fd = open(pbuffer, O_CREAT | O_RDWR | O_TRUNC, 0600);
624 code = lseek(fd, HDRSIZE, 0);
625 if (code != HDRSIZE) {
632 tlen = (length > sizeof(tbuffer) ? sizeof(tbuffer) : length);
633 #ifndef AFS_PTHREAD_ENV
637 nbytes = rx_Read(rxcall, tbuffer, tlen);
638 if (nbytes != tlen) {
639 ubik_dprint("Rx-read bulk error=%d\n", code = BULK_ERROR);
644 nbytes = write(fd, tbuffer, tlen);
646 if (nbytes != tlen) {
657 code = EndDISK_GetFile(rxcall, &tversion);
659 tcode = rx_EndCall(rxcall, code);
663 /* we got a new file, set up its header */
664 urecovery_state |= UBIK_RECHAVEDB;
666 memcpy(&ubik_dbase->version, &tversion,
667 sizeof(struct ubik_version));
668 snprintf(tbuffer, sizeof(tbuffer), "%s.DB%s%d",
669 ubik_dbase->pathName, (file<0)?"SYS":"",
670 (file<0)?-file:file);
672 snprintf(pbuffer, sizeof(pbuffer), "%s.DB%s%d.OLD",
673 ubik_dbase->pathName, (file<0)?"SYS":"",
674 (file<0)?-file:file);
675 code = unlink(pbuffer);
677 code = rename(tbuffer, pbuffer);
678 snprintf(pbuffer, sizeof(pbuffer), "%s.DB%s%d.TMP",
679 ubik_dbase->pathName, (file<0)?"SYS":"",
680 (file<0)?-file:file);
683 code = rename(pbuffer, tbuffer);
685 (*ubik_dbase->open) (ubik_dbase, file);
686 /* after data is good, sync disk with correct label */
688 (*ubik_dbase->setlabel) (ubik_dbase, 0,
689 &ubik_dbase->version);
693 snprintf(pbuffer, sizeof(pbuffer), "%s.DB%s%d.OLD",
694 ubik_dbase->pathName, (file<0)?"SYS":"",
695 (file<0)?-file:file);
702 * We will effectively invalidate the old data forever now.
703 * Unclear if we *should* but we do.
706 ubik_dbase->version.epoch = 0;
707 ubik_dbase->version.counter = 0;
709 ubik_print("Ubik: Synchronize database failed (error = %d)\n",
712 ubik_print("Ubik: Synchronize database completed\n");
713 urecovery_state |= UBIK_RECHAVEDB;
715 udisk_Invalidate(ubik_dbase, 0); /* data has changed */
716 #ifdef AFS_PTHREAD_ENV
717 CV_BROADCAST(&ubik_dbase->version_cond);
719 LWP_NoYieldSignal(&ubik_dbase->version);
722 if (!(urecovery_state & UBIK_RECHAVEDB)) {
724 continue; /* not ready */
727 /* If the database was newly initialized, then when we establish quorum, write
728 * a new label. This allows urecovery_AllBetter() to allow access for reads.
729 * Setting it to 2 also allows another site to come along with a newer
730 * database and overwrite this one.
732 if (ubik_dbase->version.epoch == 1) {
733 urecovery_AbortAll(ubik_dbase);
735 version_globals.ubik_epochTime = 2;
736 ubik_dbase->version.epoch = version_globals.ubik_epochTime;
737 ubik_dbase->version.counter = 1;
739 (*ubik_dbase->setlabel) (ubik_dbase, 0, &ubik_dbase->version);
741 udisk_Invalidate(ubik_dbase, 0); /* data may have changed */
742 #ifdef AFS_PTHREAD_ENV
743 CV_BROADCAST(&ubik_dbase->version_cond);
745 LWP_NoYieldSignal(&ubik_dbase->version);
749 /* Check the other sites and send the database to them if they
750 * do not have the current db.
752 if (!(urecovery_state & UBIK_RECSENTDB)) {
753 /* now propagate out new version to everyone else */
754 dbok = 1; /* start off assuming they all worked */
757 * Check if a write transaction is in progress. We can't send the
758 * db when a write is in progress here because the db would be
759 * obsolete as soon as it goes there. Also, ops after the begin
760 * trans would reach the recepient and wouldn't find a transaction
761 * pending there. Frankly, I don't think it's possible to get past
762 * the write-lock above if there is a write transaction in progress,
763 * but then, it won't hurt to check, will it?
765 if (ubik_dbase->flags & DBWRITING) {
768 long cur_usec = 50000;
769 while ((ubik_dbase->flags & DBWRITING) && (safety < 500)) {
771 /* sleep for a little while */
773 tv.tv_usec = cur_usec;
774 #ifdef AFS_PTHREAD_ENV
775 select(0, 0, 0, 0, &tv);
777 IOMGR_Select(0, 0, 0, 0, &tv);
785 for (ts = ubik_servers; ts; ts = ts->next) {
787 inAddr.s_addr = ts->addr[0];
792 ubik_dprint("recovery cannot send version to %s\n",
793 afs_inet_ntoa_r(inAddr.s_addr, hoststr));
798 ubik_dprint("recovery sending version to %s\n",
799 afs_inet_ntoa_r(inAddr.s_addr, hoststr));
800 if (vcmp(ts->version, ubik_dbase->version) != 0) {
801 ubik_dprint("recovery stating local database\n");
803 /* Rx code to do the Bulk Store */
804 code = (*ubik_dbase->stat) (ubik_dbase, 0, &ubikstat);
806 length = ubikstat.size;
809 rxcall = rx_NewCall(ts->disk_rxcid);
812 StartDISK_SendFile(rxcall, file, length,
813 &ubik_dbase->version);
815 ubik_dprint("StartDiskSendFile failed=%d\n",
822 sizeof(tbuffer) ? sizeof(tbuffer) : length);
824 (*ubik_dbase->read) (ubik_dbase, file,
825 tbuffer, offset, tlen);
826 if (nbytes != tlen) {
827 ubik_dprint("Local disk read error=%d\n",
831 nbytes = rx_Write(rxcall, tbuffer, tlen);
832 if (nbytes != tlen) {
833 ubik_dprint("Rx-write bulk error=%d\n", code =
840 code = EndDISK_SendFile(rxcall);
842 code = rx_EndCall(rxcall, code);
845 /* we set a new file, process its header */
846 ts->version = ubik_dbase->version;
851 /* mark file up to date */
856 urecovery_state |= UBIK_RECSENTDB;
864 * \brief send a Probe to all the network address of this server
866 * \return 0 if success, else return 1
869 DoProbe(struct ubik_server *server)
871 struct rx_connection *conns[UBIK_MAX_INTERFACE_ADDR];
872 struct rx_connection *connSuccess = 0;
873 int i, j, success_i = -1;
879 for (i = 0; (addr = server->addr[i]) && (i < UBIK_MAX_INTERFACE_ADDR);
882 rx_NewConnection(addr, ubik_callPortal, DISK_SERVICE_ID,
883 addr_globals.ubikSecClass, addr_globals.ubikSecIndex);
885 /* user requirement to use only the primary interface */
886 if (ubikPrimaryAddrOnly) {
892 opr_Assert(i); /* at least one interface address for this server */
896 if (!multi_error) { /* first success */
903 if (success_i >= 0) {
905 addr = server->addr[success_i]; /* successful interface addr */
907 if (server->disk_rxcid) /* destroy existing conn */
908 rx_DestroyConnection(server->disk_rxcid);
909 if (server->vote_rxcid)
910 rx_DestroyConnection(server->vote_rxcid);
912 /* make new connections */
913 server->disk_rxcid = conns[success_i];
914 server->vote_rxcid = rx_NewConnection(addr, ubik_callPortal,
915 VOTE_SERVICE_ID, addr_globals.ubikSecClass,
916 addr_globals.ubikSecIndex);
918 connSuccess = conns[success_i];
919 strcpy(buffer, afs_inet_ntoa_r(server->addr[0], hoststr));
921 ubik_print("ubik:server %s is back up: will be contacted through %s\n",
922 buffer, afs_inet_ntoa_r(addr, hoststr));
926 /* Destroy all connections except the one on which we succeeded */
927 for (j = 0; j < i; j++)
928 if (conns[j] != connSuccess)
929 rx_DestroyConnection(conns[j]);
932 ubik_dprint("ubik:server %s still down\n",
933 afs_inet_ntoa_r(server->addr[0], hoststr));
936 return 0; /* success */
938 return 1; /* failure */