]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/catreq.c
Fix since truncation bug; lock db during recycling; new update command line args...
[bacula/bacula] / bacula / src / dird / catreq.c
1 /*
2  *
3  *   Bacula Director -- catreq.c -- handles the message channel
4  *    catalog request from the Storage daemon.
5  *
6  *     Kern Sibbald, March MMI
7  *
8  *    This routine runs as a thread and must be thread reentrant.
9  *
10  *  Basic tasks done here:
11  *      Handle Catalog services.
12  *
13  *   Version $Id$
14  */
15 /*
16    Copyright (C) 2000, 2001, 2002 Kern Sibbald and John Walker
17
18    This program is free software; you can redistribute it and/or
19    modify it under the terms of the GNU General Public License as
20    published by the Free Software Foundation; either version 2 of
21    the License, or (at your option) any later version.
22
23    This program is distributed in the hope that it will be useful,
24    but WITHOUT ANY WARRANTY; without even the implied warranty of
25    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
26    General Public License for more details.
27
28    You should have received a copy of the GNU General Public
29    License along with this program; if not, write to the Free
30    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
31    MA 02111-1307, USA.
32
33  */
34
35 #include "bacula.h"
36 #include "dird.h"
37
38 /*
39  * Handle catalog request
40  *  For now, we simply return next Volume to be used
41  */
42
43 /* Requests from the Storage daemon */
44 static char Find_media[] = "CatReq Job=%127s FindMedia=%d\n";
45 static char Get_Vol_Info[] = "CatReq Job=%127s GetVolInfo VolName=%127s write=%d\n";
46
47 static char Update_media[] = "CatReq Job=%127s UpdateMedia VolName=%s\
48  VolJobs=%u VolFiles=%u VolBlocks=%u VolBytes=%" lld " VolMounts=%u\
49  VolErrors=%u VolWrites=%u MaxVolBytes=%" lld " EndTime=%d VolStatus=%10s\
50  Slot=%d relabel=%d\n";
51
52 static char Create_job_media[] = "CatReq Job=%127s CreateJobMedia \
53  FirstIndex=%u LastIndex=%u StartFile=%u EndFile=%u \
54  StartBlock=%u EndBlock=%u\n";
55
56
57 /* Responses  sent to Storage daemon */
58 static char OK_media[] = "1000 OK VolName=%s VolJobs=%u VolFiles=%u\
59  VolBlocks=%u VolBytes=%s VolMounts=%u VolErrors=%u VolWrites=%u\
60  MaxVolBytes=%s VolCapacityBytes=%s VolStatus=%s Slot=%d\
61  MaxVolJobs=%u MaxVolFiles=%u\n";
62
63 static char OK_update[] = "1000 OK UpdateMedia\n";
64
65 /* static char FileAttributes[] = "UpdCat Job=%127s FileAttributes "; */
66
67
68 void catalog_request(JCR *jcr, BSOCK *bs, char *msg)
69 {
70    MEDIA_DBR mr, sdmr; 
71    JOBMEDIA_DBR jm;
72    char Job[MAX_NAME_LENGTH];
73    int index, ok, relabel, writing, retry = 0;
74    POOLMEM *omsg;
75
76    memset(&mr, 0, sizeof(mr));
77    memset(&sdmr, 0, sizeof(sdmr));
78    memset(&jm, 0, sizeof(jm));
79
80    /*
81     * Request to find next appendable Volume for this Job
82     */
83    Dmsg1(200, "catreq %s", bs->msg);
84    if (sscanf(bs->msg, Find_media, &Job, &index) == 2) {
85       mr.PoolId = jcr->PoolId;
86       bstrncpy(mr.MediaType, jcr->store->media_type, sizeof(mr.MediaType));
87       Dmsg2(120, "CatReq FindMedia: Id=%d, MediaType=%s\n",
88          mr.PoolId, mr.MediaType);
89       /*
90        * Find the Next Volume for Append
91        */
92       db_lock(jcr->db);
93       for ( ;; ) {
94          strcpy(mr.VolStatus, "Append");  /* want only appendable volumes */
95          ok = db_find_next_volume(jcr, jcr->db, index, &mr);  
96          Dmsg2(100, "catreq after find_next_vol ok=%d FW=%d\n", ok, mr.FirstWritten);
97          if (!ok) {
98             /* Well, try finding recycled volumes */
99             ok = find_recycled_volume(jcr, &mr);
100             Dmsg2(100, "find_recycled_volume %d FW=%d\n", ok, mr.FirstWritten);
101             if (!ok) {
102                prune_volumes(jcr);  
103                ok = recycle_oldest_purged_volume(jcr, &mr);
104                Dmsg2(200, "find_recycled_volume2 %d FW=%d\n", ok, mr.FirstWritten);
105                if (!ok) {
106                   /* See if we can create a new Volume */
107                   ok = newVolume(jcr, &mr);
108                }
109             }
110
111             if (!ok && jcr->pool->purge_oldest_volume) {
112                Dmsg1(200, "No next volume found. PurgeOldest=%d\n",
113                    jcr->pool->purge_oldest_volume);
114                /* Find oldest volume to recycle */
115                ok = db_find_next_volume(jcr, jcr->db, -1, &mr);
116                Dmsg1(400, "Find oldest=%d\n", ok);
117                if (ok) {
118                   UAContext *ua;
119                   Dmsg0(400, "Try purge.\n");
120                   /* Try to purge oldest volume */
121                   ua = new_ua_context(jcr);
122                   Jmsg(jcr, M_INFO, 0, _("Purging oldest volume \"%s\"\n"), mr.VolumeName);
123                   ok = purge_jobs_from_volume(ua, &mr);
124                   free_ua_context(ua);
125                   if (ok) {
126                      ok = recycle_oldest_purged_volume(jcr, &mr);
127                      Dmsg1(400, "Recycle after recycle oldest=%d\n", ok);
128                   }
129                }
130             }
131          }
132          /* Check if use duration applies, then if it has expired */
133          Dmsg2(100, "VolJobs=%d FirstWritten=%d\n", mr.VolJobs, mr.FirstWritten);
134          if (ok && mr.VolJobs > 0 && mr.VolUseDuration > 0 && 
135               strcmp(mr.VolStatus, "Append") == 0) {
136             utime_t now = time(NULL);
137             if (mr.VolUseDuration <= (now - mr.FirstWritten)) {
138                ok = FALSE;
139                Dmsg4(100, "Duration=%d now=%d start=%d now-start=%d\n",
140                   (int)mr.VolUseDuration, (int)now, (int)mr.FirstWritten, 
141                   (int)(now-mr.FirstWritten));
142                Jmsg(jcr, M_INFO, 0, _("Max configured use duration exceeded. "       
143                   "Marking Volume \"%s\" as Used.\n"), mr.VolumeName);
144                strcpy(mr.VolStatus, "Used");  /* yes, mark as used */
145                if (!db_update_media_record(jcr, jcr->db, &mr)) {
146                   Jmsg(jcr, M_ERROR, 0, _("Catalog error updating volume \"%s\". ERR=%s"),
147                        mr.VolumeName, db_strerror(jcr->db));
148                }           
149                if (retry++ < 200) {            /* sanity check */
150                   continue;                    /* try again from the top */
151                } else {
152                   Jmsg(jcr, M_ERROR, 0, _(
153 "We seem to be looping trying to find the next volume. I give up.\n"));
154                }
155             }
156          }
157          break;
158       } /* end for loop */
159       db_unlock(jcr->db);
160
161       /*
162        * Send Find Media response to Storage daemon 
163        */
164       if (ok) {
165          char ed1[50], ed2[50], ed3[50];
166          jcr->MediaId = mr.MediaId;
167          pm_strcpy(&jcr->VolumeName, mr.VolumeName);
168          bash_spaces(mr.VolumeName);
169          bnet_fsend(bs, OK_media, mr.VolumeName, mr.VolJobs,
170             mr.VolFiles, mr.VolBlocks, edit_uint64(mr.VolBytes, ed1),
171             mr.VolMounts, mr.VolErrors, mr.VolWrites, 
172             edit_uint64(mr.MaxVolBytes, ed2), 
173             edit_uint64(mr.VolCapacityBytes, ed3),
174             mr.VolStatus, mr.Slot, mr.MaxVolJobs, mr.MaxVolFiles);
175          Dmsg2(100, "Find media for %s: %s", jcr->Job, bs->msg);
176       } else {
177          bnet_fsend(bs, "1901 No Media.\n");
178       }
179
180    /* 
181     * Request to find specific Volume information
182     */
183    } else if (sscanf(bs->msg, Get_Vol_Info, &Job, &mr.VolumeName, &writing) == 3) {
184       Dmsg1(400, "CatReq GetVolInfo Vol=%s\n", mr.VolumeName);
185       /*
186        * Find the Volume
187        */
188       unbash_spaces(mr.VolumeName);
189       if (db_get_media_record(jcr, jcr->db, &mr)) {
190          int VolSuitable = 0;
191          char *reason = "";           /* detailed reason for rejection */
192          jcr->MediaId = mr.MediaId;
193          Dmsg1(120, "VolumeInfo MediaId=%d\n", jcr->MediaId);
194          pm_strcpy(&jcr->VolumeName, mr.VolumeName);
195          if (!writing) {
196             VolSuitable = 1;          /* accept anything for read */
197          } else {
198             /* 
199              * SD wants to write this Volume, so make
200              *   sure it is suitable for this job, i.e.
201              *   Pool matches, and it is either Append or Recycle 
202              *   and Media Type matches and Pool allows any volume.
203              */
204             if (mr.PoolId != jcr->PoolId) {
205                reason = "not in Pool";
206             } else if (strcmp(mr.VolStatus, "Append") != 0 &&
207                        strcmp(mr.VolStatus, "Recycle") != 0) {
208                reason = "not Append or Recycle";
209             } else if (strcmp(mr.MediaType, jcr->store->media_type) != 0) {
210                reason = "not correct MediaType";
211             } else if (!jcr->pool->accept_any_volume) {
212                reason = "Volume not in sequence";
213             } else {
214                VolSuitable = 1;
215             }
216          }
217          if (VolSuitable) {
218             char ed1[50], ed2[50], ed3[50];
219             /*
220              * Send Find Media response to Storage daemon 
221              */
222             bash_spaces(mr.VolumeName);
223             bnet_fsend(bs, OK_media, mr.VolumeName, mr.VolJobs,
224                mr.VolFiles, mr.VolBlocks, edit_uint64(mr.VolBytes, ed1),
225                mr.VolMounts, mr.VolErrors, mr.VolWrites, 
226                edit_uint64(mr.MaxVolBytes, ed2), 
227                edit_uint64(mr.VolCapacityBytes, ed3),
228                mr.VolStatus, mr.Slot, mr.MaxVolJobs, mr.MaxVolFiles);
229             Dmsg2(100, "Vol Info for %s: %s", jcr->Job, bs->msg);
230          } else { 
231             /* Not suitable volume */
232             bnet_fsend(bs, "1998 Volume \"%s\" %s.\n",
233                mr.VolumeName, reason);
234          }
235
236       } else {
237          bnet_fsend(bs, "1997 Volume \"%s\" not in catalog.\n", mr.VolumeName);
238       }
239
240    
241    /*
242     * Request to update Media record. Comes typically at the end
243     *  of a Storage daemon Job Session
244     */
245    } else if (sscanf(bs->msg, Update_media, &Job, &sdmr.VolumeName, &sdmr.VolJobs,
246       &sdmr.VolFiles, &sdmr.VolBlocks, &sdmr.VolBytes, &sdmr.VolMounts, &sdmr.VolErrors,
247       &sdmr.VolWrites, &sdmr.MaxVolBytes, &sdmr.LastWritten, &sdmr.VolStatus, 
248       &sdmr.Slot, &relabel) == 14) {
249
250       db_lock(jcr->db);
251       Dmsg3(400, "Update media %s oldStat=%s newStat=%s\n", sdmr.VolumeName,
252          mr.VolStatus, sdmr.VolStatus);
253       bstrncpy(mr.VolumeName, sdmr.VolumeName, sizeof(mr.VolumeName)); /* copy Volume name */
254       unbash_spaces(mr.VolumeName);
255       if (!db_get_media_record(jcr, jcr->db, &mr)) {
256          Jmsg(jcr, M_ERROR, 0, _("Unable to get Media record for Volume %s: ERR=%s\n"),
257               mr.VolumeName, db_strerror(jcr->db));
258          bnet_fsend(bs, "1991 Catalog Request failed: %s", db_strerror(jcr->db));
259          db_unlock(jcr->db);
260          return;
261       }
262       /* Set first written time if this is first job */
263       if (mr.VolJobs == 0 || sdmr.VolJobs == 1) {
264          mr.FirstWritten = jcr->start_time;   /* use Job start time as first write */
265       }
266       Dmsg2(200, "Update media: BefVolJobs=%u After=%u\n", mr.VolJobs, sdmr.VolJobs);
267       /* Copy updated values to original media record */
268       mr.VolJobs     = sdmr.VolJobs;
269       mr.VolFiles    = sdmr.VolFiles;
270       mr.VolBlocks   = sdmr.VolBlocks;
271       mr.VolBytes    = sdmr.VolBytes;
272       mr.VolMounts   = sdmr.VolMounts;
273       mr.VolErrors   = sdmr.VolErrors;
274       mr.VolWrites   = sdmr.VolWrites;
275       mr.LastWritten = sdmr.LastWritten;
276       bstrncpy(mr.VolStatus, sdmr.VolStatus, sizeof(mr.VolStatus));
277       mr.Slot = sdmr.Slot;
278
279       /*     
280        * Update Media Record
281        */
282
283       /* Check limits and expirations if "Append" and not a relable request */
284       if (strcmp(mr.VolStatus, "Append") == 0 && !relabel) {
285          /* First handle Max Volume Bytes */
286          if ((mr.MaxVolBytes > 0 && mr.VolBytes >= mr.MaxVolBytes)) {
287             Jmsg(jcr, M_INFO, 0, _("Max Volume bytes exceeded. "             
288                 "Marking Volume \"%s\" as Full.\n"), mr.VolumeName);
289             strcpy(mr.VolStatus, "Full");
290
291          /* Now see if Volume should only be used once */
292          } else if (mr.VolBytes > 0 && jcr->pool->use_volume_once) {
293             Jmsg(jcr, M_INFO, 0, _("Volume used once. "             
294                 "Marking Volume \"%s\" as Used.\n"), mr.VolumeName);
295             strcpy(mr.VolStatus, "Used");
296
297          /* Now see if Max Jobs written to volume */
298          } else if (mr.MaxVolJobs > 0 && mr.MaxVolJobs <= mr.VolJobs) {
299             Jmsg(jcr, M_INFO, 0, _("Max Volume jobs exceeded. "       
300                 "Marking Volume \"%s\" as Used.\n"), mr.VolumeName);
301             strcpy(mr.VolStatus, "Used");
302
303          /* Now see if Max Files written to volume */
304          } else if (mr.MaxVolFiles > 0 && mr.MaxVolFiles <= mr.VolFiles) {
305             Jmsg(jcr, M_INFO, 0, _("Max Volume files exceeded. "       
306                 "Marking Volume \"%s\" as Used.\n"), mr.VolumeName);
307             strcpy(mr.VolStatus, "Used");
308
309          /* Finally, check Use duration expiration */
310          } else if (mr.VolUseDuration > 0) {
311             utime_t now = time(NULL);
312             /* See if Vol Use has expired */
313             if (mr.VolUseDuration <= (now - mr.FirstWritten)) {
314                Jmsg(jcr, M_INFO, 0, _("Max configured use duration exceeded. "       
315                   "Marking Volume \"%s\"as Used.\n"), mr.VolumeName);
316                strcpy(mr.VolStatus, "Used");  /* yes, mark as used */
317             }
318          }
319       }
320       Dmsg2(200, "db_update_media_record. Stat=%s Vol=%s\n", mr.VolStatus, mr.VolumeName);
321       if (db_update_media_record(jcr, jcr->db, &mr)) {
322          bnet_fsend(bs, OK_update);
323          Dmsg0(190, "send OK\n");
324       } else {
325          Jmsg(jcr, M_ERROR, 0, _("Catalog error updating Media record. %s"),
326             db_strerror(jcr->db));
327          bnet_fsend(bs, "1992 Update Media error\n");
328          Dmsg0(190, "send error\n");
329       }
330       db_unlock(jcr->db);
331
332    /*
333     * Request to create a JobMedia record
334     */
335    } else if (sscanf(bs->msg, Create_job_media, &Job,
336       &jm.FirstIndex, &jm.LastIndex, &jm.StartFile, &jm.EndFile,
337       &jm.StartBlock, &jm.EndBlock) == 7) {
338
339       jm.JobId = jcr->JobId;
340       jm.MediaId = jcr->MediaId;
341       Dmsg6(100, "create_jobmedia JobId=%d MediaId=%d SF=%d EF=%d FI=%d LI=%d\n",
342          jm.JobId, jm.MediaId, jm.StartFile, jm.EndFile, jm.FirstIndex, jm.LastIndex);
343       if (!db_create_jobmedia_record(jcr, jcr->db, &jm)) {
344          Jmsg(jcr, M_ERROR, 0, _("Catalog error creating JobMedia record. %s"),
345             db_strerror(jcr->db));
346          bnet_fsend(bs, "1991 Update JobMedia error\n");
347       } else {
348          Dmsg0(100, "JobMedia record created\n");
349          bnet_fsend(bs, OK_update);
350       }
351
352    } else {
353       omsg = get_memory(bs->msglen+1);
354       pm_strcpy(&omsg, bs->msg);
355       bnet_fsend(bs, "1990 Invalid Catalog Request: %s", omsg);    
356       Jmsg1(jcr, M_ERROR, 0, _("Invalid Catalog request: %s"), omsg);
357       free_memory(omsg);
358    }
359    Dmsg1(120, ">CatReq response: %s", bs->msg);
360    Dmsg1(200, "Leave catreq jcr 0x%x\n", jcr);
361    return;
362 }
363
364 /*
365  * Update File Attributes in the catalog with data
366  *  sent by the Storage daemon.  Note, we receive the whole
367  *  attribute record, but we select out only the stat packet,
368  *  VolSessionId, VolSessionTime, FileIndex, and file name 
369  *  to store in the catalog.
370  */
371 void catalog_update(JCR *jcr, BSOCK *bs, char *msg)
372 {
373    unser_declare;
374    uint32_t VolSessionId, VolSessionTime;
375    int32_t Stream;
376    uint32_t FileIndex;
377    uint32_t data_len;
378    char *p = bs->msg;
379    int len;
380    char *fname, *attr;
381    ATTR_DBR ar;
382
383    if (!jcr->pool->catalog_files) {
384       return;
385    }
386    db_start_transaction(jcr, jcr->db);     /* start transaction if not already open */
387    skip_nonspaces(&p);                /* UpdCat */
388    skip_spaces(&p);
389    skip_nonspaces(&p);                /* Job=nnn */
390    skip_spaces(&p);
391    skip_nonspaces(&p);                /* FileAttributes */
392    p += 1;
393    unser_begin(p, 0);
394    unser_uint32(VolSessionId);
395    unser_uint32(VolSessionTime);
396    unser_int32(FileIndex);
397    unser_int32(Stream);
398    unser_uint32(data_len);
399    p += unser_length(p);
400
401    Dmsg1(99, "UpdCat msg=%s\n", bs->msg);
402    Dmsg5(99, "UpdCat VolSessId=%d VolSessT=%d FI=%d Strm=%d data_len=%d\n",
403       VolSessionId, VolSessionTime, FileIndex, Stream, data_len);
404
405    if (Stream == STREAM_UNIX_ATTRIBUTES || Stream == STREAM_UNIX_ATTRIBUTES_EX) {
406       skip_nonspaces(&p);             /* skip FileIndex */
407       skip_spaces(&p);
408       skip_nonspaces(&p);             /* skip FileType */
409       skip_spaces(&p);
410       fname = p;
411       len = strlen(fname);        /* length before attributes */
412       attr = &fname[len+1];
413
414       Dmsg2(109, "dird<stored: stream=%d %s\n", Stream, fname);
415       Dmsg1(109, "dird<stored: attr=%s\n", attr);
416       ar.attr = attr; 
417       ar.fname = fname;
418       ar.FileIndex = FileIndex;
419       ar.Stream = Stream;
420       ar.link = NULL;
421       ar.JobId = jcr->JobId;
422
423       Dmsg2(111, "dird<filed: stream=%d %s\n", Stream, fname);
424       Dmsg1(120, "dird<filed: attr=%s\n", attr);
425
426       if (!db_create_file_attributes_record(jcr, jcr->db, &ar)) {
427          Jmsg1(jcr, M_FATAL, 0, _("Attribute create error. %s"), db_strerror(jcr->db));
428       }
429       /* Save values for SIG update */
430       jcr->FileId = ar.FileId;
431       jcr->FileIndex = FileIndex;
432    } else if (Stream == STREAM_MD5_SIGNATURE || Stream == STREAM_SHA1_SIGNATURE) {
433       fname = p;
434       if (jcr->FileIndex != FileIndex) {    
435          Jmsg(jcr, M_WARNING, 0, "Got MD5/SHA1 but not same File as attributes\n");
436       } else {
437          /* Update signature in catalog */
438          char SIGbuf[50];           /* 24 bytes should be enough */
439          int len, type;
440          if (Stream == STREAM_MD5_SIGNATURE) {
441             len = 16;
442             type = MD5_SIG;
443          } else {
444             len = 20;
445             type = SHA1_SIG;
446          }
447          bin_to_base64(SIGbuf, fname, len);
448          Dmsg3(190, "SIGlen=%d SIG=%s type=%d\n", strlen(SIGbuf), SIGbuf, Stream);
449          if (!db_add_SIG_to_file_record(jcr, jcr->db, jcr->FileId, SIGbuf, type)) {
450             Jmsg(jcr, M_ERROR, 0, _("Catalog error updating MD5/SHA1. %s"), 
451                db_strerror(jcr->db));
452          }
453       }
454    }
455 }