2 * Copyright (c) 2011-2012 The DragonFly Project. All rights reserved.
4 * This code is derived from software contributed to The DragonFly Project
5 * by Matthew Dillon <dillon@dragonflybsd.org>
6 * by Venkatesh Srinivas <vsrinivas@dragonflybsd.org>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
18 * 3. Neither the name of The DragonFly Project nor the names of its
19 * contributors may be used to endorse or promote products derived
20 * from this software without specific, prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
28 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
30 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 #include <sys/xdiskioctl.h>
39 #include <machine/atomic.h>
41 struct hammer2_media_config {
42 hammer2_volconf_t copy_run;
43 hammer2_volconf_t copy_pend;
49 int pipefd[2]; /* signal stop */
51 pthread_t iocom_thread;
52 enum { H2MC_STOPPED, H2MC_CONNECT, H2MC_RUNNING } state;
55 typedef struct hammer2_media_config hammer2_media_config_t;
57 #define H2CONFCTL_STOP 0x00000001
58 #define H2CONFCTL_UPDATE 0x00000002
61 TAILQ_ENTRY(diskcon) entry;
65 struct service_node_opaque {
68 dmsg_media_block_t block;
75 TAILQ_ENTRY(autoconn) entry;
79 int pipefd[2]; /* {read,write} */
80 enum { AUTOCONN_INACTIVE, AUTOCONN_ACTIVE } state;
86 TAILQ_HEAD(, diskcon) diskconq = TAILQ_HEAD_INITIALIZER(diskconq);
87 static pthread_mutex_t diskmtx;
88 static pthread_mutex_t confmtx;
90 static void *service_thread(void *data);
91 static void *udev_thread(void *data);
92 static void *autoconn_thread(void *data);
93 static void master_reconnect(const char *mntpt);
94 static void disk_reconnect(const char *disk);
95 static void disk_disconnect(void *handle);
96 static void udev_check_disks(void);
97 static void hammer2_usrmsg_handler(dmsg_msg_t *msg, int unmanaged);
98 static void *hammer2_volconf_thread(void *info);
99 static void hammer2_volconf_signal(dmsg_iocom_t *iocom);
100 static void hammer2_volconf_start(hammer2_media_config_t *conf,
101 const char *hostname);
102 static void hammer2_volconf_stop(hammer2_media_config_t *conf);
105 static void xdisk_connect(void);
108 * Start-up the master listener daemon for the machine. This daemon runs
109 * a UDP discovery protocol, a TCP rendezvous, and scans certain files
110 * and directories for work.
114 * The only purpose for the UDP discovery protocol is to determine what
115 * other IPs on the LAN are running the hammer2 service daemon. DNS is not
116 * required to operate, but hostnames (if assigned) must be unique. If
117 * no hostname is assigned the host's IP is used as the name. This name
118 * is broadcast along with the mtime of the originator's private key.
120 * Receiving hammer2 service daemons which are able to match the label against
121 * /etc/hammer2/remote/<label>.pub will initiate a persistent connection
122 * to the target. Removal of the file will cause a disconnection. A failed
123 * public key negotiation stops further connection attempts until either the
124 * file is updated or the remote mtime is updated.
126 * Generally speaking this results in a web of connections, typically a
127 * combination of point-to-point for the more important links and relayed
128 * (spanning tree) for less important or filtered links.
132 * The TCP listener serves as a rendezvous point in the cluster, accepting
133 * connections, performing registrations and authentications, maintaining
134 * the spanning tree, and keeping track of message state so disconnects can
135 * be handled properly.
137 * Once authenticated only low-level messaging protocols (which includes
138 * tracking persistent messages) are handled by this daemon. This daemon
139 * does not run the higher level quorum or locking protocols.
143 * The file /etc/hammer2/autoconn, if it exists, contains a list of targets
144 * to connect to (which do not have to be on the local lan). This list will
145 * be retried until a connection can be established. The file is not usually
146 * needed for linkages local to the LAN.
151 struct sockaddr_in lsin;
156 * Acquire socket and set options
158 if ((lfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
159 fprintf(stderr, "master_listen: socket(): %s\n",
164 setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
167 * Setup listen port and try to bind. If the bind fails we assume
168 * that a master listener process is already running and silently
171 bzero(&lsin, sizeof(lsin));
172 lsin.sin_family = AF_INET;
173 lsin.sin_addr.s_addr = INADDR_ANY;
174 lsin.sin_port = htons(DMSG_LISTEN_PORT);
175 if (bind(lfd, (struct sockaddr *)&lsin, sizeof(lsin)) < 0) {
179 "master listen: daemon already running\n");
184 fprintf(stderr, "master listen: startup\n");
188 * Fork and disconnect the controlling terminal and parent process,
189 * executing the specified function as a pthread.
191 * Returns to the original process which can then continue running.
192 * In debug mode this call will create the pthread without forking
193 * and set NormalExit to 0, instead of fork.
195 hammer2_demon(service_thread, (void *)(intptr_t)lfd);
202 * Master listen/accept thread. Accept connections on the master socket,
203 * starting a pthread for each one.
207 service_thread(void *data)
209 struct sockaddr_in asin;
212 dmsg_master_service_info_t *info;
213 int lfd = (int)(intptr_t)data;
218 struct statfs *mntbuf = NULL;
219 struct statvfs *mntvbuf = NULL;
222 * Nobody waits for us
224 setproctitle("hammer2 master listen");
225 pthread_detach(pthread_self());
228 * Start up a thread to handle block device monitoring for
229 * export to the cluster.
231 pthread_create(&thread, NULL, udev_thread, NULL);
234 * Start up a thread to tie /dev/xdisk into the cluster
240 * Start thread to manage /etc/hammer2/autoconn
242 pthread_create(&thread, NULL, autoconn_thread, NULL);
245 * Scan existing hammer2 mounts and reconnect to them using
246 * HAMMER2IOC_RECLUSTER.
248 count = getmntvinfo(&mntbuf, &mntvbuf, MNT_NOWAIT);
249 for (i = 0; i < count; ++i) {
250 if (strcmp(mntbuf[i].f_fstypename, "hammer2") == 0)
251 master_reconnect(mntbuf[i].f_mntonname);
255 * Accept connections and create pthreads to handle them after
260 fd = accept(lfd, (struct sockaddr *)&asin, &alen);
267 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt);
268 fprintf(stderr, "service_thread: accept fd %d\n", fd);
269 info = malloc(sizeof(*info));
270 bzero(info, sizeof(*info));
273 info->usrmsg_callback = hammer2_usrmsg_handler;
274 info->label = strdup("client");
275 pthread_create(&thread, NULL, dmsg_master_service, info);
281 * Handle/Monitor the dmsg stream. If unmanaged is set we are responsible
282 * for responding for the message, otherwise if it is not set libdmsg has
283 * already done some preprocessing and will respond to the message for us
286 * We primarily monitor for VOLCONFs
290 hammer2_usrmsg_handler(dmsg_msg_t *msg, int unmanaged)
293 hammer2_media_config_t *conf;
294 dmsg_lnk_hammer2_volconf_t *msgconf;
298 * Only process messages which are part of a LNK_CONN stream
302 (state->rxcmd & DMSGF_BASECMDMASK) != DMSG_LNK_CONN) {
303 hammer2_shell_parse(msg, unmanaged);
308 case DMSG_LNK_CONN | DMSGF_CREATE | DMSGF_DELETE:
309 case DMSG_LNK_CONN | DMSGF_DELETE:
310 case DMSG_LNK_ERROR | DMSGF_DELETE:
312 * Deleting connection, clean out all volume configs
314 if (state->media == NULL || state->media->usrhandle == NULL)
316 conf = state->media->usrhandle;
317 fprintf(stderr, "Shutting down media spans\n");
318 for (i = 0; i < HAMMER2_COPYID_COUNT; ++i) {
319 if (conf[i].thread) {
320 conf[i].ctl = H2CONFCTL_STOP;
321 pthread_cond_signal(&conf[i].cond);
324 for (i = 0; i < HAMMER2_COPYID_COUNT; ++i) {
325 if (conf[i].thread) {
326 pthread_join(conf[i].thread, NULL);
327 conf->thread_started = 0;
328 pthread_cond_destroy(&conf[i].cond);
331 state->media->usrhandle = NULL;
334 case DMSG_LNK_HAMMER2_VOLCONF:
336 * One-way volume-configuration message is transmitted
337 * over the open LNK_CONN transaction.
339 fprintf(stderr, "RECEIVED VOLCONF\n");
341 if ((conf = state->media->usrhandle) == NULL) {
342 conf = malloc(sizeof(*conf) * HAMMER2_COPYID_COUNT);
343 bzero(conf, sizeof(*conf) * HAMMER2_COPYID_COUNT);
344 state->media->usrhandle = conf;
346 msgconf = H2_LNK_VOLCONF(msg);
348 if (msgconf->index < 0 ||
349 msgconf->index >= HAMMER2_COPYID_COUNT) {
351 "VOLCONF: ILLEGAL INDEX %d\n",
355 if (msgconf->copy.path[sizeof(msgconf->copy.path) - 1] != 0 ||
356 msgconf->copy.path[0] == 0) {
358 "VOLCONF: ILLEGAL PATH %d\n",
362 conf += msgconf->index;
363 pthread_mutex_lock(&confmtx);
364 conf->copy_pend = msgconf->copy;
365 conf->ctl |= H2CONFCTL_UPDATE;
366 pthread_mutex_unlock(&confmtx);
367 if (conf->thread_started == 0) {
368 fprintf(stderr, "VOLCONF THREAD STARTED\n");
369 pthread_cond_init(&conf->cond, NULL);
370 pthread_create(&conf->thread, NULL,
371 hammer2_volconf_thread, (void *)conf);
372 conf->thread_started = 1;
374 pthread_cond_signal(&conf->cond);
378 dmsg_msg_reply(msg, DMSG_ERR_NOSUPP);
384 hammer2_volconf_thread(void *info)
386 hammer2_media_config_t *conf = info;
388 setproctitle("hammer2 volconf");
390 pthread_mutex_lock(&confmtx);
391 while ((conf->ctl & H2CONFCTL_STOP) == 0) {
392 if (conf->ctl & H2CONFCTL_UPDATE) {
393 fprintf(stderr, "VOLCONF UPDATE\n");
394 conf->ctl &= ~H2CONFCTL_UPDATE;
395 if (bcmp(&conf->copy_run, &conf->copy_pend,
396 sizeof(conf->copy_run)) == 0) {
397 fprintf(stderr, "VOLCONF: no changes\n");
401 * XXX TODO - auto reconnect on lookup failure or
402 * connect failure or stream failure.
405 pthread_mutex_unlock(&confmtx);
406 hammer2_volconf_stop(conf);
407 conf->copy_run = conf->copy_pend;
408 if (conf->copy_run.copyid != 0 &&
409 strncmp((char*)conf->copy_run.path, "span:", 5) == 0) {
410 hammer2_volconf_start(conf,
411 (char*)conf->copy_run.path + 5);
413 pthread_mutex_lock(&confmtx);
414 fprintf(stderr, "VOLCONF UPDATE DONE state %d\n", conf->state);
416 if (conf->state == H2MC_CONNECT) {
417 hammer2_volconf_start(conf, (char*)conf->copy_run.path + 5);
418 pthread_mutex_unlock(&confmtx);
420 pthread_mutex_lock(&confmtx);
422 pthread_cond_wait(&conf->cond, &confmtx);
425 pthread_mutex_unlock(&confmtx);
426 hammer2_volconf_stop(conf);
432 hammer2_volconf_start(hammer2_media_config_t *conf, const char *hostname)
434 dmsg_master_service_info_t *info;
436 switch(conf->state) {
439 conf->fd = dmsg_connect(hostname);
441 fprintf(stderr, "Unable to connect to %s\n", hostname);
442 conf->state = H2MC_CONNECT;
443 } else if (pipe(conf->pipefd) < 0) {
445 fprintf(stderr, "pipe() failed during volconf\n");
446 conf->state = H2MC_CONNECT;
448 fprintf(stderr, "VOLCONF CONNECT\n");
449 info = malloc(sizeof(*info));
450 bzero(info, sizeof(*info));
452 info->altfd = conf->pipefd[0];
453 info->altmsg_callback = hammer2_volconf_signal;
454 info->usrmsg_callback = hammer2_usrmsg_handler;
456 conf->state = H2MC_RUNNING;
457 pthread_create(&conf->iocom_thread, NULL,
458 dmsg_master_service, info);
468 hammer2_volconf_stop(hammer2_media_config_t *conf)
470 switch(conf->state) {
474 conf->state = H2MC_STOPPED;
477 close(conf->pipefd[1]);
478 conf->pipefd[1] = -1;
479 pthread_join(conf->iocom_thread, NULL);
480 conf->state = H2MC_STOPPED;
487 hammer2_volconf_signal(dmsg_iocom_t *iocom)
489 atomic_set_int(&iocom->flags, DMSG_IOCOMF_EOF);
493 * Monitor block devices. Currently polls every ~10 seconds or so.
497 udev_thread(void *data __unused)
502 pthread_detach(pthread_self());
503 setproctitle("hammer2 udev_thread");
505 if ((fd = open(UDEV_DEVICE_PATH, O_RDWR)) < 0) {
506 fprintf(stderr, "udev_thread: unable to open \"%s\"\n",
511 while (ioctl(fd, UDEVWAIT, &seq) == 0) {
518 static void *autoconn_connect_thread(void *data);
519 static void autoconn_disconnect_signal(dmsg_iocom_t *iocom);
523 autoconn_thread(void *data __unused)
525 TAILQ_HEAD(, autoconn) autolist;
527 struct autoconn *next;
536 TAILQ_INIT(&autolist);
540 pthread_detach(pthread_self());
541 setproctitle("hammer2 autoconn_thread");
549 * Poll the file. Loop up if the synchronized state (lmod)
552 if (stat(HAMMER2_DEFAULT_DIR "/autoconn", &st) == 0) {
553 if (lmod == st.st_mtime)
555 fp = fopen(HAMMER2_DEFAULT_DIR "/autoconn", "r");
565 * Wait at least 5 seconds after the file is created or
568 * Do not update the synchronized state.
570 if (fp == NULL && found_last) {
573 } else if (fp && found_last == 0) {
580 * Don't scan the file until the time progresses past the
581 * file's mtime, so we can validate that the file was not
582 * further modified during our scan.
584 * Do not update the synchronized state.
588 if (t == st.st_mtime) {
598 * Set staging to disconnect, then scan the file.
600 TAILQ_FOREACH(ac, &autolist, entry)
602 while (fp && fgets(buf, sizeof(buf), fp) != NULL) {
605 if ((host = strtok(buf, " \t\r\n")) == NULL ||
609 TAILQ_FOREACH(ac, &autolist, entry) {
610 if (strcmp(host, ac->host) == 0)
614 ac = malloc(sizeof(*ac));
615 bzero(ac, sizeof(*ac));
616 ac->host = strdup(host);
617 ac->state = AUTOCONN_INACTIVE;
618 TAILQ_INSERT_TAIL(&autolist, ac, entry);
624 * Ignore the scan (and retry again) if the file was
625 * modified during the scan.
627 * Do not update the synchronized state.
630 if (fstat(fileno(fp), &st) < 0) {
635 if (t != st.st_mtime)
640 * Update the synchronized state and reconfigure the
641 * connect list as needed.
644 next = TAILQ_FIRST(&autolist);
645 while ((ac = next) != NULL) {
646 next = TAILQ_NEXT(ac, entry);
651 if (ac->stage && ac->state == AUTOCONN_INACTIVE) {
652 if (pipe(ac->pipefd) == 0) {
654 ac->state = AUTOCONN_ACTIVE;
655 pthread_create(&thread, NULL,
656 autoconn_connect_thread,
662 * Unstaging, stop active connection.
664 * We write to the pipe which causes the iocom_core
665 * to call autoconn_disconnect_signal().
667 if (ac->stage == 0 &&
668 ac->state == AUTOCONN_ACTIVE) {
669 if (ac->stopme == 0) {
672 write(ac->pipefd[1], &dummy, 1);
677 * Unstaging, delete inactive connection.
679 if (ac->stage == 0 &&
680 ac->state == AUTOCONN_INACTIVE) {
681 TAILQ_REMOVE(&autolist, ac, entry);
694 autoconn_connect_thread(void *data)
696 dmsg_master_service_info_t *info;
702 pthread_detach(pthread_self());
703 setproctitle("hammer2 dmsg");
705 while (ac->stopme == 0) {
706 fd = dmsg_connect(ac->host);
708 if (DMsgDebugOpt > 2) {
710 "autoconn: Connect failure: %s\n",
716 fprintf(stderr, "autoconn: Connect %s\n", ac->host);
718 info = malloc(sizeof(*info));
719 bzero(info, sizeof(*info));
721 info->altfd = ac->pipefd[0];
722 info->altmsg_callback = autoconn_disconnect_signal;
723 info->usrmsg_callback = hammer2_usrmsg_handler;
725 info->noclosealt = 1;
726 pthread_create(&ac->thread, NULL, dmsg_master_service, info);
727 pthread_join(ac->thread, &res);
729 close(ac->pipefd[0]);
730 ac->state = AUTOCONN_INACTIVE;
731 /* auto structure can be ripped out here */
737 autoconn_disconnect_signal(dmsg_iocom_t *iocom)
739 fprintf(stderr, "autoconn: Shutting down socket\n");
740 atomic_set_int(&iocom->flags, DMSG_IOCOMF_EOF);
744 * Retrieve the list of disk attachments and attempt to export
749 udev_check_disks(void)
759 error = sysctlbyname("kern.disks", NULL, &n, NULL, 0);
760 if (error < 0 || n == 0)
762 if (n >= sizeof(tmpbuf))
766 error = sysctlbyname("kern.disks", buf, &n, NULL, 0);
779 fprintf(stderr, "DISKS: %s\n", buf);
780 for (disk = strtok(buf, WS); disk; disk = strtok(NULL, WS)) {
781 disk_reconnect(disk);
789 * Normally the mount program supplies a cluster communications
790 * descriptor to the hammer2 vfs on mount, but if you kill the service
791 * daemon and restart it that link will be lost.
793 * This procedure attempts to [re]connect to existing mounts when
794 * the service daemon is started up before going into its accept
797 * NOTE: A hammer2 mount point can only accomodate one connection at a time
798 * so this will disconnect any existing connection during the
803 master_reconnect(const char *mntpt)
805 struct hammer2_ioc_recluster recls;
806 dmsg_master_service_info_t *info;
811 fd = open(mntpt, O_RDONLY);
813 fprintf(stderr, "reconnect %s: no access to mount\n", mntpt);
816 if (pipe(pipefds) < 0) {
817 fprintf(stderr, "reconnect %s: pipe() failed\n", mntpt);
821 bzero(&recls, sizeof(recls));
822 recls.fd = pipefds[0];
823 if (ioctl(fd, HAMMER2IOC_RECLUSTER, &recls) < 0) {
824 fprintf(stderr, "reconnect %s: ioctl failed\n", mntpt);
833 info = malloc(sizeof(*info));
834 bzero(info, sizeof(*info));
835 info->fd = pipefds[1];
837 info->usrmsg_callback = hammer2_usrmsg_handler;
838 info->label = strdup("hammer2");
839 pthread_create(&thread, NULL, dmsg_master_service, info);
843 * Reconnect a physical disk service to the mesh.
847 disk_reconnect(const char *disk)
849 struct disk_ioc_recluster recls;
851 dmsg_master_service_info_t *info;
858 * Urm, this will auto-create mdX+1, just ignore for now.
859 * This mechanic needs to be fixed. It might actually be nice
860 * to be able to export md disks.
862 if (strncmp(disk, "md", 2) == 0)
864 if (strncmp(disk, "xa", 2) == 0)
868 * Check if already connected
870 pthread_mutex_lock(&diskmtx);
871 TAILQ_FOREACH(dc, &diskconq, entry) {
872 if (strcmp(dc->disk, disk) == 0)
875 pthread_mutex_unlock(&diskmtx);
880 * Not already connected, create a connection to the kernel
883 asprintf(&path, "/dev/%s", disk);
884 fd = open(path, O_RDONLY);
886 fprintf(stderr, "reconnect %s: no access to disk\n", disk);
891 if (pipe(pipefds) < 0) {
892 fprintf(stderr, "reconnect %s: pipe() failed\n", disk);
896 bzero(&recls, sizeof(recls));
897 recls.fd = pipefds[0];
898 if (ioctl(fd, DIOCRECLUSTER, &recls) < 0) {
899 fprintf(stderr, "reconnect %s: ioctl failed\n", disk);
908 dc = malloc(sizeof(*dc));
909 dc->disk = strdup(disk);
910 pthread_mutex_lock(&diskmtx);
911 TAILQ_INSERT_TAIL(&diskconq, dc, entry);
912 pthread_mutex_unlock(&diskmtx);
914 info = malloc(sizeof(*info));
915 bzero(info, sizeof(*info));
916 info->fd = pipefds[1];
918 info->usrmsg_callback = hammer2_usrmsg_handler;
919 info->exit_callback = disk_disconnect;
921 info->label = strdup(dc->disk);
922 pthread_create(&thread, NULL, dmsg_master_service, info);
927 disk_disconnect(void *handle)
929 struct diskcon *dc = handle;
931 fprintf(stderr, "DISK_DISCONNECT %s\n", dc->disk);
933 pthread_mutex_lock(&diskmtx);
934 TAILQ_REMOVE(&diskconq, dc, entry);
935 pthread_mutex_unlock(&diskmtx);
941 * Connect our cluster controller to /dev/xdisk. xdisk will pick up
942 * SPAN messages that we route to it, makes remote block devices
943 * available to the host, and can issue dmsg transactions based on
950 dmsg_master_service_info_t *info;
951 struct xdisk_attach_ioctl xaioc;
958 * Is /dev/xdisk available?
960 xfd = open("/dev/xdisk", O_RDWR, 0600);
962 fprintf(stderr, "xdisk_connect: Unable to open /dev/xdisk\n");
966 if (pipe(pipefds) < 0) {
967 fprintf(stderr, "xdisk_connect: pipe() failed\n");
972 * Pipe between cluster controller (this user process).
974 info = malloc(sizeof(*info));
975 bzero(info, sizeof(*info));
976 info->fd = pipefds[1];
978 info->usrmsg_callback = hammer2_usrmsg_handler;
979 info->exit_callback = NULL;
980 pthread_create(&thread, NULL, dmsg_master_service, info);
983 * And the xdisk device.
985 bzero(&xaioc, sizeof(xaioc));
986 xaioc.fd = pipefds[0];
987 error = ioctl(xfd, XDISKIOCATTACH, &xaioc);
993 "xdisk_connect: cannot attach %s\n",