]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/msgchan.c
3e9199a1e4e9ffb02457cf2f7f7a827e6376fb7e
[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 device=%s\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 offline=%d "
54    "autoselect=%d autochanger=%d "
55    "changer_name=%127s media_type=%127s volume_name=%127s";
56
57 /* Storage Daemon requests */
58 static char Job_start[]  = "3010 Job %127s start\n";
59 static char Job_end[]    =
60    "3099 Job %127s end JobStatus=%d JobFiles=%d JobBytes=%" lld "\n";
61
62 /* Forward referenced functions */
63 extern "C" void *msg_thread(void *arg);
64
65 /*
66  * Establish a message channel connection with the Storage daemon
67  * and perform authentication.
68  */
69 bool connect_to_storage_daemon(JCR *jcr, int retry_interval,
70                               int max_retry_time, int verbose)
71 {
72    BSOCK *sd;
73    STORE *store;
74
75    if (jcr->store_bsock) {
76       return true;                    /* already connected */
77    }
78    store = (STORE *)jcr->storage->first();
79
80    /*
81     *  Open message channel with the Storage daemon
82     */
83    Dmsg2(200, "bnet_connect to Storage daemon %s:%d\n", store->address,
84       store->SDport);
85    sd = bnet_connect(jcr, retry_interval, max_retry_time,
86           _("Storage daemon"), store->address,
87           NULL, store->SDport, verbose);
88    if (sd == NULL) {
89       return false;
90    }
91    sd->res = (RES *)store;        /* save pointer to other end */
92    jcr->store_bsock = sd;
93
94    if (!authenticate_storage_daemon(jcr, store)) {
95       bnet_close(sd);
96       jcr->store_bsock = NULL;
97       return false;
98    }
99    return true;
100 }
101
102 /*
103  * Here we ask the SD to send us the info for a 
104  *  particular device resource.
105  */
106 bool update_device_res(JCR *jcr, DEVICE *dev)
107 {
108    POOL_MEM device_name, changer_name, media_type, volume_name;
109    int dev_open, dev_append, dev_read, dev_labeled;
110    int dev_offline, dev_autochanger, dev_autoselect;
111    BSOCK *sd;
112    if (!connect_to_storage_daemon(jcr, 5, 30, 0)) {
113       return false;
114    }
115    sd = jcr->store_bsock;
116    pm_strcpy(device_name, dev->hdr.name);
117    bash_spaces(device_name);
118    bnet_fsend(sd, query_device, device_name.c_str());
119    if (bget_dirmsg(sd) > 0) {
120       Dmsg1(400, "<stored: %s", sd->msg);
121       if (sscanf(sd->msg, OK_query, &dev_append, &dev_read,
122           &dev->num_writers, &dev->num_waiting, &dev_open,
123           &dev->use_count, &dev_labeled, &dev_offline, &dev_autoselect, 
124           &dev_autochanger,  changer_name.c_str(), media_type.c_str(),
125           volume_name.c_str()) != 13) {
126          return false;
127       }
128       unbash_spaces(changer_name);
129       unbash_spaces(media_type);
130       unbash_spaces(volume_name);
131       bstrncpy(dev->ChangerName, changer_name.c_str(), sizeof(dev->ChangerName));
132       bstrncpy(dev->MediaType, media_type.c_str(), sizeof(dev->MediaType));
133       bstrncpy(dev->VolumeName, volume_name.c_str(), sizeof(dev->VolumeName));
134       dev->open = dev_open;
135       dev->append = dev_append;
136       dev->read = dev_read;
137       dev->labeled = dev_labeled;
138       dev->offline = dev_offline;
139       dev->autoselect = dev_autoselect;
140       dev->autochanger = dev_autochanger;
141       dev->found = true;
142    } else {
143       return false;
144    }
145    return true;
146 }
147
148 /*
149  * Start a job with the Storage daemon
150  */
151 int start_storage_daemon_job(JCR *jcr, alist *store, int append)
152 {
153    bool ok;
154    STORE *storage;
155    BSOCK *sd;
156    char auth_key[100];
157    POOL_MEM device_name, pool_name, pool_type, media_type;
158
159    sd = jcr->store_bsock;
160    /*
161     * Now send JobId and permissions, and get back the authorization key.
162     */
163    bash_spaces(jcr->job->hdr.name);
164    bash_spaces(jcr->client->hdr.name);
165    bash_spaces(jcr->fileset->hdr.name);
166    if (jcr->fileset->MD5[0] == 0) {
167       bstrncpy(jcr->fileset->MD5, "**Dummy**", sizeof(jcr->fileset->MD5));
168    }
169    bnet_fsend(sd, jobcmd, jcr->JobId, jcr->Job, jcr->job->hdr.name,
170               jcr->client->hdr.name, jcr->JobType, jcr->JobLevel,
171               jcr->fileset->hdr.name, !jcr->pool->catalog_files,
172               jcr->job->SpoolAttributes, jcr->fileset->MD5, jcr->spool_data, jcr->write_part_after_job);
173    Dmsg1(200, "Jobcmd=%s\n", sd->msg);
174    unbash_spaces(jcr->job->hdr.name);
175    unbash_spaces(jcr->client->hdr.name);
176    unbash_spaces(jcr->fileset->hdr.name);
177    if (bget_dirmsg(sd) > 0) {
178        Dmsg1(110, "<stored: %s", sd->msg);
179        if (sscanf(sd->msg, OKjob, &jcr->VolSessionId,
180                   &jcr->VolSessionTime, &auth_key) != 3) {
181           Dmsg1(100, "BadJob=%s\n", sd->msg);
182           Jmsg(jcr, M_FATAL, 0, _("Storage daemon rejected Job command: %s\n"), sd->msg);
183           return 0;
184        } else {
185           jcr->sd_auth_key = bstrdup(auth_key);
186           Dmsg1(150, "sd_auth_key=%s\n", jcr->sd_auth_key);
187        }
188    } else {
189       Jmsg(jcr, M_FATAL, 0, _("<stored: bad response to Job command: %s\n"),
190          bnet_strerror(sd));
191       return 0;
192    }
193
194    pm_strcpy(pool_type, jcr->pool->pool_type);
195    pm_strcpy(pool_name, jcr->pool->hdr.name);
196    bash_spaces(pool_type);
197    bash_spaces(pool_name);
198
199    /*
200     * We have two loops here. The first comes from the 
201     *  Storage = associated with the Job, and we need 
202     *  to attach to each one.
203     * The inner loop loops over all the alternative devices
204     *  associated with each Storage. It selects the first
205     *  available one.
206     *
207     * Note, the outer loop is not yet implemented.
208     */
209 // foreach_alist(storage, store) {
210       storage = (STORE *)store->first();
211       DEVICE *dev;
212       /* Loop over alternative storages until one is OK */
213       foreach_alist(dev, storage->device) {
214          pm_strcpy(device_name, dev->hdr.name);
215          pm_strcpy(media_type, dev->MediaType);
216          bash_spaces(device_name);
217          bash_spaces(media_type);
218          bnet_fsend(sd, use_device, device_name.c_str(),
219                     media_type.c_str(), pool_name.c_str(), pool_type.c_str(),
220                     append);
221          Dmsg1(200, ">stored: %s", sd->msg);
222          if (bget_dirmsg(sd) > 0) {
223             Dmsg1(400, "<stored: %s", sd->msg);
224             /* ****FIXME**** save actual device name */
225             ok = sscanf(sd->msg, OK_device, device_name.c_str()) == 1;
226             if (ok) {
227                break;
228             }
229          } else {
230             POOL_MEM err_msg;
231             ok = false;
232             pm_strcpy(err_msg, sd->msg); /* save message */
233             Jmsg(jcr, M_WARNING, 0, _("\n"
234                "     Storage daemon didn't accept Device \"%s\" because:\n     %s"),
235                device_name.c_str(), err_msg.c_str()/* sd->msg */);
236          }
237       }
238 //    if (!ok) {
239 //       break;
240 //    }
241 // }
242    if (ok) {
243       ok = bnet_fsend(sd, "run");
244    }
245    return ok;
246 }
247
248 /*
249  * Start a thread to handle Storage daemon messages and
250  *  Catalog requests.
251  */
252 int start_storage_daemon_message_thread(JCR *jcr)
253 {
254    int status;
255    pthread_t thid;
256
257    P(jcr->mutex);
258    jcr->use_count++;                  /* mark in use by msg thread */
259    jcr->sd_msg_thread_done = false;
260    jcr->SD_msg_chan = 0;
261    V(jcr->mutex);
262    Dmsg0(100, "Start SD msg_thread.\n");
263    if ((status=pthread_create(&thid, NULL, msg_thread, (void *)jcr)) != 0) {
264       berrno be;
265       Jmsg1(jcr, M_ABORT, 0, _("Cannot create message thread: %s\n"), be.strerror(status));
266    }
267    Dmsg0(100, "SD msg_thread started.\n");
268    /* Wait for thread to start */
269    while (jcr->SD_msg_chan == 0) {
270       bmicrosleep(0, 50);
271    }
272    return 1;
273 }
274
275 extern "C" void msg_thread_cleanup(void *arg)
276 {
277    JCR *jcr = (JCR *)arg;
278    Dmsg0(200, "End msg_thread\n");
279    db_end_transaction(jcr, jcr->db);       /* terminate any open transaction */
280    P(jcr->mutex);
281    jcr->sd_msg_thread_done = true;
282    pthread_cond_broadcast(&jcr->term_wait); /* wakeup any waiting threads */
283    jcr->SD_msg_chan = 0;
284    V(jcr->mutex);
285    free_jcr(jcr);                     /* release jcr */
286 }
287
288 /*
289  * Handle the message channel (i.e. requests from the
290  *  Storage daemon).
291  * Note, we are running in a separate thread.
292  */
293 extern "C" void *msg_thread(void *arg)
294 {
295    JCR *jcr = (JCR *)arg;
296    BSOCK *sd;
297    int JobStatus;
298    char Job[MAX_NAME_LENGTH];
299    uint32_t JobFiles;
300    uint64_t JobBytes;
301    int stat;
302
303    pthread_detach(pthread_self());
304    jcr->SD_msg_chan = pthread_self();
305    pthread_cleanup_push(msg_thread_cleanup, arg);
306    sd = jcr->store_bsock;
307
308    /* Read the Storage daemon's output.
309     */
310    Dmsg0(100, "Start msg_thread loop\n");
311    while ((stat=bget_dirmsg(sd)) >= 0) {
312       Dmsg1(200, "<stored: %s", sd->msg);
313       if (sscanf(sd->msg, Job_start, &Job) == 1) {
314          continue;
315       }
316       if (sscanf(sd->msg, Job_end, &Job, &JobStatus, &JobFiles,
317                  &JobBytes) == 4) {
318          jcr->SDJobStatus = JobStatus; /* termination status */
319          jcr->SDJobFiles = JobFiles;
320          jcr->SDJobBytes = JobBytes;
321          break;
322       }
323    }
324    if (is_bnet_error(sd)) {
325       jcr->SDJobStatus = JS_ErrorTerminated;
326    }
327    pthread_cleanup_pop(1);
328    return NULL;
329 }
330
331 void wait_for_storage_daemon_termination(JCR *jcr)
332 {
333    int cancel_count = 0;
334    /* Now wait for Storage daemon to terminate our message thread */
335    set_jcr_job_status(jcr, JS_WaitSD);
336    P(jcr->mutex);
337    while (!jcr->sd_msg_thread_done) {
338       struct timeval tv;
339       struct timezone tz;
340       struct timespec timeout;
341
342       gettimeofday(&tv, &tz);
343       timeout.tv_nsec = 0;
344       timeout.tv_sec = tv.tv_sec + 10; /* wait 10 seconds */
345       Dmsg0(300, "I'm waiting for message thread termination.\n");
346       pthread_cond_timedwait(&jcr->term_wait, &jcr->mutex, &timeout);
347       if (job_canceled(jcr)) {
348          cancel_count++;
349       }
350       /* Give SD 30 seconds to clean up after cancel */
351       if (cancel_count == 3) {
352          break;
353       }
354    }
355    V(jcr->mutex);
356    set_jcr_job_status(jcr, JS_Terminated);
357 }
358
359
360 #define MAX_TRIES 30
361 #define WAIT_TIME 2
362 extern "C" void *device_thread(void *arg)
363 {
364    int i;
365    JCR *jcr;
366    DEVICE *dev;
367
368
369    pthread_detach(pthread_self());
370    jcr = new_control_jcr("*DeviceInit*", JT_SYSTEM);
371    for (i=0; i < MAX_TRIES; i++) {
372       if (!connect_to_storage_daemon(jcr, 10, 30, 1)) {
373          Dmsg0(000, "Failed connecting to SD.\n");
374          continue;
375       }
376       LockRes();
377       foreach_res(dev, R_DEVICE) {
378          if (!update_device_res(jcr, dev)) {
379             Dmsg1(900, "Error updating device=%s\n", dev->hdr.name);
380          } else {
381             Dmsg1(900, "Updated Device=%s\n", dev->hdr.name);
382          }
383       }
384       UnlockRes();
385       bnet_close(jcr->store_bsock);
386       jcr->store_bsock = NULL;
387       break;
388
389    }
390    free_jcr(jcr);
391    return NULL;
392 }
393
394 /*
395  * Start a thread to handle getting Device resource information
396  *  from SD. This is called once at startup of the Director.
397  */
398 void init_device_resources()
399 {
400    int status;
401    pthread_t thid;
402
403    Dmsg0(100, "Start Device thread.\n");
404    if ((status=pthread_create(&thid, NULL, device_thread, NULL)) != 0) {
405       berrno be;
406       Jmsg1(NULL, M_ABORT, 0, _("Cannot create message thread: %s\n"), be.strerror(status));
407    }
408 }