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