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