]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/msgchan.c
Vacation work -- see tech log
[bacula/bacula] / bacula / src / dird / msgchan.c
1 /*
2  *
3  *   Bacula Director -- msgchan.c -- handles the message channel
4  *    to the Storage daemon and the File daemon.
5  *
6  *     Kern Sibbald, August MM
7  *
8  *    This routine runs as a thread and must be thread reentrant.
9  *
10  *  Basic tasks done here:
11  *    Open a message channel with the Storage daemon
12  *      to authenticate ourself and to pass the JobId.
13  *    Create a thread to interact with the Storage daemon
14  *      who returns a job status and requests Catalog services, etc.
15  *
16  *   Version $Id$
17  */
18 /*
19    Copyright (C) 2000-2005 Kern Sibbald
20
21    This program is free software; you can redistribute it and/or
22    modify it under the terms of the GNU General Public License as
23    published by the Free Software Foundation; either version 2 of
24    the License, or (at your option) any later version.
25
26    This program is distributed in the hope that it will be useful,
27    but WITHOUT ANY WARRANTY; without even the implied warranty of
28    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
29    General Public License for more details.
30
31    You should have received a copy of the GNU General Public
32    License along with this program; if not, write to the Free
33    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
34    MA 02111-1307, USA.
35
36  */
37
38 #include "bacula.h"
39 #include "dird.h"
40
41 /* Commands sent to Storage daemon */
42 static char jobcmd[]     = "JobId=%d job=%s job_name=%s client_name=%s "
43    "type=%d level=%d FileSet=%s NoAttr=%d SpoolAttr=%d FileSetMD5=%s "
44    "SpoolData=%d WritePartAfterJob=%d";
45 static char use_device[] = "use device=%s media_type=%s pool_name=%s "
46    "pool_type=%s append=%d\n";
47 static char query_device[] = "query device=%s";
48
49 /* Response from Storage daemon */
50 static char OKjob[]      = "3000 OK Job SDid=%d SDtime=%d Authorization=%100s\n";
51 static char OK_device[]  = "3000 OK use device\n";
52 static char OK_query[]  = "3001 OK query append=%d read=%d num_writers=%d "
53    "num_waiting=%d open=%d use_count=%d labeled=%d "
54    "media_type=%127s volume_name=%127s";
55
56 /* Storage Daemon requests */
57 static char Job_start[]  = "3010 Job %127s start\n";
58 static char Job_end[]    =
59    "3099 Job %127s end JobStatus=%d JobFiles=%d JobBytes=%" lld "\n";
60
61 /* Forward referenced functions */
62 extern "C" void *msg_thread(void *arg);
63
64 /*
65  * Establish a message channel connection with the Storage daemon
66  * and perform authentication.
67  */
68 bool connect_to_storage_daemon(JCR *jcr, int retry_interval,
69                               int max_retry_time, int verbose)
70 {
71    BSOCK *sd;
72    STORE *store;
73
74    if (jcr->store_bsock) {
75       return true;                    /* already connected */
76    }
77    store = (STORE *)jcr->storage->first();
78
79    /*
80     *  Open message channel with the Storage daemon
81     */
82    Dmsg2(200, "bnet_connect to Storage daemon %s:%d\n", store->address,
83       store->SDport);
84    sd = bnet_connect(jcr, retry_interval, max_retry_time,
85           _("Storage daemon"), store->address,
86           NULL, store->SDport, verbose);
87    if (sd == NULL) {
88       return false;
89    }
90    sd->res = (RES *)store;        /* save pointer to other end */
91    jcr->store_bsock = sd;
92
93    if (!authenticate_storage_daemon(jcr, store)) {
94       bnet_close(sd);
95       jcr->store_bsock = NULL;
96       return false;
97    }
98    return true;
99 }
100
101 /*
102  * Here we ask the SD to send us the info for a 
103  *  particular device resource.
104  */
105 bool update_device_res(JCR *jcr, DEVICE *dev)
106 {
107    POOL_MEM device_name, media_type, volume_name;
108    int dev_open, dev_append, dev_read, dev_labeled;
109    BSOCK *sd;
110    if (!connect_to_storage_daemon(jcr, 5, 30, 0)) {
111       return false;
112    }
113    sd = jcr->store_bsock;
114    pm_strcpy(device_name, dev->hdr.name);
115    bash_spaces(device_name);
116    bnet_fsend(sd, query_device, device_name.c_str());
117    if (bget_dirmsg(sd) > 0) {
118       Dmsg1(400, "<stored: %s", sd->msg);
119       if (sscanf(sd->msg, OK_query, &dev_append, &dev_read,
120           &dev->num_writers, &dev->num_waiting, &dev_open,
121           &dev->use_count, &dev_labeled, media_type.c_str(),
122           volume_name.c_str()) != 9) {
123          return false;
124       }
125       unbash_spaces(media_type);
126       unbash_spaces(volume_name);
127       bstrncpy(dev->MediaType, media_type.c_str(), sizeof(dev->MediaType));
128       bstrncpy(dev->VolumeName, volume_name.c_str(), sizeof(dev->VolumeName));
129       dev->open = dev_open;
130       dev->append = dev_append;
131       dev->read = dev_read;
132       dev->labeled = dev_labeled;
133       dev->found = true;
134    } else {
135       return false;
136    }
137    return true;
138 }
139
140 /*
141  * Start a job with the Storage daemon
142  */
143 int start_storage_daemon_job(JCR *jcr, alist *store, int append)
144 {
145    bool ok;
146    STORE *storage;
147    BSOCK *sd;
148    char auth_key[100];
149    POOL_MEM device_name, pool_name, pool_type, media_type;
150
151    sd = jcr->store_bsock;
152    /*
153     * Now send JobId and permissions, and get back the authorization key.
154     */
155    bash_spaces(jcr->job->hdr.name);
156    bash_spaces(jcr->client->hdr.name);
157    bash_spaces(jcr->fileset->hdr.name);
158    if (jcr->fileset->MD5[0] == 0) {
159       bstrncpy(jcr->fileset->MD5, "**Dummy**", sizeof(jcr->fileset->MD5));
160    }
161    bnet_fsend(sd, jobcmd, jcr->JobId, jcr->Job, jcr->job->hdr.name,
162               jcr->client->hdr.name, jcr->JobType, jcr->JobLevel,
163               jcr->fileset->hdr.name, !jcr->pool->catalog_files,
164               jcr->job->SpoolAttributes, jcr->fileset->MD5, jcr->spool_data, jcr->write_part_after_job);
165    Dmsg1(200, "Jobcmd=%s\n", sd->msg);
166    unbash_spaces(jcr->job->hdr.name);
167    unbash_spaces(jcr->client->hdr.name);
168    unbash_spaces(jcr->fileset->hdr.name);
169    if (bget_dirmsg(sd) > 0) {
170        Dmsg1(110, "<stored: %s", sd->msg);
171        if (sscanf(sd->msg, OKjob, &jcr->VolSessionId,
172                   &jcr->VolSessionTime, &auth_key) != 3) {
173           Dmsg1(100, "BadJob=%s\n", sd->msg);
174           Jmsg(jcr, M_FATAL, 0, _("Storage daemon rejected Job command: %s\n"), sd->msg);
175           return 0;
176        } else {
177           jcr->sd_auth_key = bstrdup(auth_key);
178           Dmsg1(150, "sd_auth_key=%s\n", jcr->sd_auth_key);
179        }
180    } else {
181       Jmsg(jcr, M_FATAL, 0, _("<stored: bad response to Job command: %s\n"),
182          bnet_strerror(sd));
183       return 0;
184    }
185
186 // foreach_alist(storage, store) {
187       storage = (STORE *)store->first();
188       pm_strcpy(device_name, storage->dev_name());
189       pm_strcpy(media_type, storage->media_type);
190       pm_strcpy(pool_type, jcr->pool->pool_type);
191       pm_strcpy(pool_name, jcr->pool->hdr.name);
192       bash_spaces(device_name);
193       bash_spaces(media_type);
194       bash_spaces(pool_type);
195       bash_spaces(pool_name);
196       bnet_fsend(sd, use_device, device_name.c_str(),
197                  media_type.c_str(), pool_name.c_str(), pool_type.c_str(),
198                  append);
199       Dmsg1(200, ">stored: %s", sd->msg);
200       ok = response(jcr, sd, OK_device, "Use Device", NO_DISPLAY);
201       if (!ok) {
202          pm_strcpy(pool_type, sd->msg); /* save message */
203          Jmsg(jcr, M_FATAL, 0, _("\n"
204             "     Storage daemon didn't accept Device \"%s\" because:\n     %s"),
205             device_name.c_str(), pool_type.c_str()/* sd->msg */);
206       }
207 // }
208    if (ok) {
209       bnet_fsend(sd, "run");
210    }
211    return ok;
212 }
213
214 /*
215  * Start a thread to handle Storage daemon messages and
216  *  Catalog requests.
217  */
218 int start_storage_daemon_message_thread(JCR *jcr)
219 {
220    int status;
221    pthread_t thid;
222
223    P(jcr->mutex);
224    jcr->use_count++;                  /* mark in use by msg thread */
225    jcr->sd_msg_thread_done = false;
226    jcr->SD_msg_chan = 0;
227    V(jcr->mutex);
228    Dmsg0(100, "Start SD msg_thread.\n");
229    if ((status=pthread_create(&thid, NULL, msg_thread, (void *)jcr)) != 0) {
230       berrno be;
231       Jmsg1(jcr, M_ABORT, 0, _("Cannot create message thread: %s\n"), be.strerror(status));
232    }
233    Dmsg0(100, "SD msg_thread started.\n");
234    /* Wait for thread to start */
235    while (jcr->SD_msg_chan == 0) {
236       bmicrosleep(0, 50);
237    }
238    return 1;
239 }
240
241 extern "C" void msg_thread_cleanup(void *arg)
242 {
243    JCR *jcr = (JCR *)arg;
244    Dmsg0(200, "End msg_thread\n");
245    db_end_transaction(jcr, jcr->db);       /* terminate any open transaction */
246    P(jcr->mutex);
247    jcr->sd_msg_thread_done = true;
248    pthread_cond_broadcast(&jcr->term_wait); /* wakeup any waiting threads */
249    jcr->SD_msg_chan = 0;
250    V(jcr->mutex);
251    free_jcr(jcr);                     /* release jcr */
252 }
253
254 /*
255  * Handle the message channel (i.e. requests from the
256  *  Storage daemon).
257  * Note, we are running in a separate thread.
258  */
259 extern "C" void *msg_thread(void *arg)
260 {
261    JCR *jcr = (JCR *)arg;
262    BSOCK *sd;
263    int JobStatus;
264    char Job[MAX_NAME_LENGTH];
265    uint32_t JobFiles;
266    uint64_t JobBytes;
267    int stat;
268
269    pthread_detach(pthread_self());
270    jcr->SD_msg_chan = pthread_self();
271    pthread_cleanup_push(msg_thread_cleanup, arg);
272    sd = jcr->store_bsock;
273
274    /* Read the Storage daemon's output.
275     */
276    Dmsg0(100, "Start msg_thread loop\n");
277    while ((stat=bget_dirmsg(sd)) >= 0) {
278       Dmsg1(200, "<stored: %s", sd->msg);
279       if (sscanf(sd->msg, Job_start, &Job) == 1) {
280          continue;
281       }
282       if (sscanf(sd->msg, Job_end, &Job, &JobStatus, &JobFiles,
283                  &JobBytes) == 4) {
284          jcr->SDJobStatus = JobStatus; /* termination status */
285          jcr->SDJobFiles = JobFiles;
286          jcr->SDJobBytes = JobBytes;
287          break;
288       }
289    }
290    if (is_bnet_error(sd)) {
291       jcr->SDJobStatus = JS_ErrorTerminated;
292    }
293    pthread_cleanup_pop(1);
294    return NULL;
295 }
296
297 void wait_for_storage_daemon_termination(JCR *jcr)
298 {
299    int cancel_count = 0;
300    /* Now wait for Storage daemon to terminate our message thread */
301    set_jcr_job_status(jcr, JS_WaitSD);
302    P(jcr->mutex);
303    while (!jcr->sd_msg_thread_done) {
304       struct timeval tv;
305       struct timezone tz;
306       struct timespec timeout;
307
308       gettimeofday(&tv, &tz);
309       timeout.tv_nsec = 0;
310       timeout.tv_sec = tv.tv_sec + 10; /* wait 10 seconds */
311       Dmsg0(300, "I'm waiting for message thread termination.\n");
312       pthread_cond_timedwait(&jcr->term_wait, &jcr->mutex, &timeout);
313       if (job_canceled(jcr)) {
314          cancel_count++;
315       }
316       /* Give SD 30 seconds to clean up after cancel */
317       if (cancel_count == 3) {
318          break;
319       }
320    }
321    V(jcr->mutex);
322    set_jcr_job_status(jcr, JS_Terminated);
323 }
324
325
326 #define MAX_TRIES 30
327 #define WAIT_TIME 2
328 extern "C" void *device_thread(void *arg)
329 {
330    int i;
331    JCR *jcr;
332    DEVICE *dev;
333
334
335    pthread_detach(pthread_self());
336    jcr = new_control_jcr("*DeviceInit*", JT_SYSTEM);
337    for (i=0; i < MAX_TRIES; i++) {
338       if (!connect_to_storage_daemon(jcr, 10, 30, 1)) {
339          Dmsg0(000, "Failed connecting to SD.\n");
340          continue;
341       }
342       LockRes();
343       foreach_res(dev, R_DEVICE) {
344          if (!update_device_res(jcr, dev)) {
345             Dmsg1(900, "Error updating device=%s\n", dev->hdr.name);
346          } else {
347             Dmsg1(900, "Updated Device=%s\n", dev->hdr.name);
348          }
349       }
350       UnlockRes();
351       bnet_close(jcr->store_bsock);
352       jcr->store_bsock = NULL;
353       break;
354
355    }
356    free_jcr(jcr);
357    return NULL;
358 }
359
360 /*
361  * Start a thread to handle getting Device resource information
362  *  from SD. This is called once at startup of the Director.
363  */
364 void init_device_resources()
365 {
366    int status;
367    pthread_t thid;
368
369    Dmsg0(100, "Start Device thread.\n");
370    if ((status=pthread_create(&thid, NULL, device_thread, NULL)) != 0) {
371       berrno be;
372       Jmsg1(NULL, M_ABORT, 0, _("Cannot create message thread: %s\n"), be.strerror(status));
373    }
374 }