]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/ua_cmds.c
Drop old semaphore and workq code
[bacula/bacula] / bacula / src / dird / ua_cmds.c
1 /*
2  *
3  *   Bacula Director -- User Agent Commands
4  *
5  *     Kern Sibbald, September MM
6  *
7  *   Version $Id$
8  */
9
10 /*
11    Copyright (C) 2000-2003 Kern Sibbald and John Walker
12
13    This program is free software; you can redistribute it and/or
14    modify it under the terms of the GNU General Public License as
15    published by the Free Software Foundation; either version 2 of
16    the License, or (at your option) any later version.
17
18    This program is distributed in the hope that it will be useful,
19    but WITHOUT ANY WARRANTY; without even the implied warranty of
20    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21    General Public License for more details.
22
23    You should have received a copy of the GNU General Public
24    License along with this program; if not, write to the Free
25    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
26    MA 02111-1307, USA.
27
28  */
29
30 #include "bacula.h"
31 #include "dird.h"
32
33 /* Imported subroutines */
34
35 /* Imported variables */
36 extern int r_first;
37 extern int r_last;
38 extern struct s_res resources[];
39 extern char my_name[];
40 extern jobq_t job_queue;              /* job queue */
41
42 extern char *list_pool;
43
44 /* Imported functions */
45 extern int statuscmd(UAContext *ua, char *cmd);
46 extern int listcmd(UAContext *ua, char *cmd);
47 extern int llistcmd(UAContext *ua, char *cmd);
48 extern int show_cmd(UAContext *ua, char *cmd);
49 extern int messagescmd(UAContext *ua, char *cmd);
50 extern int autodisplaycmd(UAContext *ua, char *cmd);
51 extern int sqlquerycmd(UAContext *ua, char *cmd);
52 extern int querycmd(UAContext *ua, char *cmd);
53 extern int runcmd(UAContext *ua, char *cmd);
54 extern int retentioncmd(UAContext *ua, char *cmd);
55 extern int prunecmd(UAContext *ua, char *cmd);
56 extern int purgecmd(UAContext *ua, char *cmd);
57 extern int restorecmd(UAContext *ua, char *cmd);
58 extern int label_cmd(UAContext *ua, char *cmd);
59 extern int relabel_cmd(UAContext *ua, char *cmd);
60 extern int update_slots(UAContext *ua);  /* ua_label.c */
61
62 /* Forward referenced functions */
63 static int add_cmd(UAContext *ua, char *cmd),  createcmd(UAContext *ua, char *cmd), cancelcmd(UAContext *ua, char *cmd);
64 static int setdebug_cmd(UAContext *ua, char *cmd);
65 static int var_cmd(UAContext *ua, char *cmd);
66 static int estimate_cmd(UAContext *ua, char *cmd);
67 static int help_cmd(UAContext *ua, char *cmd);
68 static int delete_cmd(UAContext *ua, char *cmd);
69 static int use_cmd(UAContext *ua, char *cmd),  unmount_cmd(UAContext *ua, char *cmd);
70 static int version_cmd(UAContext *ua, char *cmd), automount_cmd(UAContext *ua, char *cmd);
71 static int time_cmd(UAContext *ua, char *cmd);
72 static int update_volume(UAContext *ua);
73 static int update_pool(UAContext *ua);
74 static int delete_volume(UAContext *ua);
75 static int delete_pool(UAContext *ua);
76 static int mount_cmd(UAContext *ua, char *cmd);
77 static int release_cmd(UAContext *ua, char *cmd);
78 static int update_cmd(UAContext *ua, char *cmd);
79 static int wait_cmd(UAContext *ua, char *cmd);
80
81 int quit_cmd(UAContext *ua, char *cmd);
82
83
84 struct cmdstruct { char *key; int (*func)(UAContext *ua, char *cmd); char *help; }; 
85 static struct cmdstruct commands[] = {
86  { N_("add"),        add_cmd,         _("add media to a pool")},
87  { N_("autodisplay"), autodisplaycmd, _("autodisplay [on/off] -- console messages")},
88  { N_("automount"),   automount_cmd,  _("automount [on/off] -- after label")},
89  { N_("cancel"),     cancelcmd,     _("cancel job=nnn -- cancel a job")},
90  { N_("create"),     createcmd,     _("create DB Pool from resource")},  
91  { N_("delete"),     delete_cmd,    _("delete [pool=<pool-name> | media volume=<volume-name>]")},    
92  { N_("estimate"),   estimate_cmd,  _("performs FileSet estimate, listing gives full listing")},
93  { N_("exit"),       quit_cmd,      _("exit = quit")},
94  { N_("help"),       help_cmd,      _("print this command")},
95  { N_("label"),      label_cmd,     _("label a tape")},
96  { N_("list"),       listcmd,       _("list [pools | jobs | jobtotals | media <pool> | files job=<nn>]; from catalog")},
97  { N_("llist"),      llistcmd,      _("full or long list like list command")},
98  { N_("messages"),   messagescmd,   _("messages")},
99  { N_("mount"),      mount_cmd,     _("mount <storage-name>")},
100  { N_("prune"),      prunecmd,      _("prune expired records from catalog")},
101  { N_("purge"),      purgecmd,      _("purge records from catalog")},
102  { N_("query"),      querycmd,      _("query catalog")},
103  { N_("quit"),       quit_cmd,      _("quit")},
104  { N_("relabel"),    relabel_cmd,   _("relabel a tape")},
105  { N_("release"),    release_cmd,   _("release <storage-name>")},
106  { N_("restore"),    restorecmd,    _("restore files")},
107  { N_("run"),        runcmd,        _("run <job-name>")},
108  { N_("setdebug"),   setdebug_cmd,  _("sets debug level")},
109  { N_("show"),       show_cmd,      _("show (resource records) [jobs | pools | ... | all]")},
110  { N_("sqlquery"),   sqlquerycmd,   _("use SQL to query catalog")}, 
111  { N_("status"),     statuscmd,     _("status [storage | client]=<name>")},
112  { N_("time"),       time_cmd,      _("print current time")},
113  { N_("unmount"),    unmount_cmd,   _("unmount <storage-name>")},
114  { N_("update"),     update_cmd,    _("update Volume or Pool")},
115  { N_("use"),        use_cmd,       _("use catalog xxx")},
116  { N_("var"),        var_cmd,       _("does variable expansion")},
117  { N_("version"),    version_cmd,   _("print Director version")},
118  { N_("wait"),       wait_cmd,      _("wait until no jobs are running")},
119              };
120 #define comsize (sizeof(commands)/sizeof(struct cmdstruct))
121
122 /*
123  * Execute a command from the UA
124  */
125 int do_a_command(UAContext *ua, char *cmd)
126 {
127    unsigned int i;
128    int len, stat;
129    int found;
130
131    found = 0;
132    stat = 1;
133
134    Dmsg1(120, "Command: %s\n", ua->UA_sock->msg);
135    if (ua->argc == 0) {
136       return 1;
137    }
138
139    len = strlen(ua->argk[0]);
140    for (i=0; i<comsize; i++) {     /* search for command */
141       if (strncasecmp(ua->argk[0],  _(commands[i].key), len) == 0) {
142          stat = (*commands[i].func)(ua, cmd);   /* go execute command */
143          found = 1;
144          break;
145       }
146    }
147    if (!found) {
148       pm_strcat(&ua->UA_sock->msg, _(": is an illegal command\n"));
149       ua->UA_sock->msglen = strlen(ua->UA_sock->msg);
150       bnet_send(ua->UA_sock);
151    }
152    return stat;
153 }
154
155 /*
156  * This is a common routine used to stuff the Pool DB record defaults
157  *   into the Media DB record just before creating a media (Volume) 
158  *   record.
159  */
160 void set_pool_dbr_defaults_in_media_dbr(MEDIA_DBR *mr, POOL_DBR *pr)
161 {
162    mr->PoolId = pr->PoolId;
163    strcpy(mr->VolStatus, "Append");
164    mr->Recycle = pr->Recycle;
165    mr->VolRetention = pr->VolRetention;
166    mr->VolUseDuration = pr->VolUseDuration;
167    mr->MaxVolJobs = pr->MaxVolJobs;
168    mr->MaxVolFiles = pr->MaxVolFiles;
169    mr->MaxVolBytes = pr->MaxVolBytes;
170 }
171
172
173 /*
174  *  Add Volumes to an existing Pool
175  */
176 static int add_cmd(UAContext *ua, char *cmd) 
177 {
178    POOL_DBR pr;
179    MEDIA_DBR mr;
180    int num, i, max, startnum;
181    int first_id = 0;
182    char name[MAX_NAME_LENGTH];
183    STORE *store;
184    int slot = 0;
185
186    bsendmsg(ua, _(
187 "You probably don't want to be using this command since it\n"
188 "creates database records without labeling the Volumes.\n"
189 "You probably want to use the \"label\" command.\n\n"));
190
191    if (!open_db(ua)) {
192       return 1;
193    }
194
195    memset(&pr, 0, sizeof(pr));
196    memset(&mr, 0, sizeof(mr));
197
198    if (!get_pool_dbr(ua, &pr)) {
199       return 1;
200    }
201
202    Dmsg4(120, "id=%d Num=%d Max=%d type=%s\n", pr.PoolId, pr.NumVols,
203       pr.MaxVols, pr.PoolType);
204
205    while (pr.MaxVols > 0 && pr.NumVols >= pr.MaxVols) {
206       bsendmsg(ua, _("Pool already has maximum volumes = %d\n"), pr.MaxVols);
207       for (;;) {
208          if (!get_pint(ua, _("Enter new maximum (zero for unlimited): "))) {
209             return 1;
210          }
211          pr.MaxVols = ua->pint32_val;
212       }
213    }
214
215    /* Get media type */
216    if ((store = get_storage_resource(ua, 0)) != NULL) {
217       bstrncpy(mr.MediaType, store->media_type, sizeof(mr.MediaType));
218    } else if (!get_media_type(ua, mr.MediaType, sizeof(mr.MediaType))) {
219       return 1;
220    }
221       
222    if (pr.MaxVols == 0) {
223       max = 1000;
224    } else {
225       max = pr.MaxVols - pr.NumVols;
226    }
227    for (;;) {
228       char buf[100]; 
229       bsnprintf(buf, sizeof(buf), _("Enter number of Volumes to create. 0=>fixed name. Max=%d: "), max);
230       if (!get_pint(ua, buf)) {
231          return 1;
232       }
233       num = ua->pint32_val;
234       if (num < 0 || num > max) {
235          bsendmsg(ua, _("The number must be between 0 and %d\n"), max);
236          continue;
237       }
238       break;
239    }
240 getVolName:
241    if (num == 0) {
242       if (!get_cmd(ua, _("Enter Volume name: "))) {
243          return 1;
244       }
245    } else {
246       if (!get_cmd(ua, _("Enter base volume name: "))) {
247          return 1;
248       }
249    }
250    /* Don't allow | in Volume name because it is the volume separator character */
251    if (!is_volume_name_legal(ua, ua->cmd)) {
252       goto getVolName;
253    }
254    if (strlen(ua->cmd) >= MAX_NAME_LENGTH-10) {
255       bsendmsg(ua, _("Volume name too long.\n"));
256       goto getVolName;
257    }
258    if (strlen(ua->cmd) == 0) {
259       bsendmsg(ua, _("Volume name must be at least one character long.\n"));
260       goto getVolName;
261    }
262
263    bstrncpy(name, ua->cmd, sizeof(name));
264    if (num > 0) {
265       strcat(name, "%04d");
266
267       for (;;) {
268          if (!get_pint(ua, _("Enter the starting number: "))) {
269             return 1;
270          }
271          startnum = ua->pint32_val;
272          if (startnum < 1) {
273             bsendmsg(ua, _("Start number must be greater than zero.\n"));
274             continue;
275          }
276          break;
277       }
278    } else {
279       startnum = 1;
280       num = 1;
281    }
282
283    if (store && store->autochanger) {
284       if (!get_pint(ua, _("Enter slot (0 for none): "))) {
285          return 1;
286       }
287       slot = ua->pint32_val;
288    }
289            
290    set_pool_dbr_defaults_in_media_dbr(&mr, &pr);
291    for (i=startnum; i < num+startnum; i++) { 
292       bsnprintf(mr.VolumeName, sizeof(mr.VolumeName), name, i);
293       mr.Slot = slot++;
294       Dmsg1(200, "Create Volume %s\n", mr.VolumeName);
295       if (!db_create_media_record(ua->jcr, ua->db, &mr)) {
296          bsendmsg(ua, db_strerror(ua->db));
297          return 1;
298       }
299       if (i == startnum) {
300          first_id = mr.PoolId;
301       }
302    }
303    pr.NumVols += num;
304    Dmsg0(200, "Update pool record.\n"); 
305    if (db_update_pool_record(ua->jcr, ua->db, &pr) != 1) {
306       bsendmsg(ua, db_strerror(ua->db));
307       return 1;
308    }
309    bsendmsg(ua, _("%d Volumes created in pool %s\n"), num, pr.Name);
310
311    return 1;
312 }
313
314 /*
315  * Turn auto mount on/off  
316  * 
317  *  automount on 
318  *  automount off
319  */
320 int automount_cmd(UAContext *ua, char *cmd)
321 {
322    char *onoff;
323
324    if (ua->argc != 2) {
325       if (!get_cmd(ua, _("Turn on or off? "))) {
326             return 1;
327       }
328       onoff = ua->cmd;
329    } else {
330       onoff = ua->argk[1];
331    }
332
333    ua->automount = (strcasecmp(onoff, _("off")) == 0) ? 0 : 1;
334    return 1; 
335 }
336
337
338 /*
339  * Cancel a job
340  */
341 static int cancelcmd(UAContext *ua, char *cmd)
342 {
343    int i;
344    int njobs = 0;
345    BSOCK *sd, *fd;
346    JCR *jcr = NULL;
347    char JobName[MAX_NAME_LENGTH];
348
349    if (!open_db(ua)) {
350       return 1;
351    }
352
353    for (i=1; i<ua->argc; i++) {
354       if (strcasecmp(ua->argk[i], _("jobid")) == 0) {
355          if (!ua->argv[i]) {
356             break;
357          }
358          if (!(jcr=get_jcr_by_id(atoi(ua->argv[i])))) {
359             bsendmsg(ua, _("JobId %d is not running.\n"), atoi(ua->argv[i]));
360             return 1;
361          }
362          break;
363       } else if (strcasecmp(ua->argk[i], _("job")) == 0) {
364          if (!ua->argv[i]) {
365             break;
366          }
367          if (!(jcr=get_jcr_by_partial_name(ua->argv[i]))) {
368             bsendmsg(ua, _("Job %s is not running.\n"), ua->argv[i]);
369             return 1;
370          }
371          break;
372       }
373    }
374    /* If we still do not have a jcr,
375     *   throw up a list and ask the user to select one.
376     */
377    if (!jcr) {
378       /* Count Jobs running */
379       lock_jcr_chain();
380       for (jcr=NULL; (jcr=get_next_jcr(jcr)); njobs++) {
381          if (jcr->JobId == 0) {      /* this is us */
382             free_locked_jcr(jcr);
383             njobs--;
384             continue;
385          }
386          free_locked_jcr(jcr);
387       }
388       unlock_jcr_chain();
389
390       if (njobs == 0) {
391          bsendmsg(ua, _("No Jobs running.\n"));
392          return 1;
393       }
394       start_prompt(ua, _("Select Job:\n"));
395       lock_jcr_chain();
396       for (jcr=NULL; (jcr=get_next_jcr(jcr)); ) {
397          if (jcr->JobId == 0) {      /* this is us */
398             free_locked_jcr(jcr);
399             continue;
400          }
401          add_prompt(ua, jcr->Job);
402          free_locked_jcr(jcr);
403       }
404       unlock_jcr_chain();
405
406       if (do_prompt(ua, _("Job"),  _("Choose Job to cancel"), JobName, sizeof(JobName)) < 0) {
407          return 1;
408       }
409       if (njobs == 1) {
410          if (!get_yesno(ua, _("Confirm cancel (yes/no): ")) || ua->pint32_val == 0) {
411             return 1;
412          }
413       }
414       jcr = get_jcr_by_full_name(JobName);
415       if (!jcr) {
416          bsendmsg(ua, _("Job %s not found.\n"), JobName);
417          return 1;
418       }
419    }
420      
421    switch (jcr->JobStatus) {
422    case JS_Created:
423    case JS_WaitJobRes:
424    case JS_WaitClientRes:
425    case JS_WaitStoreRes:
426    case JS_WaitPriority:
427    case JS_WaitMaxJobs:
428    case JS_WaitStartTime:
429       set_jcr_job_status(jcr, JS_Canceled);
430       bsendmsg(ua, _("JobId %d, Job %s marked to be canceled.\n"),
431               jcr->JobId, jcr->Job);
432       jobq_remove(&job_queue, jcr); /* attempt to remove it from queue */
433       free_jcr(jcr);                  /* this decrements the use count only */
434       return 1;
435          
436    default:
437       set_jcr_job_status(jcr, JS_Canceled);
438
439       /* Cancel File daemon */
440       if (jcr->file_bsock) {
441          ua->jcr->client = jcr->client;
442          if (!connect_to_file_daemon(ua->jcr, 10, FDConnectTimeout, 1)) {
443             bsendmsg(ua, _("Failed to connect to File daemon.\n"));
444             free_jcr(jcr);
445             return 1;
446          }
447          Dmsg0(200, "Connected to file daemon\n");
448          fd = ua->jcr->file_bsock;
449          bnet_fsend(fd, "cancel Job=%s\n", jcr->Job);
450          while (bnet_recv(fd) >= 0) {
451             bsendmsg(ua, "%s", fd->msg);
452          }
453          bnet_sig(fd, BNET_TERMINATE);
454          bnet_close(fd);
455          ua->jcr->file_bsock = NULL;
456       }
457
458       /* Cancel Storage daemon */
459       if (jcr->store_bsock) {
460          ua->jcr->store = jcr->store;
461          if (!connect_to_storage_daemon(ua->jcr, 10, SDConnectTimeout, 1)) {
462             bsendmsg(ua, _("Failed to connect to Storage daemon.\n"));
463             free_jcr(jcr);
464             return 1;
465          }
466          Dmsg0(200, "Connected to storage daemon\n");
467          sd = ua->jcr->store_bsock;
468          bnet_fsend(sd, "cancel Job=%s\n", jcr->Job);
469          while (bnet_recv(sd) >= 0) {
470             bsendmsg(ua, "%s", sd->msg);
471          }
472          bnet_sig(sd, BNET_TERMINATE);
473          bnet_close(sd);
474          ua->jcr->store_bsock = NULL;
475       }
476    }
477    free_jcr(jcr);
478
479    return 1; 
480 }
481
482 /*
483  * This is a common routine to create or update a
484  *   Pool DB base record from a Pool Resource. We handle
485  *   the setting of MaxVols and NumVols slightly differently
486  *   depending on if we are creating the Pool or we are
487  *   simply bringing it into agreement with the resource (updage).
488  */
489 static void set_pooldbr_from_poolres(POOL_DBR *pr, POOL *pool, e_pool_op op)
490 {
491    strcpy(pr->PoolType, pool->pool_type);
492    if (op == POOL_OP_CREATE) {
493       pr->MaxVols = pool->max_volumes;
494       pr->NumVols = 0;
495    } else {          /* update pool */
496       if (pr->MaxVols != pool->max_volumes) {
497          pr->MaxVols = pool->max_volumes;
498       }
499       if (pr->MaxVols != 0 && pr->MaxVols < pr->NumVols) {
500          pr->MaxVols = pr->NumVols;
501       }
502    }
503    pr->UseOnce = pool->use_volume_once;
504    pr->UseCatalog = pool->use_catalog;
505    pr->AcceptAnyVolume = pool->accept_any_volume;
506    pr->Recycle = pool->Recycle;
507    pr->VolRetention = pool->VolRetention;
508    pr->VolUseDuration = pool->VolUseDuration;
509    pr->MaxVolJobs = pool->MaxVolJobs;
510    pr->MaxVolFiles = pool->MaxVolFiles;
511    pr->MaxVolBytes = pool->MaxVolBytes;
512    pr->AutoPrune = pool->AutoPrune;
513    pr->Recycle = pool->Recycle;
514    if (pool->label_format) {
515       strcpy(pr->LabelFormat, pool->label_format);
516    } else {
517       strcpy(pr->LabelFormat, "*");    /* none */
518    }
519 }
520
521
522 /*
523  * Create a pool record from a given Pool resource
524  *   Also called from backup.c
525  * Returns: -1  on error
526  *           0  record already exists
527  *           1  record created
528  */
529
530 int create_pool(JCR *jcr, B_DB *db, POOL *pool, e_pool_op op)
531 {
532    POOL_DBR  pr;
533
534    memset(&pr, 0, sizeof(POOL_DBR));
535
536    strcpy(pr.Name, pool->hdr.name);
537
538    if (db_get_pool_record(jcr, db, &pr)) {
539       /* Pool Exists */
540       if (op == POOL_OP_UPDATE) {  /* update request */
541          set_pooldbr_from_poolres(&pr, pool, op);
542          db_update_pool_record(jcr, db, &pr);
543       }
544       return 0;                       /* exists */
545    }
546
547    set_pooldbr_from_poolres(&pr, pool, op);
548
549    if (!db_create_pool_record(jcr, db, &pr)) {
550       return -1;                      /* error */
551    }
552    return 1;
553 }
554
555
556
557 /*
558  * Create a Pool Record in the database.
559  *  It is always created from the Resource record.
560  */
561 static int createcmd(UAContext *ua, char *cmd) 
562 {
563    POOL *pool;
564
565    if (!open_db(ua)) {
566       return 1;
567    }
568
569    pool = get_pool_resource(ua);
570    if (!pool) {
571       return 1;
572    }
573
574    switch (create_pool(ua->jcr, ua->db, pool, POOL_OP_CREATE)) {
575    case 0:
576       bsendmsg(ua, _("Error: Pool %s already exists.\n\
577 Use update to change it.\n"), pool->hdr.name);
578       break;
579
580    case -1:
581       bsendmsg(ua, db_strerror(ua->db));
582       break;
583
584    default:
585      break;
586    }
587    bsendmsg(ua, _("Pool %s created.\n"), pool->hdr.name);
588    return 1;
589 }
590
591
592
593
594 /*
595  * Update a Pool Record in the database.
596  *  It is always updated from the Resource record.
597  *
598  *    update pool=<pool-name>
599  *         updates pool from Pool resource
600  *    update media pool=<pool-name> volume=<volume-name>
601  *         changes pool info for volume
602  */
603 static int update_cmd(UAContext *ua, char *cmd) 
604 {
605    static char *kw[] = {
606       N_("media"),  /* 0 */
607       N_("volume"), /* 1 */
608       N_("pool"),   /* 2 */
609       N_("slots"),  /* 3 */
610       NULL};
611
612    if (!open_db(ua)) {
613       return 1;
614    }
615
616    switch (find_arg_keyword(ua, kw)) {
617    case 0:
618    case 1:
619       update_volume(ua);
620       return 1;
621    case 2:
622       update_pool(ua);
623       return 1;
624    case 3:
625       update_slots(ua);
626       return 1;
627    default:
628       break;
629    }
630     
631    start_prompt(ua, _("Update choice:\n"));
632    add_prompt(ua, _("Volume parameters"));
633    add_prompt(ua, _("Pool from resource"));
634    add_prompt(ua, _("Slots from autochanger"));
635    switch (do_prompt(ua, _("item"), _("Choose catalog item to update"), NULL, 0)) {
636    case 0:
637       update_volume(ua);
638       break;
639    case 1:
640       update_pool(ua);
641       break;
642    case 2:
643       update_slots(ua);
644       break;
645    default:
646       break;
647    }
648    return 1;
649 }
650
651 static void update_volstatus(UAContext *ua, char *val, MEDIA_DBR *mr)
652 {
653    POOLMEM *query = get_pool_memory(PM_MESSAGE);
654    char *kw[] = {
655       "Append",
656       "Archive",
657       "Disabled",
658       "Full",
659       "Used", 
660       "Cleaning", 
661       "Recycle",
662       "Read-Only",
663       NULL};
664    bool found = false;
665    int i;
666
667    for (i=0; kw[i]; i++) {
668       if (strcasecmp(val, kw[i]) == 0) {
669          found = true;
670          break;
671       }
672    }
673    if (!found) {
674       bsendmsg(ua, _("Invalid VolStatus specified: %s\n"), val);
675    } else {
676       bstrncpy(mr->VolStatus, kw[i], sizeof(mr->VolStatus));
677       Mmsg(&query, "UPDATE Media SET VolStatus='%s' WHERE MediaId=%u",
678          mr->VolStatus, mr->MediaId);
679       if (!db_sql_query(ua->db, query, NULL, NULL)) {  
680          bsendmsg(ua, "%s", db_strerror(ua->db));
681       } else {
682          bsendmsg(ua, _("New Volume status is: %s\n"), mr->VolStatus);
683       }
684    }
685    free_pool_memory(query);
686 }
687
688 static void update_volretention(UAContext *ua, char *val, MEDIA_DBR *mr)
689 {
690    char ed1[50];
691    POOLMEM *query;
692    if (!duration_to_utime(val, &mr->VolRetention)) {
693       bsendmsg(ua, _("Invalid retention period specified: %s\n"), val);
694       return;
695    }
696    query = get_pool_memory(PM_MESSAGE);
697    Mmsg(&query, "UPDATE Media SET VolRetention=%s WHERE MediaId=%u",
698       edit_uint64(mr->VolRetention, ed1), mr->MediaId);
699    if (!db_sql_query(ua->db, query, NULL, NULL)) {  
700       bsendmsg(ua, "%s", db_strerror(ua->db));
701    } else {
702       bsendmsg(ua, _("New retention seconds is: %s\n"),
703          edit_utime(mr->VolRetention, ed1));
704    }
705    free_pool_memory(query);
706 }
707
708 static void update_voluseduration(UAContext *ua, char *val, MEDIA_DBR *mr)
709 {
710    char ed1[50];
711    POOLMEM *query;
712
713    if (!duration_to_utime(val, &mr->VolUseDuration)) {
714       bsendmsg(ua, _("Invalid use duration specified: %s\n"), val);
715       return;
716    }
717    query = get_pool_memory(PM_MESSAGE);
718    Mmsg(&query, "UPDATE Media SET VolUseDuration=%s WHERE MediaId=%u",
719       edit_uint64(mr->VolUseDuration, ed1), mr->MediaId);
720    if (!db_sql_query(ua->db, query, NULL, NULL)) {  
721       bsendmsg(ua, "%s", db_strerror(ua->db));
722    } else {
723       bsendmsg(ua, _("New use duration is: %s\n"),
724          edit_utime(mr->VolUseDuration, ed1));
725    }
726    free_pool_memory(query);
727 }
728
729 static void update_volmaxjobs(UAContext *ua, char *val, MEDIA_DBR *mr)
730 {
731    POOLMEM *query = get_pool_memory(PM_MESSAGE);
732    Mmsg(&query, "UPDATE Media SET MaxVolJobs=%s WHERE MediaId=%u",
733       val, mr->MediaId);
734    if (!db_sql_query(ua->db, query, NULL, NULL)) {  
735       bsendmsg(ua, "%s", db_strerror(ua->db));
736    } else {
737       bsendmsg(ua, _("New max jobs is: %s\n"), val);
738    }
739    free_pool_memory(query);
740 }
741
742 static void update_volmaxfiles(UAContext *ua, char *val, MEDIA_DBR *mr)
743 {
744    POOLMEM *query = get_pool_memory(PM_MESSAGE);
745    Mmsg(&query, "UPDATE Media SET MaxVolFiles=%s WHERE MediaId=%u",
746       val, mr->MediaId);
747    if (!db_sql_query(ua->db, query, NULL, NULL)) {  
748       bsendmsg(ua, "%s", db_strerror(ua->db));
749    } else {
750       bsendmsg(ua, _("New max files is: %s\n"), val);
751    }
752    free_pool_memory(query);
753 }
754
755 static void update_volmaxbytes(UAContext *ua, char *val, MEDIA_DBR *mr)
756 {
757    uint64_t maxbytes;
758    char ed1[50];
759    POOLMEM *query;
760
761    if (!size_to_uint64(val, strlen(val), &maxbytes)) {
762       bsendmsg(ua, _("Invalid max. bytes specification: %s\n"), val);
763       return;
764    } 
765    query = get_pool_memory(PM_MESSAGE);
766    Mmsg(&query, "UPDATE Media SET MaxVolBytes=%s WHERE MediaId=%u",
767       edit_uint64(maxbytes, ed1), mr->MediaId);
768    if (!db_sql_query(ua->db, query, NULL, NULL)) {  
769       bsendmsg(ua, "%s", db_strerror(ua->db));
770    } else {
771       bsendmsg(ua, _("New Max bytes is: %s\n"), edit_uint64(maxbytes, ed1));
772    }
773    free_pool_memory(query);
774 }
775
776 static void update_volrecycle(UAContext *ua, char *val, MEDIA_DBR *mr)
777 {
778    int recycle;
779    POOLMEM *query;
780    if (strcasecmp(val, _("yes")) == 0) {
781       recycle = 1;
782    } else if (strcasecmp(val, _("no")) == 0) {
783       recycle = 0;
784    } else {
785       bsendmsg(ua, _("Invalid value. It must by yes or no.\n"));
786       return;
787    }
788    query = get_pool_memory(PM_MESSAGE);
789    Mmsg(&query, "UPDATE Media SET Recycle=%d WHERE MediaId=%u",
790       recycle, mr->MediaId);
791    if (!db_sql_query(ua->db, query, NULL, NULL)) {  
792       bsendmsg(ua, "%s", db_strerror(ua->db));
793    } else {       
794       bsendmsg(ua, _("New recycle flag is: %s\n"),
795          mr->Recycle==1?_("yes"):_("no"));
796    }
797    free_pool_memory(query);
798 }
799
800 /*
801  * Update a media record -- allows you to change the
802  *  Volume status. E.g. if you want Bacula to stop
803  *  writing on the volume, set it to anything other
804  *  than Append.
805  */              
806 static int update_volume(UAContext *ua)
807 {
808    MEDIA_DBR mr;
809    POOLMEM *query;
810    char ed1[30];
811    bool done = false;
812    char *kw[] = {
813       N_("VolStatus"),                /* 0 */
814       N_("VolRetention"),             /* 1 */
815       N_("VolUse"),                   /* 2 */
816       N_("MaxVolJobs"),               /* 3 */
817       N_("MaxVolFiles"),              /* 4 */
818       N_("MaxVolBytes"),              /* 5 */
819       N_("Recycle"),                  /* 6 */
820       NULL };
821
822    if (!select_media_dbr(ua, &mr)) {
823       return 0;
824    }
825    for (int i=0; kw[i]; i++) {
826       int j;
827       if ((j=find_arg_with_value(ua, kw[i])) > 0) {
828          switch (i) {
829          case 0:
830             update_volstatus(ua, ua->argv[j], &mr);
831             break;
832          case 1:
833             update_volretention(ua, ua->argv[j], &mr);
834             break;
835          case 2:
836             update_voluseduration(ua, ua->argv[j], &mr);
837             break;
838          case 3:
839             update_volmaxjobs(ua, ua->argv[j], &mr);
840             break;
841          case 4:
842             update_volmaxfiles(ua, ua->argv[j], &mr);
843             break;
844          case 5:
845             update_volmaxbytes(ua, ua->argv[j], &mr);
846             break;
847          case 6:
848             update_volrecycle(ua, ua->argv[j], &mr);
849             break;
850          }
851          done = true;
852       }
853    }
854
855    for ( ; !done; ) {
856       if (!select_media_dbr(ua, &mr)) {
857          return 0;
858       }
859       bsendmsg(ua, _("Updating Volume \"%s\"\n"), mr.VolumeName);
860       start_prompt(ua, _("Parameters to modify:\n"));
861       add_prompt(ua, _("Volume Status"));
862       add_prompt(ua, _("Volume Retention Period"));
863       add_prompt(ua, _("Volume Use Duration"));
864       add_prompt(ua, _("Maximum Volume Jobs"));
865       add_prompt(ua, _("Maximum Volume Files"));
866       add_prompt(ua, _("Maximum Volume Bytes"));
867       add_prompt(ua, _("Recycle Flag"));
868       add_prompt(ua, _("Slot"));
869       add_prompt(ua, _("Volume Files"));
870       add_prompt(ua, _("Done"));
871       switch (do_prompt(ua, "", _("Select parameter to modify"), NULL, 0)) {
872       case 0:                         /* Volume Status */
873          /* Modify Volume Status */
874          bsendmsg(ua, _("Current Volume status is: %s\n"), mr.VolStatus);
875          start_prompt(ua, _("Possible Values are:\n"));
876          add_prompt(ua, "Append");      /* Better not translate these as */
877          add_prompt(ua, "Archive");     /* They are known in the database code */
878          add_prompt(ua, "Disabled");
879          add_prompt(ua, "Full");
880          add_prompt(ua, "Used");
881          add_prompt(ua, "Cleaning");
882          if (strcmp(mr.VolStatus, "Purged") == 0) {
883             add_prompt(ua, "Recycle");
884          }
885          add_prompt(ua, "Read-Only");
886          if (do_prompt(ua, "", _("Choose new Volume Status"), ua->cmd, sizeof(mr.VolStatus)) < 0) {
887             return 1;
888          }
889          update_volstatus(ua, ua->cmd, &mr);
890          break;
891       case 1:                         /* Retention */
892          bsendmsg(ua, _("Current retention seconds is: %s\n"),
893             edit_utime(mr.VolRetention, ed1));
894          if (!get_cmd(ua, _("Enter Volume Retention period: "))) {
895             return 0;
896          }
897          update_volretention(ua, ua->cmd, &mr);
898          break;
899
900       case 2:                         /* Use Duration */
901          bsendmsg(ua, _("Current use duration is: %s\n"),
902             edit_utime(mr.VolUseDuration, ed1));
903          if (!get_cmd(ua, _("Enter Volume Use Duration: "))) {
904             return 0;
905          }
906          update_voluseduration(ua, ua->cmd, &mr);
907          break;
908
909       case 3:                         /* Max Jobs */
910          bsendmsg(ua, _("Current max jobs is: %u\n"), mr.MaxVolJobs);
911          if (!get_pint(ua, _("Enter new Maximum Jobs: "))) {
912             return 0;
913          }
914          update_volmaxjobs(ua, ua->cmd, &mr);
915          break;
916
917       case 4:                         /* Max Files */
918          bsendmsg(ua, _("Current max files is: %u\n"), mr.MaxVolFiles);
919          if (!get_pint(ua, _("Enter new Maximum Files: "))) {
920             return 0;
921          }
922          update_volmaxfiles(ua, ua->cmd, &mr);
923          break;
924
925       case 5:                         /* Max Bytes */
926          bsendmsg(ua, _("Current value is: %s\n"), edit_uint64(mr.MaxVolBytes, ed1));
927          if (!get_cmd(ua, _("Enter new Maximum Bytes: "))) {
928             return 0;
929          }
930          update_volmaxbytes(ua, ua->cmd, &mr);
931          break;
932
933
934       case 6:                         /* Recycle */
935          bsendmsg(ua, _("Current recycle flag is: %s\n"),
936             mr.Recycle==1?_("yes"):_("no"));
937          if (!get_yesno(ua, _("Enter new Recycle status: "))) {
938             return 0;
939          }
940          update_volrecycle(ua, ua->cmd, &mr);
941          break;
942
943       case 7:                         /* Slot */
944          int slot;
945          POOL_DBR pr;
946
947          memset(&pr, 0, sizeof(POOL_DBR));
948          pr.PoolId = mr.PoolId;
949          if (!db_get_pool_record(ua->jcr, ua->db, &pr)) {
950             bsendmsg(ua, "%s", db_strerror(ua->db));
951             return 0;
952          }
953          bsendmsg(ua, _("Current Slot is: %d\n"), mr.Slot);
954          if (!get_pint(ua, _("Enter new Slot: "))) {
955             return 0;
956          }
957          slot = ua->pint32_val;
958          if (pr.MaxVols > 0 && slot > (int)pr.MaxVols) {
959             bsendmsg(ua, _("Invalid slot, it must be between 0 and %d\n"),
960                pr.MaxVols);
961             break;
962          }
963          query = get_pool_memory(PM_MESSAGE);
964          Mmsg(&query, "UPDATE Media SET Slot=%d WHERE MediaId=%u",
965             slot, mr.MediaId);
966          if (!db_sql_query(ua->db, query, NULL, NULL)) {  
967             bsendmsg(ua, "%s", db_strerror(ua->db));
968          } else {
969             bsendmsg(ua, "New Slot is: %d\n", slot);
970          }
971          free_pool_memory(query);
972          break;
973
974       case 8:                         /* Volume Files */
975          int32_t VolFiles;
976          bsendmsg(ua, _("Warning changing Volume Files can result\n"
977                         "in loss of data on your Volume\n\n"));
978          bsendmsg(ua, _("Current Volume Files is: %u\n"), mr.VolFiles);
979          if (!get_pint(ua, _("Enter new number of Files for Volume: "))) {
980             return 0;
981          }
982          VolFiles = ua->pint32_val;
983          if (VolFiles != (int)(mr.VolFiles + 1)) {
984             bsendmsg(ua, _("Normally, you should only increase Volume Files by one!\n"));
985             if (!get_yesno(ua, _("Continue? (yes/no): ")) || ua->pint32_val == 0) {
986                break;
987             }
988          }
989          query = get_pool_memory(PM_MESSAGE);
990          Mmsg(&query, "UPDATE Media SET VolFiles=%u WHERE MediaId=%u",
991             VolFiles, mr.MediaId);
992          if (!db_sql_query(ua->db, query, NULL, NULL)) {  
993             bsendmsg(ua, "%s", db_strerror(ua->db));
994          } else {
995             bsendmsg(ua, _("New Volume Files is: %u\n"), VolFiles);
996          }
997          free_pool_memory(query);
998          break;
999
1000       default:                        /* Done or error */
1001          bsendmsg(ua, "Selection done.\n");
1002          return 1;
1003       }
1004    }
1005    return 1;
1006 }
1007
1008 /* 
1009  * Update pool record -- pull info from current POOL resource
1010  */
1011 static int update_pool(UAContext *ua)
1012 {
1013    POOL_DBR  pr;
1014    int id;
1015    POOL *pool;
1016    POOLMEM *query;       
1017    
1018    pool = get_pool_resource(ua);
1019    if (!pool) {
1020       return 0;
1021    }
1022
1023    memset(&pr, 0, sizeof(pr));
1024    strcpy(pr.Name, pool->hdr.name);
1025    if (!get_pool_dbr(ua, &pr)) {
1026       return 0;
1027    }
1028
1029    set_pooldbr_from_poolres(&pr, pool, POOL_OP_UPDATE); /* update */
1030
1031    id = db_update_pool_record(ua->jcr, ua->db, &pr);
1032    if (id <= 0) {
1033       bsendmsg(ua, _("db_update_pool_record returned %d. ERR=%s\n"),
1034          id, db_strerror(ua->db));
1035    }
1036    query = get_pool_memory(PM_MESSAGE);
1037    Mmsg(&query, list_pool, pr.PoolId);
1038    db_list_sql_query(ua->jcr, ua->db, query, prtit, ua, 1, HORZ_LIST);
1039    free_pool_memory(query);
1040    bsendmsg(ua, _("Pool DB record updated from resource.\n"));
1041    return 1;
1042 }
1043
1044
1045 static void do_storage_setdebug(UAContext *ua, STORE *store, int level)
1046 {
1047    BSOCK *sd;
1048
1049    ua->jcr->store = store;
1050    /* Try connecting for up to 15 seconds */
1051    bsendmsg(ua, _("Connecting to Storage daemon %s at %s:%d\n"), 
1052       store->hdr.name, store->address, store->SDport);
1053    if (!connect_to_storage_daemon(ua->jcr, 1, 15, 0)) {
1054       bsendmsg(ua, _("Failed to connect to Storage daemon.\n"));
1055       return;
1056    }
1057    Dmsg0(120, _("Connected to storage daemon\n"));
1058    sd = ua->jcr->store_bsock;
1059    bnet_fsend(sd, "setdebug=%d\n", level);
1060    if (bnet_recv(sd) >= 0) {
1061       bsendmsg(ua, "%s", sd->msg);
1062    }
1063    bnet_sig(sd, BNET_TERMINATE);
1064    bnet_close(sd);
1065    ua->jcr->store_bsock = NULL;
1066    return;  
1067 }
1068    
1069 static void do_client_setdebug(UAContext *ua, CLIENT *client, int level)
1070 {
1071    BSOCK *fd;
1072
1073    /* Connect to File daemon */
1074
1075    ua->jcr->client = client;
1076    /* Try to connect for 15 seconds */
1077    bsendmsg(ua, _("Connecting to Client %s at %s:%d\n"), 
1078       client->hdr.name, client->address, client->FDport);
1079    if (!connect_to_file_daemon(ua->jcr, 1, 15, 0)) {
1080       bsendmsg(ua, _("Failed to connect to Client.\n"));
1081       return;
1082    }
1083    Dmsg0(120, "Connected to file daemon\n");
1084    fd = ua->jcr->file_bsock;
1085    bnet_fsend(fd, "setdebug=%d\n", level);
1086    if (bnet_recv(fd) >= 0) {
1087       bsendmsg(ua, "%s", fd->msg);
1088    }
1089    bnet_sig(fd, BNET_TERMINATE);
1090    bnet_close(fd);
1091    ua->jcr->file_bsock = NULL;
1092    return;  
1093 }
1094
1095
1096 static void do_all_setdebug(UAContext *ua, int level)
1097 {
1098    STORE *store, **unique_store;
1099    CLIENT *client, **unique_client;
1100    int i, j, found;
1101
1102    /* Director */
1103    debug_level = level;
1104
1105    /* Count Storage items */
1106    LockRes();
1107    store = NULL;
1108    for (i=0; (store = (STORE *)GetNextRes(R_STORAGE, (RES *)store)); i++)
1109       { }
1110    unique_store = (STORE **) malloc(i * sizeof(STORE));
1111    /* Find Unique Storage address/port */         
1112    store = (STORE *)GetNextRes(R_STORAGE, NULL);
1113    i = 0;
1114    unique_store[i++] = store;
1115    while ((store = (STORE *)GetNextRes(R_STORAGE, (RES *)store))) {
1116       found = 0;
1117       for (j=0; j<i; j++) {
1118          if (strcmp(unique_store[j]->address, store->address) == 0 &&
1119              unique_store[j]->SDport == store->SDport) {
1120             found = 1;
1121             break;
1122          }
1123       }
1124       if (!found) {
1125          unique_store[i++] = store;
1126          Dmsg2(140, "Stuffing: %s:%d\n", store->address, store->SDport);
1127       }
1128    }
1129    UnlockRes();
1130
1131    /* Call each unique Storage daemon */
1132    for (j=0; j<i; j++) {
1133       do_storage_setdebug(ua, unique_store[j], level);
1134    }
1135    free(unique_store);
1136
1137    /* Count Client items */
1138    LockRes();
1139    client = NULL;
1140    for (i=0; (client = (CLIENT *)GetNextRes(R_CLIENT, (RES *)client)); i++)
1141       { }
1142    unique_client = (CLIENT **) malloc(i * sizeof(CLIENT));
1143    /* Find Unique Client address/port */         
1144    client = (CLIENT *)GetNextRes(R_CLIENT, NULL);
1145    i = 0;
1146    unique_client[i++] = client;
1147    while ((client = (CLIENT *)GetNextRes(R_CLIENT, (RES *)client))) {
1148       found = 0;
1149       for (j=0; j<i; j++) {
1150          if (strcmp(unique_client[j]->address, client->address) == 0 &&
1151              unique_client[j]->FDport == client->FDport) {
1152             found = 1;
1153             break;
1154          }
1155       }
1156       if (!found) {
1157          unique_client[i++] = client;
1158          Dmsg2(140, "Stuffing: %s:%d\n", client->address, client->FDport);
1159       }
1160    }
1161    UnlockRes();
1162
1163    /* Call each unique File daemon */
1164    for (j=0; j<i; j++) {
1165       do_client_setdebug(ua, unique_client[j], level);
1166    }
1167    free(unique_client);
1168 }
1169
1170 /*
1171  * setdebug level=nn all
1172  */
1173 static int setdebug_cmd(UAContext *ua, char *cmd)
1174 {
1175    STORE *store;
1176    CLIENT *client;
1177    int level;
1178    int i;
1179
1180    if (!open_db(ua)) {
1181       return 1;
1182    }
1183    Dmsg1(120, "setdebug:%s:\n", cmd);
1184
1185    level = -1;
1186    i = find_arg_with_value(ua, _("level"));
1187    if (i >= 0) {
1188       level = atoi(ua->argv[i]);
1189    }
1190    if (level < 0) {
1191       if (!get_pint(ua, _("Enter new debug level: "))) {
1192          return 1;
1193       }
1194       level = ua->pint32_val;
1195    }
1196
1197    /* General debug? */
1198    for (i=1; i<ua->argc; i++) {
1199       if (strcasecmp(ua->argk[i], _("all")) == 0) {
1200          do_all_setdebug(ua, level);
1201          return 1;
1202       }
1203       if (strcasecmp(ua->argk[i], _("dir")) == 0 ||
1204           strcasecmp(ua->argk[i], _("director")) == 0) {
1205          debug_level = level;
1206          return 1;
1207       }
1208       if (strcasecmp(ua->argk[i], _("client")) == 0) {
1209          client = NULL;
1210          if (ua->argv[i]) {
1211             client = (CLIENT *)GetResWithName(R_CLIENT, ua->argv[i]);
1212             if (client) {
1213                do_client_setdebug(ua, client, level);
1214                return 1;
1215             }
1216          }
1217          client = select_client_resource(ua);   
1218          if (client) {
1219             do_client_setdebug(ua, client, level);
1220             return 1;
1221          }
1222       }
1223
1224       if (strcasecmp(ua->argk[i], _("store")) == 0 ||
1225           strcasecmp(ua->argk[i], _("storage")) == 0) {
1226          store = NULL;
1227          if (ua->argv[i]) {
1228             store = (STORE *)GetResWithName(R_STORAGE, ua->argv[i]);
1229             if (store) {
1230                do_storage_setdebug(ua, store, level);
1231                return 1;
1232             }
1233          }
1234          store = get_storage_resource(ua, 0);
1235          if (store) {
1236             do_storage_setdebug(ua, store, level);
1237             return 1;
1238          }
1239       }
1240    } 
1241    /*
1242     * We didn't find an appropriate keyword above, so
1243     * prompt the user.
1244     */
1245    start_prompt(ua, _("Available daemons are: \n"));
1246    add_prompt(ua, _("Director"));
1247    add_prompt(ua, _("Storage"));
1248    add_prompt(ua, _("Client"));
1249    add_prompt(ua, _("All"));
1250    switch(do_prompt(ua, "", _("Select daemon type to set debug level"), NULL, 0)) {
1251    case 0:                         /* Director */
1252       debug_level = level;
1253       break;
1254    case 1:
1255       store = get_storage_resource(ua, 0);
1256       if (store) {
1257          do_storage_setdebug(ua, store, level);
1258       }
1259       break;
1260    case 2:
1261       client = select_client_resource(ua);
1262       if (client) {
1263          do_client_setdebug(ua, client, level);
1264       }
1265       break;
1266    case 3:
1267       do_all_setdebug(ua, level);
1268       break;
1269    default:
1270       break;
1271    }
1272    return 1;
1273 }
1274
1275 static int var_cmd(UAContext *ua, char *cmd)
1276 {
1277    POOLMEM *var = get_pool_memory(PM_FNAME);
1278    for (int i=1; i<ua->argc; i++) {
1279       if (ua->argk[i] && variable_expansion(ua->jcr, ua->argk[i], &var)) {
1280          bsendmsg(ua, "%s\n", var);
1281       }
1282    }
1283    free_pool_memory(var);
1284    return 1;
1285 }
1286
1287 static int estimate_cmd(UAContext *ua, char *cmd)
1288 {
1289    JOB *job = NULL;
1290    CLIENT *client = NULL;
1291    FILESET *fileset = NULL;
1292    int listing = 0;
1293    BSOCK *fd;
1294    char since[MAXSTRING];
1295
1296    for (int i=1; i<ua->argc; i++) {
1297       if (strcasecmp(ua->argk[i], _("client")) == 0) {
1298          if (ua->argv[i]) {
1299             client = (CLIENT *)GetResWithName(R_CLIENT, ua->argv[i]);
1300             continue;
1301          }
1302       }
1303       if (strcasecmp(ua->argk[i], _("job")) == 0) {
1304          if (ua->argv[i]) {
1305             job = (JOB *)GetResWithName(R_JOB, ua->argv[i]);
1306             continue;
1307          }
1308       }
1309       if (strcasecmp(ua->argk[i], _("fileset")) == 0) {
1310          if (ua->argv[i]) {
1311             fileset = (FILESET *)GetResWithName(R_FILESET, ua->argv[i]);
1312             continue;
1313          }
1314       }
1315       if (strcasecmp(ua->argk[i], _("listing")) == 0) {
1316          listing = 1;
1317       }
1318    } 
1319    if (!job && !(client && fileset)) {
1320       if (!(job = select_job_resource(ua))) {
1321          return 1;
1322       }
1323    }
1324    if (!job) {
1325       job = (JOB *)GetResWithName(R_JOB, ua->argk[1]);
1326    }
1327    if (!client) {
1328       client = job->client;
1329    }
1330    if (!fileset) {
1331       fileset = job->fileset;
1332    }
1333    ua->jcr->client = client;
1334    ua->jcr->fileset = fileset;
1335    close_db(ua);
1336    ua->catalog = client->catalog;
1337
1338    if (!open_db(ua)) {
1339       return 1;
1340    }
1341
1342    get_level_since_time(ua->jcr, since, sizeof(since));
1343
1344    bsendmsg(ua, _("Connecting to Client %s at %s:%d\n"),
1345       job->client->hdr.name, job->client->address, job->client->FDport);
1346    if (!connect_to_file_daemon(ua->jcr, 1, 15, 0)) {
1347       bsendmsg(ua, _("Failed to connect to Client.\n"));
1348       return 1;
1349    }
1350    fd = ua->jcr->file_bsock;
1351
1352    if (!send_include_list(ua->jcr)) {
1353       bsendmsg(ua, _("Error sending include list.\n"));
1354       return 1;
1355    }
1356
1357    if (!send_exclude_list(ua->jcr)) {
1358       bsendmsg(ua, _("Error sending exclude list.\n"));
1359       return 1;
1360    }
1361
1362    if (!send_level_command(ua->jcr)) {
1363       return 1;
1364    }
1365
1366    bnet_fsend(fd, "estimate listing=%d\n", listing);
1367    while (bnet_recv(fd) >= 0) {
1368       bsendmsg(ua, "%s", fd->msg);
1369    }
1370
1371    bnet_sig(fd, BNET_TERMINATE);
1372    bnet_close(fd);
1373    ua->jcr->file_bsock = NULL;
1374
1375    return 1;
1376 }
1377
1378
1379 /*
1380  * print time
1381  */
1382 static int time_cmd(UAContext *ua, char *cmd)
1383 {
1384    char sdt[50];
1385    time_t ttime = time(NULL);
1386    struct tm tm;
1387    localtime_r(&ttime, &tm);
1388    strftime(sdt, sizeof(sdt), "%d-%b-%Y %H:%M:%S", &tm);
1389    bsendmsg(ua, "%s\n", sdt);
1390    return 1;
1391 }
1392
1393
1394
1395 /*
1396  * Delete Pool records (should purge Media with it).
1397  *
1398  *  delete pool=<pool-name>
1399  *  delete media pool=<pool-name> volume=<name>
1400  */
1401 static int delete_cmd(UAContext *ua, char *cmd)
1402 {
1403    static char *keywords[] = {
1404       N_("volume"),
1405       N_("pool"),
1406       NULL};
1407
1408    if (!open_db(ua)) {
1409       return 1;
1410    }
1411
1412    bsendmsg(ua, _(
1413 "In general it is not a good idea to delete either a\n"
1414 "Pool or a Volume since they may contain data.\n\n"));
1415      
1416    switch (find_arg_keyword(ua, keywords)) {
1417    case 0:
1418       delete_volume(ua);     
1419       return 1;
1420    case 1:
1421       delete_pool(ua);
1422       return 1;
1423    default:
1424       break;
1425    }
1426    switch (do_keyword_prompt(ua, _("Choose catalog item to delete"), keywords)) {
1427    case 0:
1428       delete_volume(ua);
1429       break;
1430    case 1:
1431       delete_pool(ua);
1432       break;
1433    default:
1434       bsendmsg(ua, _("Nothing done.\n"));
1435       break;
1436    }
1437    return 1;
1438 }
1439
1440 /*
1441  * Delete media records from database -- dangerous 
1442  */
1443 static int delete_volume(UAContext *ua)
1444 {
1445    MEDIA_DBR mr;
1446
1447    if (!select_media_dbr(ua, &mr)) {
1448       return 1;
1449    }
1450    bsendmsg(ua, _("\nThis command will delete volume %s\n"
1451       "and all Jobs saved on that volume from the Catalog\n"),
1452       mr.VolumeName);
1453
1454    if (!get_yesno(ua, _("Are you sure you want to delete this Volume? (yes/no): "))) {
1455       return 1;
1456    }
1457    if (ua->pint32_val) {
1458       db_delete_media_record(ua->jcr, ua->db, &mr);
1459    }
1460    return 1;
1461 }
1462
1463 /*
1464  * Delete a pool record from the database -- dangerous   
1465  */
1466 static int delete_pool(UAContext *ua)
1467 {
1468    POOL_DBR  pr;
1469    
1470    memset(&pr, 0, sizeof(pr));
1471
1472    if (!get_pool_dbr(ua, &pr)) {
1473       return 1;
1474    }
1475    if (!get_yesno(ua, _("Are you sure you want to delete this Pool? (yes/no): "))) {
1476       return 1;
1477    }
1478    if (ua->pint32_val) {
1479       db_delete_pool_record(ua->jcr, ua->db, &pr);
1480    }
1481    return 1;
1482 }
1483
1484
1485 static void do_mount_cmd(UAContext *ua, char *command)
1486 {
1487    STORE *store;
1488    BSOCK *sd;
1489    char dev_name[MAX_NAME_LENGTH];
1490
1491
1492    if (!open_db(ua)) {
1493       return;
1494    }
1495    Dmsg2(120, "%s: %s\n", command, ua->UA_sock->msg);
1496
1497    store = get_storage_resource(ua, 1);
1498    if (!store) {
1499       return;
1500    }
1501
1502    Dmsg2(120, "Found storage, MediaType=%s DevName=%s\n",
1503       store->media_type, store->dev_name);
1504
1505    ua->jcr->store = store;
1506    if (!connect_to_storage_daemon(ua->jcr, 10, SDConnectTimeout, 1)) {
1507       bsendmsg(ua, _("Failed to connect to Storage daemon.\n"));
1508       return;
1509    }
1510    sd = ua->jcr->store_bsock;
1511    strcpy(dev_name, store->dev_name);
1512    bash_spaces(dev_name);
1513    bnet_fsend(sd, "%s %s", command, dev_name);
1514    while (bnet_recv(sd) >= 0) {
1515       bsendmsg(ua, "%s", sd->msg);
1516    }
1517    bnet_sig(sd, BNET_TERMINATE);
1518    bnet_close(sd);
1519    ua->jcr->store_bsock = NULL;
1520 }
1521
1522 /*
1523  * mount [storage | device] <name>
1524  */
1525 static int mount_cmd(UAContext *ua, char *cmd)
1526 {
1527    do_mount_cmd(ua, "mount");          /* mount */
1528    return 1;
1529 }
1530
1531
1532 /*
1533  * unmount [storage | device] <name>
1534  */
1535 static int unmount_cmd(UAContext *ua, char *cmd)
1536 {
1537    do_mount_cmd(ua, "unmount");          /* unmount */
1538    return 1;
1539 }
1540
1541
1542 /*
1543  * release [storage | device] <name>
1544  */
1545 static int release_cmd(UAContext *ua, char *cmd)
1546 {
1547    do_mount_cmd(ua, "release");          /* release */
1548    return 1;
1549 }
1550
1551
1552 /*
1553  * Switch databases
1554  *   use catalog=<name>
1555  */
1556 static int use_cmd(UAContext *ua, char *cmd)
1557 {
1558    CAT *oldcatalog, *catalog;
1559
1560
1561    close_db(ua);                      /* close any previously open db */
1562    oldcatalog = ua->catalog;
1563
1564    if (!(catalog = get_catalog_resource(ua))) {
1565       ua->catalog = oldcatalog;
1566    } else {
1567       ua->catalog = catalog;
1568    }
1569    if (open_db(ua)) {
1570       bsendmsg(ua, _("Using Catalog name=%s DB=%s\n"),
1571          ua->catalog->hdr.name, ua->catalog->db_name);
1572    }
1573    return 1;
1574 }
1575
1576 int quit_cmd(UAContext *ua, char *cmd) 
1577 {
1578    ua->quit = TRUE;
1579    return 1;
1580 }
1581
1582 /*
1583  * Wait until no job is running 
1584  */
1585 int wait_cmd(UAContext *ua, char *cmd) 
1586 {
1587    bmicrosleep(0, 200000);            /* let job actually start */
1588    for (int running=1; running; ) {
1589       running = 0;
1590       lock_jcr_chain();
1591       for (JCR *jcr=NULL; (jcr=get_next_jcr(jcr)); ) {
1592          if (jcr->JobId != 0) {
1593             running = 1;
1594             free_locked_jcr(jcr);
1595             break;
1596          }
1597          free_locked_jcr(jcr);
1598       }
1599       unlock_jcr_chain();
1600       if (running) {
1601          bmicrosleep(1, 0);
1602       }
1603    }
1604    return 1;
1605 }
1606
1607
1608 static int help_cmd(UAContext *ua, char *cmd)
1609 {
1610    unsigned int i;
1611
1612 /* usage(); */
1613    bsendmsg(ua, _("  Command    Description\n  =======    ===========\n"));
1614    for (i=0; i<comsize; i++) {
1615       bsendmsg(ua, _("  %-10s %s\n"), _(commands[i].key), _(commands[i].help));
1616    }
1617    bsendmsg(ua, "\n");
1618    return 1;
1619 }
1620
1621 static int version_cmd(UAContext *ua, char *cmd)
1622 {
1623    bsendmsg(ua, "%s Version: " VERSION " (" BDATE ")\n", my_name);
1624    return 1;
1625 }
1626
1627
1628 /* A bit brain damaged in that if the user has not done
1629  * a "use catalog xxx" command, we simply find the first
1630  * catalog resource and open it.
1631  */
1632 int open_db(UAContext *ua)
1633 {
1634    if (ua->db) {
1635       return 1;
1636    }
1637    if (!ua->catalog) {
1638       LockRes();
1639       ua->catalog = (CAT *)GetNextRes(R_CATALOG, NULL);
1640       UnlockRes();
1641       if (!ua->catalog) {    
1642          bsendmsg(ua, _("Could not find a Catalog resource\n"));
1643          return 0;
1644       } else {
1645          bsendmsg(ua, _("Using default Catalog name=%s DB=%s\n"), 
1646             ua->catalog->hdr.name, ua->catalog->db_name);
1647       }
1648    }
1649
1650    ua->jcr->catalog = ua->catalog;
1651
1652    Dmsg0(150, "Open database\n");
1653    ua->db = db_init_database(ua->jcr, ua->catalog->db_name, ua->catalog->db_user,
1654                              ua->catalog->db_password, ua->catalog->db_address,
1655                              ua->catalog->db_port, ua->catalog->db_socket);
1656    if (!ua->db || !db_open_database(ua->jcr, ua->db)) {
1657       bsendmsg(ua, _("Could not open database \"%s\".\n"),
1658                  ua->catalog->db_name);
1659       if (ua->db) {
1660          bsendmsg(ua, "%s", db_strerror(ua->db));
1661       }
1662       close_db(ua);
1663       return 0;
1664    }
1665    ua->jcr->db = ua->db;
1666    Dmsg1(150, "DB %s opened\n", ua->catalog->db_name);
1667    return 1;
1668 }
1669
1670 void close_db(UAContext *ua)
1671 {
1672    if (ua->db) {
1673       db_close_database(ua->jcr, ua->db);
1674    }
1675    ua->db = NULL;
1676 }