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