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