]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/catreq.c
dc08a48291cb5ca11b866c9a6cdb27b5c0ec3d5f
[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                         jcr->pool->recycle_oldest_volume)) {
113                Dmsg2(200, "No next volume found. PurgeOldest=%d\n RecyleOldest=%d",
114                    jcr->pool->purge_oldest_volume, jcr->pool->recycle_oldest_volume);
115                /* Find oldest volume to recycle */
116                ok = db_find_next_volume(jcr, jcr->db, -1, &mr);
117                Dmsg1(400, "Find oldest=%d\n", ok);
118                if (ok) {
119                   UAContext *ua;
120                   Dmsg0(400, "Try purge.\n");
121                   /* Try to purge oldest volume */
122                   ua = new_ua_context(jcr);
123                   if (jcr->pool->purge_oldest_volume) {
124                      Jmsg(jcr, M_INFO, 0, _("Purging oldest volume \"%s\"\n"), mr.VolumeName);
125                      ok = purge_jobs_from_volume(ua, &mr);
126                   } else {
127                      Jmsg(jcr, M_INFO, 0, _("Pruning oldest volume \"%s\"\n"), mr.VolumeName);
128                      ok = prune_volume(ua, &mr);
129                   }
130                   free_ua_context(ua);
131                   if (ok) {
132                      ok = recycle_volume(jcr, &mr);
133                      Dmsg1(400, "Recycle after purge oldest=%d\n", ok);
134                   }
135                }
136             }
137          }
138          /* Check if use duration applies, then if it has expired */
139          Dmsg2(100, "VolJobs=%d FirstWritten=%d\n", mr.VolJobs, mr.FirstWritten);
140          if (ok && mr.VolJobs > 0 && mr.VolUseDuration > 0 && 
141               strcmp(mr.VolStatus, "Append") == 0) {
142             utime_t now = time(NULL);
143             if (mr.VolUseDuration <= (now - mr.FirstWritten)) {
144                ok = FALSE;
145                Dmsg4(100, "Duration=%d now=%d start=%d now-start=%d\n",
146                   (int)mr.VolUseDuration, (int)now, (int)mr.FirstWritten, 
147                   (int)(now-mr.FirstWritten));
148                Jmsg(jcr, M_INFO, 0, _("Max configured use duration exceeded. "       
149                   "Marking Volume \"%s\" as Used.\n"), mr.VolumeName);
150                strcpy(mr.VolStatus, "Used");  /* yes, mark as used */
151                if (!db_update_media_record(jcr, jcr->db, &mr)) {
152                   Jmsg(jcr, M_ERROR, 0, _("Catalog error updating volume \"%s\". ERR=%s"),
153                        mr.VolumeName, db_strerror(jcr->db));
154                }           
155                if (retry++ < 200) {            /* sanity check */
156                   continue;                    /* try again from the top */
157                } else {
158                   Jmsg(jcr, M_ERROR, 0, _(
159 "We seem to be looping trying to find the next volume. I give up.\n"));
160                }
161             }
162          }
163          break;
164       } /* end for loop */
165       db_unlock(jcr->db);
166
167       /*
168        * Send Find Media response to Storage daemon 
169        */
170       if (ok) {
171          char ed1[50], ed2[50], ed3[50];
172          jcr->MediaId = mr.MediaId;
173          pm_strcpy(&jcr->VolumeName, mr.VolumeName);
174          bash_spaces(mr.VolumeName);
175          bnet_fsend(bs, OK_media, mr.VolumeName, mr.VolJobs,
176             mr.VolFiles, mr.VolBlocks, edit_uint64(mr.VolBytes, ed1),
177             mr.VolMounts, mr.VolErrors, mr.VolWrites, 
178             edit_uint64(mr.MaxVolBytes, ed2), 
179             edit_uint64(mr.VolCapacityBytes, ed3),
180             mr.VolStatus, mr.Slot, mr.MaxVolJobs, mr.MaxVolFiles);
181          Dmsg2(100, "Find media for %s: %s", jcr->Job, bs->msg);
182       } else {
183          bnet_fsend(bs, "1901 No Media.\n");
184       }
185
186    /* 
187     * Request to find specific Volume information
188     */
189    } else if (sscanf(bs->msg, Get_Vol_Info, &Job, &mr.VolumeName, &writing) == 3) {
190       Dmsg1(400, "CatReq GetVolInfo Vol=%s\n", mr.VolumeName);
191       /*
192        * Find the Volume
193        */
194       unbash_spaces(mr.VolumeName);
195       if (db_get_media_record(jcr, jcr->db, &mr)) {
196          bool VolSuitable = false;
197          char *reason = "";           /* detailed reason for rejection */
198          jcr->MediaId = mr.MediaId;
199          Dmsg1(120, "VolumeInfo MediaId=%d\n", jcr->MediaId);
200          pm_strcpy(&jcr->VolumeName, mr.VolumeName);
201          if (!writing) {
202             VolSuitable = true;        /* accept anything for read */
203          } else {
204             /* 
205              * SD wants to write this Volume, so make
206              *   sure it is suitable for this job, i.e.
207              *   Pool matches, and it is either Append or Recycle 
208              *   and Media Type matches and Pool allows any volume.
209              */
210             if (mr.PoolId != jcr->PoolId) {
211                reason = "not in Pool";
212             } else if (strcmp(mr.VolStatus, "Append") != 0 &&
213                        strcmp(mr.VolStatus, "Recycle") != 0) {
214                reason = "not Append or Recycle";
215                /* XXX nicb start */
216                /* What we're trying to do here is see if the current volume is
217                 * "recycleable" - ie. if we prune all expired jobs off it, is
218                 * it now possible to reuse it for the job that it is currently
219                 * needed for?
220                 */
221                if ((mr.LastWritten + mr.VolRetention) < (utime_t)time(NULL)
222                      && mr.Recycle && jcr->pool->recycle_current_volume   
223                      && (strcmp(mr.VolStatus, "Full") == 0 ||
224                         strcmp(mr.VolStatus, "Used") == 0)) {
225                   /*
226                    * Attempt prune of current volume to see if we can
227                    * recycle it for use.
228                    */
229                   UAContext *ua;
230
231                   reason = "not Append or Recycle (auto recycle failed)";
232
233                   ua = new_ua_context(jcr);
234                   ok = prune_volume(ua, &mr);
235                   free_ua_context(ua);
236
237                   if (ok) {
238                      /* If fully purged, recycle current volume */
239                      if (recycle_volume(jcr, &mr)) {
240                         Jmsg(jcr, M_INFO, 0, "Recycled current "
241                               "volume \"%s\"\n", mr.VolumeName);
242                         VolSuitable = true;
243                      }
244                   }
245                }
246                /* XXX nicb end */
247             } else if (strcmp(mr.MediaType, jcr->store->media_type) != 0) {
248                reason = "not correct MediaType";
249             } else if (!jcr->pool->accept_any_volume) {
250                reason = "Volume not in sequence";
251             } else {
252                VolSuitable = true;
253             }
254          }
255          if (VolSuitable) {
256             char ed1[50], ed2[50], ed3[50];
257             /*
258              * Send Find Media response to Storage daemon 
259              */
260             bash_spaces(mr.VolumeName);
261             bnet_fsend(bs, OK_media, mr.VolumeName, mr.VolJobs,
262                mr.VolFiles, mr.VolBlocks, edit_uint64(mr.VolBytes, ed1),
263                mr.VolMounts, mr.VolErrors, mr.VolWrites, 
264                edit_uint64(mr.MaxVolBytes, ed2), 
265                edit_uint64(mr.VolCapacityBytes, ed3),
266                mr.VolStatus, mr.Slot, mr.MaxVolJobs, mr.MaxVolFiles);
267             Dmsg2(100, "Vol Info for %s: %s", jcr->Job, bs->msg);
268          } else { 
269             /* Not suitable volume */
270             bnet_fsend(bs, "1998 Volume \"%s\" %s.\n",
271                mr.VolumeName, reason);
272          }
273
274       } else {
275          bnet_fsend(bs, "1997 Volume \"%s\" not in catalog.\n", mr.VolumeName);
276       }
277
278    
279    /*
280     * Request to update Media record. Comes typically at the end
281     *  of a Storage daemon Job Session
282     */
283    } else if (sscanf(bs->msg, Update_media, &Job, &sdmr.VolumeName, &sdmr.VolJobs,
284       &sdmr.VolFiles, &sdmr.VolBlocks, &sdmr.VolBytes, &sdmr.VolMounts, &sdmr.VolErrors,
285       &sdmr.VolWrites, &sdmr.MaxVolBytes, &sdmr.LastWritten, &sdmr.VolStatus, 
286       &sdmr.Slot, &relabel) == 14) {
287
288       db_lock(jcr->db);
289       Dmsg3(400, "Update media %s oldStat=%s newStat=%s\n", sdmr.VolumeName,
290          mr.VolStatus, sdmr.VolStatus);
291       bstrncpy(mr.VolumeName, sdmr.VolumeName, sizeof(mr.VolumeName)); /* copy Volume name */
292       unbash_spaces(mr.VolumeName);
293       if (!db_get_media_record(jcr, jcr->db, &mr)) {
294          Jmsg(jcr, M_ERROR, 0, _("Unable to get Media record for Volume %s: ERR=%s\n"),
295               mr.VolumeName, db_strerror(jcr->db));
296          bnet_fsend(bs, "1991 Catalog Request failed: %s", db_strerror(jcr->db));
297          db_unlock(jcr->db);
298          return;
299       }
300       /* Set first written time if this is first job */
301       if (mr.VolJobs == 0 || sdmr.VolJobs == 1) {
302          mr.FirstWritten = jcr->start_time;   /* use Job start time as first write */
303       }
304       Dmsg2(200, "Update media: BefVolJobs=%u After=%u\n", mr.VolJobs, sdmr.VolJobs);
305       /* Copy updated values to original media record */
306       mr.VolJobs     = sdmr.VolJobs;
307       mr.VolFiles    = sdmr.VolFiles;
308       mr.VolBlocks   = sdmr.VolBlocks;
309       mr.VolBytes    = sdmr.VolBytes;
310       mr.VolMounts   = sdmr.VolMounts;
311       mr.VolErrors   = sdmr.VolErrors;
312       mr.VolWrites   = sdmr.VolWrites;
313       mr.LastWritten = sdmr.LastWritten;
314       bstrncpy(mr.VolStatus, sdmr.VolStatus, sizeof(mr.VolStatus));
315       mr.Slot = sdmr.Slot;
316
317       /*     
318        * Update Media Record
319        */
320
321       /* Check limits and expirations if "Append" and not a relable request */
322       if (strcmp(mr.VolStatus, "Append") == 0 && !relabel) {
323          /* First handle Max Volume Bytes */
324          if ((mr.MaxVolBytes > 0 && mr.VolBytes >= mr.MaxVolBytes)) {
325             Jmsg(jcr, M_INFO, 0, _("Max Volume bytes exceeded. "             
326                 "Marking Volume \"%s\" as Full.\n"), mr.VolumeName);
327             strcpy(mr.VolStatus, "Full");
328
329          /* Now see if Volume should only be used once */
330          } else if (mr.VolBytes > 0 && jcr->pool->use_volume_once) {
331             Jmsg(jcr, M_INFO, 0, _("Volume used once. "             
332                 "Marking Volume \"%s\" as Used.\n"), mr.VolumeName);
333             strcpy(mr.VolStatus, "Used");
334
335          /* Now see if Max Jobs written to volume */
336          } else if (mr.MaxVolJobs > 0 && mr.MaxVolJobs <= mr.VolJobs) {
337             Jmsg(jcr, M_INFO, 0, _("Max Volume jobs exceeded. "       
338                 "Marking Volume \"%s\" as Used.\n"), mr.VolumeName);
339             strcpy(mr.VolStatus, "Used");
340
341          /* Now see if Max Files written to volume */
342          } else if (mr.MaxVolFiles > 0 && mr.MaxVolFiles <= mr.VolFiles) {
343             Jmsg(jcr, M_INFO, 0, _("Max Volume files exceeded. "       
344                 "Marking Volume \"%s\" as Used.\n"), mr.VolumeName);
345             strcpy(mr.VolStatus, "Used");
346
347          /* Finally, check Use duration expiration */
348          } else if (mr.VolUseDuration > 0) {
349             utime_t now = time(NULL);
350             /* See if Vol Use has expired */
351             if (mr.VolUseDuration <= (now - mr.FirstWritten)) {
352                Jmsg(jcr, M_INFO, 0, _("Max configured use duration exceeded. "       
353                   "Marking Volume \"%s\"as Used.\n"), mr.VolumeName);
354                strcpy(mr.VolStatus, "Used");  /* yes, mark as used */
355             }
356          }
357       }
358       Dmsg2(200, "db_update_media_record. Stat=%s Vol=%s\n", mr.VolStatus, mr.VolumeName);
359       if (db_update_media_record(jcr, jcr->db, &mr)) {
360          bnet_fsend(bs, OK_update);
361          Dmsg0(190, "send OK\n");
362       } else {
363          Jmsg(jcr, M_ERROR, 0, _("Catalog error updating Media record. %s"),
364             db_strerror(jcr->db));
365          bnet_fsend(bs, "1992 Update Media error\n");
366          Dmsg0(190, "send error\n");
367       }
368       db_unlock(jcr->db);
369
370    /*
371     * Request to create a JobMedia record
372     */
373    } else if (sscanf(bs->msg, Create_job_media, &Job,
374       &jm.FirstIndex, &jm.LastIndex, &jm.StartFile, &jm.EndFile,
375       &jm.StartBlock, &jm.EndBlock) == 7) {
376
377       jm.JobId = jcr->JobId;
378       jm.MediaId = jcr->MediaId;
379       Dmsg6(100, "create_jobmedia JobId=%d MediaId=%d SF=%d EF=%d FI=%d LI=%d\n",
380          jm.JobId, jm.MediaId, jm.StartFile, jm.EndFile, jm.FirstIndex, jm.LastIndex);
381       if (!db_create_jobmedia_record(jcr, jcr->db, &jm)) {
382          Jmsg(jcr, M_ERROR, 0, _("Catalog error creating JobMedia record. %s"),
383             db_strerror(jcr->db));
384          bnet_fsend(bs, "1991 Update JobMedia error\n");
385       } else {
386          Dmsg0(100, "JobMedia record created\n");
387          bnet_fsend(bs, OK_update);
388       }
389
390    } else {
391       omsg = get_memory(bs->msglen+1);
392       pm_strcpy(&omsg, bs->msg);
393       bnet_fsend(bs, "1990 Invalid Catalog Request: %s", omsg);    
394       Jmsg1(jcr, M_ERROR, 0, _("Invalid Catalog request: %s"), omsg);
395       free_memory(omsg);
396    }
397    Dmsg1(120, ">CatReq response: %s", bs->msg);
398    Dmsg1(200, "Leave catreq jcr 0x%x\n", jcr);
399    return;
400 }
401
402 /*
403  * Update File Attributes in the catalog with data
404  *  sent by the Storage daemon.  Note, we receive the whole
405  *  attribute record, but we select out only the stat packet,
406  *  VolSessionId, VolSessionTime, FileIndex, and file name 
407  *  to store in the catalog.
408  */
409 void catalog_update(JCR *jcr, BSOCK *bs, char *msg)
410 {
411    unser_declare;
412    uint32_t VolSessionId, VolSessionTime;
413    int32_t Stream;
414    uint32_t FileIndex;
415    uint32_t data_len;
416    char *p = bs->msg;
417    int len;
418    char *fname, *attr;
419    ATTR_DBR ar;
420
421    if (!jcr->pool->catalog_files) {
422       return;
423    }
424    db_start_transaction(jcr, jcr->db);     /* start transaction if not already open */
425    skip_nonspaces(&p);                /* UpdCat */
426    skip_spaces(&p);
427    skip_nonspaces(&p);                /* Job=nnn */
428    skip_spaces(&p);
429    skip_nonspaces(&p);                /* FileAttributes */
430    p += 1;
431    unser_begin(p, 0);
432    unser_uint32(VolSessionId);
433    unser_uint32(VolSessionTime);
434    unser_int32(FileIndex);
435    unser_int32(Stream);
436    unser_uint32(data_len);
437    p += unser_length(p);
438
439    Dmsg1(99, "UpdCat msg=%s\n", bs->msg);
440    Dmsg5(99, "UpdCat VolSessId=%d VolSessT=%d FI=%d Strm=%d data_len=%d\n",
441       VolSessionId, VolSessionTime, FileIndex, Stream, data_len);
442
443    if (Stream == STREAM_UNIX_ATTRIBUTES || Stream == STREAM_UNIX_ATTRIBUTES_EX) {
444       skip_nonspaces(&p);             /* skip FileIndex */
445       skip_spaces(&p);
446       skip_nonspaces(&p);             /* skip FileType */
447       skip_spaces(&p);
448       fname = p;
449       len = strlen(fname);        /* length before attributes */
450       attr = &fname[len+1];
451
452       Dmsg2(109, "dird<stored: stream=%d %s\n", Stream, fname);
453       Dmsg1(109, "dird<stored: attr=%s\n", attr);
454       ar.attr = attr; 
455       ar.fname = fname;
456       ar.FileIndex = FileIndex;
457       ar.Stream = Stream;
458       ar.link = NULL;
459       ar.JobId = jcr->JobId;
460
461       Dmsg2(111, "dird<filed: stream=%d %s\n", Stream, fname);
462       Dmsg1(120, "dird<filed: attr=%s\n", attr);
463
464       if (!db_create_file_attributes_record(jcr, jcr->db, &ar)) {
465          Jmsg1(jcr, M_FATAL, 0, _("Attribute create error. %s"), db_strerror(jcr->db));
466       }
467       /* Save values for SIG update */
468       jcr->FileId = ar.FileId;
469       jcr->FileIndex = FileIndex;
470    } else if (Stream == STREAM_MD5_SIGNATURE || Stream == STREAM_SHA1_SIGNATURE) {
471       fname = p;
472       if (jcr->FileIndex != FileIndex) {    
473          Jmsg(jcr, M_WARNING, 0, "Got MD5/SHA1 but not same File as attributes\n");
474       } else {
475          /* Update signature in catalog */
476          char SIGbuf[50];           /* 24 bytes should be enough */
477          int len, type;
478          if (Stream == STREAM_MD5_SIGNATURE) {
479             len = 16;
480             type = MD5_SIG;
481          } else {
482             len = 20;
483             type = SHA1_SIG;
484          }
485          bin_to_base64(SIGbuf, fname, len);
486          Dmsg3(190, "SIGlen=%d SIG=%s type=%d\n", strlen(SIGbuf), SIGbuf, Stream);
487          if (!db_add_SIG_to_file_record(jcr, jcr->db, jcr->FileId, SIGbuf, type)) {
488             Jmsg(jcr, M_ERROR, 0, _("Catalog error updating MD5/SHA1. %s"), 
489                db_strerror(jcr->db));
490          }
491       }
492    }
493 }