]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/ua_cmds.c
Fix: clock diff, Dan's patch, Nic's patch, segfault
[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    POOLMEM *query;
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    query = get_pool_memory(PM_MESSAGE);
814    Mmsg(&query, "UPDATE Media SET PoolId=%u WHERE MediaId=%u", pr.PoolId, mr->MediaId);
815    if (!db_sql_query(ua->db, query, NULL, NULL)) {  
816       bsendmsg(ua, "%s", db_strerror(ua->db));
817    } else {       
818       bsendmsg(ua, _("New Pool is: %s\n"), pr.Name);
819    }
820    free_pool_memory(query);
821 }
822
823 /*
824  * Update a media record -- allows you to change the
825  *  Volume status. E.g. if you want Bacula to stop
826  *  writing on the volume, set it to anything other
827  *  than Append.
828  */              
829 static int update_volume(UAContext *ua)
830 {
831    MEDIA_DBR mr;
832    POOL_DBR pr;
833    POOLMEM *query;
834    char ed1[30];
835    bool done = false;
836    char *kw[] = {
837       N_("VolStatus"),                /* 0 */
838       N_("VolRetention"),             /* 1 */
839       N_("VolUse"),                   /* 2 */
840       N_("MaxVolJobs"),               /* 3 */
841       N_("MaxVolFiles"),              /* 4 */
842       N_("MaxVolBytes"),              /* 5 */
843       N_("Recycle"),                  /* 6 */
844       N_("Pool"),                     /* 7 */
845       NULL };
846
847    for (int i=0; kw[i]; i++) {
848       int j;
849       if ((j=find_arg_with_value(ua, kw[i])) > 0) {
850          if (!select_media_dbr(ua, &mr)) {
851             return 0;
852          }
853          switch (i) {
854          case 0:
855             update_volstatus(ua, ua->argv[j], &mr);
856             break;
857          case 1:
858             update_volretention(ua, ua->argv[j], &mr);
859             break;
860          case 2:
861             update_voluseduration(ua, ua->argv[j], &mr);
862             break;
863          case 3:
864             update_volmaxjobs(ua, ua->argv[j], &mr);
865             break;
866          case 4:
867             update_volmaxfiles(ua, ua->argv[j], &mr);
868             break;
869          case 5:
870             update_volmaxbytes(ua, ua->argv[j], &mr);
871             break;
872          case 6:
873             update_volrecycle(ua, ua->argv[j], &mr);
874             break;
875          case 7:
876             update_volpool(ua, ua->argv[j], &mr);
877          }
878          done = true;
879       }
880    }
881
882    for ( ; !done; ) {
883       if (!select_media_dbr(ua, &mr)) {
884          return 0;
885       }
886       bsendmsg(ua, _("Updating Volume \"%s\"\n"), mr.VolumeName);
887       start_prompt(ua, _("Parameters to modify:\n"));
888       add_prompt(ua, _("Volume Status"));
889       add_prompt(ua, _("Volume Retention Period"));
890       add_prompt(ua, _("Volume Use Duration"));
891       add_prompt(ua, _("Maximum Volume Jobs"));
892       add_prompt(ua, _("Maximum Volume Files"));
893       add_prompt(ua, _("Maximum Volume Bytes"));
894       add_prompt(ua, _("Recycle Flag"));
895       add_prompt(ua, _("Slot"));
896       add_prompt(ua, _("Volume Files"));
897       add_prompt(ua, _("Pool"));
898       add_prompt(ua, _("Done"));
899       switch (do_prompt(ua, "", _("Select parameter to modify"), NULL, 0)) {
900       case 0:                         /* Volume Status */
901          /* Modify Volume Status */
902          bsendmsg(ua, _("Current Volume status is: %s\n"), mr.VolStatus);
903          start_prompt(ua, _("Possible Values are:\n"));
904          add_prompt(ua, "Append");      /* Better not translate these as */
905          add_prompt(ua, "Archive");     /* They are known in the database code */
906          add_prompt(ua, "Disabled");
907          add_prompt(ua, "Full");
908          add_prompt(ua, "Used");
909          add_prompt(ua, "Cleaning");
910          if (strcmp(mr.VolStatus, "Purged") == 0) {
911             add_prompt(ua, "Recycle");
912          }
913          add_prompt(ua, "Read-Only");
914          if (do_prompt(ua, "", _("Choose new Volume Status"), ua->cmd, sizeof(mr.VolStatus)) < 0) {
915             return 1;
916          }
917          update_volstatus(ua, ua->cmd, &mr);
918          break;
919       case 1:                         /* Retention */
920          bsendmsg(ua, _("Current retention seconds is: %s\n"),
921             edit_utime(mr.VolRetention, ed1));
922          if (!get_cmd(ua, _("Enter Volume Retention period: "))) {
923             return 0;
924          }
925          update_volretention(ua, ua->cmd, &mr);
926          break;
927
928       case 2:                         /* Use Duration */
929          bsendmsg(ua, _("Current use duration is: %s\n"),
930             edit_utime(mr.VolUseDuration, ed1));
931          if (!get_cmd(ua, _("Enter Volume Use Duration: "))) {
932             return 0;
933          }
934          update_voluseduration(ua, ua->cmd, &mr);
935          break;
936
937       case 3:                         /* Max Jobs */
938          bsendmsg(ua, _("Current max jobs is: %u\n"), mr.MaxVolJobs);
939          if (!get_pint(ua, _("Enter new Maximum Jobs: "))) {
940             return 0;
941          }
942          update_volmaxjobs(ua, ua->cmd, &mr);
943          break;
944
945       case 4:                         /* Max Files */
946          bsendmsg(ua, _("Current max files is: %u\n"), mr.MaxVolFiles);
947          if (!get_pint(ua, _("Enter new Maximum Files: "))) {
948             return 0;
949          }
950          update_volmaxfiles(ua, ua->cmd, &mr);
951          break;
952
953       case 5:                         /* Max Bytes */
954          bsendmsg(ua, _("Current value is: %s\n"), edit_uint64(mr.MaxVolBytes, ed1));
955          if (!get_cmd(ua, _("Enter new Maximum Bytes: "))) {
956             return 0;
957          }
958          update_volmaxbytes(ua, ua->cmd, &mr);
959          break;
960
961
962       case 6:                         /* Recycle */
963          bsendmsg(ua, _("Current recycle flag is: %s\n"),
964             mr.Recycle==1?_("yes"):_("no"));
965          if (!get_yesno(ua, _("Enter new Recycle status: "))) {
966             return 0;
967          }
968          update_volrecycle(ua, ua->cmd, &mr);
969          break;
970
971       case 7:                         /* Slot */
972          int slot;
973
974          memset(&pr, 0, sizeof(POOL_DBR));
975          pr.PoolId = mr.PoolId;
976          if (!db_get_pool_record(ua->jcr, ua->db, &pr)) {
977             bsendmsg(ua, "%s", db_strerror(ua->db));
978             return 0;
979          }
980          bsendmsg(ua, _("Current Slot is: %d\n"), mr.Slot);
981          if (!get_pint(ua, _("Enter new Slot: "))) {
982             return 0;
983          }
984          slot = ua->pint32_val;
985          if (pr.MaxVols > 0 && slot > (int)pr.MaxVols) {
986             bsendmsg(ua, _("Invalid slot, it must be between 0 and %d\n"),
987                pr.MaxVols);
988             break;
989          }
990          query = get_pool_memory(PM_MESSAGE);
991          Mmsg(&query, "UPDATE Media SET Slot=%d WHERE MediaId=%u",
992             slot, mr.MediaId);
993          if (!db_sql_query(ua->db, query, NULL, NULL)) {  
994             bsendmsg(ua, "%s", db_strerror(ua->db));
995          } else {
996             bsendmsg(ua, "New Slot is: %d\n", slot);
997          }
998          free_pool_memory(query);
999          break;
1000
1001       case 8:                         /* Volume Files */
1002          int32_t VolFiles;
1003          bsendmsg(ua, _("Warning changing Volume Files can result\n"
1004                         "in loss of data on your Volume\n\n"));
1005          bsendmsg(ua, _("Current Volume Files is: %u\n"), mr.VolFiles);
1006          if (!get_pint(ua, _("Enter new number of Files for Volume: "))) {
1007             return 0;
1008          }
1009          VolFiles = ua->pint32_val;
1010          if (VolFiles != (int)(mr.VolFiles + 1)) {
1011             bsendmsg(ua, _("Normally, you should only increase Volume Files by one!\n"));
1012             if (!get_yesno(ua, _("Continue? (yes/no): ")) || ua->pint32_val == 0) {
1013                break;
1014             }
1015          }
1016          query = get_pool_memory(PM_MESSAGE);
1017          Mmsg(&query, "UPDATE Media SET VolFiles=%u WHERE MediaId=%u",
1018             VolFiles, mr.MediaId);
1019          if (!db_sql_query(ua->db, query, NULL, NULL)) {  
1020             bsendmsg(ua, "%s", db_strerror(ua->db));
1021          } else {
1022             bsendmsg(ua, _("New Volume Files is: %u\n"), VolFiles);
1023          }
1024          free_pool_memory(query);
1025          break;
1026
1027       case 9:                         /* Volume's Pool */
1028          memset(&pr, 0, sizeof(POOL_DBR));
1029          pr.PoolId = mr.PoolId;
1030          if (!db_get_pool_record(ua->jcr, ua->db, &pr)) {
1031             bsendmsg(ua, "%s", db_strerror(ua->db));
1032             return 0;
1033          }
1034          bsendmsg(ua, _("Current Pool is: %s\n"), pr.Name);
1035          if (!get_cmd(ua, _("Enter new Pool name: "))) {
1036             return 0;
1037          }
1038          update_volpool(ua, ua->cmd, &mr);
1039          return 1;
1040       default:                        /* Done or error */
1041          bsendmsg(ua, "Selection done.\n");
1042          return 1;
1043       }
1044    }
1045    return 1;
1046 }
1047
1048 /* 
1049  * Update pool record -- pull info from current POOL resource
1050  */
1051 static int update_pool(UAContext *ua)
1052 {
1053    POOL_DBR  pr;
1054    int id;
1055    POOL *pool;
1056    POOLMEM *query;       
1057    
1058    pool = get_pool_resource(ua);
1059    if (!pool) {
1060       return 0;
1061    }
1062
1063    memset(&pr, 0, sizeof(pr));
1064    strcpy(pr.Name, pool->hdr.name);
1065    if (!get_pool_dbr(ua, &pr)) {
1066       return 0;
1067    }
1068
1069    set_pooldbr_from_poolres(&pr, pool, POOL_OP_UPDATE); /* update */
1070
1071    id = db_update_pool_record(ua->jcr, ua->db, &pr);
1072    if (id <= 0) {
1073       bsendmsg(ua, _("db_update_pool_record returned %d. ERR=%s\n"),
1074          id, db_strerror(ua->db));
1075    }
1076    query = get_pool_memory(PM_MESSAGE);
1077    Mmsg(&query, list_pool, pr.PoolId);
1078    db_list_sql_query(ua->jcr, ua->db, query, prtit, ua, 1, HORZ_LIST);
1079    free_pool_memory(query);
1080    bsendmsg(ua, _("Pool DB record updated from resource.\n"));
1081    return 1;
1082 }
1083
1084
1085 static void do_storage_setdebug(UAContext *ua, STORE *store, int level)
1086 {
1087    BSOCK *sd;
1088
1089    ua->jcr->store = store;
1090    /* Try connecting for up to 15 seconds */
1091    bsendmsg(ua, _("Connecting to Storage daemon %s at %s:%d\n"), 
1092       store->hdr.name, store->address, store->SDport);
1093    if (!connect_to_storage_daemon(ua->jcr, 1, 15, 0)) {
1094       bsendmsg(ua, _("Failed to connect to Storage daemon.\n"));
1095       return;
1096    }
1097    Dmsg0(120, _("Connected to storage daemon\n"));
1098    sd = ua->jcr->store_bsock;
1099    bnet_fsend(sd, "setdebug=%d\n", level);
1100    if (bnet_recv(sd) >= 0) {
1101       bsendmsg(ua, "%s", sd->msg);
1102    }
1103    bnet_sig(sd, BNET_TERMINATE);
1104    bnet_close(sd);
1105    ua->jcr->store_bsock = NULL;
1106    return;  
1107 }
1108    
1109 static void do_client_setdebug(UAContext *ua, CLIENT *client, int level)
1110 {
1111    BSOCK *fd;
1112
1113    /* Connect to File daemon */
1114
1115    ua->jcr->client = client;
1116    /* Try to connect for 15 seconds */
1117    bsendmsg(ua, _("Connecting to Client %s at %s:%d\n"), 
1118       client->hdr.name, client->address, client->FDport);
1119    if (!connect_to_file_daemon(ua->jcr, 1, 15, 0)) {
1120       bsendmsg(ua, _("Failed to connect to Client.\n"));
1121       return;
1122    }
1123    Dmsg0(120, "Connected to file daemon\n");
1124    fd = ua->jcr->file_bsock;
1125    bnet_fsend(fd, "setdebug=%d\n", level);
1126    if (bnet_recv(fd) >= 0) {
1127       bsendmsg(ua, "%s", fd->msg);
1128    }
1129    bnet_sig(fd, BNET_TERMINATE);
1130    bnet_close(fd);
1131    ua->jcr->file_bsock = NULL;
1132    return;  
1133 }
1134
1135
1136 static void do_all_setdebug(UAContext *ua, int level)
1137 {
1138    STORE *store, **unique_store;
1139    CLIENT *client, **unique_client;
1140    int i, j, found;
1141
1142    /* Director */
1143    debug_level = level;
1144
1145    /* Count Storage items */
1146    LockRes();
1147    store = NULL;
1148    for (i=0; (store = (STORE *)GetNextRes(R_STORAGE, (RES *)store)); i++)
1149       { }
1150    unique_store = (STORE **) malloc(i * sizeof(STORE));
1151    /* Find Unique Storage address/port */         
1152    store = (STORE *)GetNextRes(R_STORAGE, NULL);
1153    i = 0;
1154    unique_store[i++] = store;
1155    while ((store = (STORE *)GetNextRes(R_STORAGE, (RES *)store))) {
1156       found = 0;
1157       for (j=0; j<i; j++) {
1158          if (strcmp(unique_store[j]->address, store->address) == 0 &&
1159              unique_store[j]->SDport == store->SDport) {
1160             found = 1;
1161             break;
1162          }
1163       }
1164       if (!found) {
1165          unique_store[i++] = store;
1166          Dmsg2(140, "Stuffing: %s:%d\n", store->address, store->SDport);
1167       }
1168    }
1169    UnlockRes();
1170
1171    /* Call each unique Storage daemon */
1172    for (j=0; j<i; j++) {
1173       do_storage_setdebug(ua, unique_store[j], level);
1174    }
1175    free(unique_store);
1176
1177    /* Count Client items */
1178    LockRes();
1179    client = NULL;
1180    for (i=0; (client = (CLIENT *)GetNextRes(R_CLIENT, (RES *)client)); i++)
1181       { }
1182    unique_client = (CLIENT **) malloc(i * sizeof(CLIENT));
1183    /* Find Unique Client address/port */         
1184    client = (CLIENT *)GetNextRes(R_CLIENT, NULL);
1185    i = 0;
1186    unique_client[i++] = client;
1187    while ((client = (CLIENT *)GetNextRes(R_CLIENT, (RES *)client))) {
1188       found = 0;
1189       for (j=0; j<i; j++) {
1190          if (strcmp(unique_client[j]->address, client->address) == 0 &&
1191              unique_client[j]->FDport == client->FDport) {
1192             found = 1;
1193             break;
1194          }
1195       }
1196       if (!found) {
1197          unique_client[i++] = client;
1198          Dmsg2(140, "Stuffing: %s:%d\n", client->address, client->FDport);
1199       }
1200    }
1201    UnlockRes();
1202
1203    /* Call each unique File daemon */
1204    for (j=0; j<i; j++) {
1205       do_client_setdebug(ua, unique_client[j], level);
1206    }
1207    free(unique_client);
1208 }
1209
1210 /*
1211  * setdebug level=nn all
1212  */
1213 static int setdebug_cmd(UAContext *ua, char *cmd)
1214 {
1215    STORE *store;
1216    CLIENT *client;
1217    int level;
1218    int i;
1219
1220    if (!open_db(ua)) {
1221       return 1;
1222    }
1223    Dmsg1(120, "setdebug:%s:\n", cmd);
1224
1225    level = -1;
1226    i = find_arg_with_value(ua, _("level"));
1227    if (i >= 0) {
1228       level = atoi(ua->argv[i]);
1229    }
1230    if (level < 0) {
1231       if (!get_pint(ua, _("Enter new debug level: "))) {
1232          return 1;
1233       }
1234       level = ua->pint32_val;
1235    }
1236
1237    /* General debug? */
1238    for (i=1; i<ua->argc; i++) {
1239       if (strcasecmp(ua->argk[i], _("all")) == 0) {
1240          do_all_setdebug(ua, level);
1241          return 1;
1242       }
1243       if (strcasecmp(ua->argk[i], _("dir")) == 0 ||
1244           strcasecmp(ua->argk[i], _("director")) == 0) {
1245          debug_level = level;
1246          return 1;
1247       }
1248       if (strcasecmp(ua->argk[i], _("client")) == 0 ||
1249           strcasecmp(ua->argk[i], _("fd")) == 0) {
1250          client = NULL;
1251          if (ua->argv[i]) {
1252             client = (CLIENT *)GetResWithName(R_CLIENT, ua->argv[i]);
1253             if (client) {
1254                do_client_setdebug(ua, client, level);
1255                return 1;
1256             }
1257          }
1258          client = select_client_resource(ua);   
1259          if (client) {
1260             do_client_setdebug(ua, client, level);
1261             return 1;
1262          }
1263       }
1264
1265       if (strcasecmp(ua->argk[i], _("store")) == 0 ||
1266           strcasecmp(ua->argk[i], _("storage")) == 0 ||
1267           strcasecmp(ua->argk[i], _("sd")) == 0) {
1268          store = NULL;
1269          if (ua->argv[i]) {
1270             store = (STORE *)GetResWithName(R_STORAGE, ua->argv[i]);
1271             if (store) {
1272                do_storage_setdebug(ua, store, level);
1273                return 1;
1274             }
1275          }
1276          store = get_storage_resource(ua, 0);
1277          if (store) {
1278             do_storage_setdebug(ua, store, level);
1279             return 1;
1280          }
1281       }
1282    } 
1283    /*
1284     * We didn't find an appropriate keyword above, so
1285     * prompt the user.
1286     */
1287    start_prompt(ua, _("Available daemons are: \n"));
1288    add_prompt(ua, _("Director"));
1289    add_prompt(ua, _("Storage"));
1290    add_prompt(ua, _("Client"));
1291    add_prompt(ua, _("All"));
1292    switch(do_prompt(ua, "", _("Select daemon type to set debug level"), NULL, 0)) {
1293    case 0:                         /* Director */
1294       debug_level = level;
1295       break;
1296    case 1:
1297       store = get_storage_resource(ua, 0);
1298       if (store) {
1299          do_storage_setdebug(ua, store, level);
1300       }
1301       break;
1302    case 2:
1303       client = select_client_resource(ua);
1304       if (client) {
1305          do_client_setdebug(ua, client, level);
1306       }
1307       break;
1308    case 3:
1309       do_all_setdebug(ua, level);
1310       break;
1311    default:
1312       break;
1313    }
1314    return 1;
1315 }
1316
1317 static int var_cmd(UAContext *ua, char *cmd)
1318 {
1319    POOLMEM *val = get_pool_memory(PM_FNAME);
1320    char *var;
1321
1322    if (!open_db(ua)) {
1323       return 1;
1324    }
1325    for (var=ua->cmd; *var != ' '; ) {    /* skip command */
1326       var++;
1327    }
1328    while (*var == ' ') {                 /* skip spaces */
1329       var++;
1330    }
1331    Dmsg1(100, "Var=%s:\n", var);
1332    variable_expansion(ua->jcr, var, &val);  
1333    bsendmsg(ua, "%s\n", val);
1334    free_pool_memory(val);
1335    return 1;
1336 }
1337
1338 static int estimate_cmd(UAContext *ua, char *cmd)
1339 {
1340    JOB *job = NULL;
1341    CLIENT *client = NULL;
1342    FILESET *fileset = NULL;
1343    int listing = 0;
1344    BSOCK *fd;
1345    char since[MAXSTRING];
1346
1347    for (int i=1; i<ua->argc; i++) {
1348       if (strcasecmp(ua->argk[i], _("client")) == 0 ||
1349           strcasecmp(ua->argk[i], _("fd")) == 0) {
1350          if (ua->argv[i]) {
1351             client = (CLIENT *)GetResWithName(R_CLIENT, ua->argv[i]);
1352             continue;
1353          }
1354       }
1355       if (strcasecmp(ua->argk[i], _("job")) == 0) {
1356          if (ua->argv[i]) {
1357             job = (JOB *)GetResWithName(R_JOB, ua->argv[i]);
1358             continue;
1359          }
1360       }
1361       if (strcasecmp(ua->argk[i], _("fileset")) == 0) {
1362          if (ua->argv[i]) {
1363             fileset = (FILESET *)GetResWithName(R_FILESET, ua->argv[i]);
1364             continue;
1365          }
1366       }
1367       if (strcasecmp(ua->argk[i], _("listing")) == 0) {
1368          listing = 1;
1369       }
1370    } 
1371    if (!job && !(client && fileset)) {
1372       if (!(job = select_job_resource(ua))) {
1373          return 1;
1374       }
1375    }
1376    if (!job) {
1377       job = (JOB *)GetResWithName(R_JOB, ua->argk[1]);
1378    }
1379    if (!client) {
1380       client = job->client;
1381    }
1382    if (!fileset) {
1383       fileset = job->fileset;
1384    }
1385    ua->jcr->client = client;
1386    ua->jcr->fileset = fileset;
1387    close_db(ua);
1388    ua->catalog = client->catalog;
1389
1390    if (!open_db(ua)) {
1391       return 1;
1392    }
1393
1394    get_level_since_time(ua->jcr, since, sizeof(since));
1395
1396    bsendmsg(ua, _("Connecting to Client %s at %s:%d\n"),
1397       job->client->hdr.name, job->client->address, job->client->FDport);
1398    if (!connect_to_file_daemon(ua->jcr, 1, 15, 0)) {
1399       bsendmsg(ua, _("Failed to connect to Client.\n"));
1400       return 1;
1401    }
1402    fd = ua->jcr->file_bsock;
1403
1404    if (!send_include_list(ua->jcr)) {
1405       bsendmsg(ua, _("Error sending include list.\n"));
1406       return 1;
1407    }
1408
1409    if (!send_exclude_list(ua->jcr)) {
1410       bsendmsg(ua, _("Error sending exclude list.\n"));
1411       return 1;
1412    }
1413
1414    if (!send_level_command(ua->jcr)) {
1415       return 1;
1416    }
1417
1418    bnet_fsend(fd, "estimate listing=%d\n", listing);
1419    while (bnet_recv(fd) >= 0) {
1420       bsendmsg(ua, "%s", fd->msg);
1421    }
1422
1423    bnet_sig(fd, BNET_TERMINATE);
1424    bnet_close(fd);
1425    ua->jcr->file_bsock = NULL;
1426
1427    return 1;
1428 }
1429
1430
1431 /*
1432  * print time
1433  */
1434 static int time_cmd(UAContext *ua, char *cmd)
1435 {
1436    char sdt[50];
1437    time_t ttime = time(NULL);
1438    struct tm tm;
1439    localtime_r(&ttime, &tm);
1440    strftime(sdt, sizeof(sdt), "%d-%b-%Y %H:%M:%S", &tm);
1441    bsendmsg(ua, "%s\n", sdt);
1442    return 1;
1443 }
1444
1445
1446
1447 /*
1448  * Delete Pool records (should purge Media with it).
1449  *
1450  *  delete pool=<pool-name>
1451  *  delete media pool=<pool-name> volume=<name>
1452  */
1453 static int delete_cmd(UAContext *ua, char *cmd)
1454 {
1455    static char *keywords[] = {
1456       N_("volume"),
1457       N_("pool"),
1458       N_("job"),
1459       NULL};
1460
1461    if (!open_db(ua)) {
1462       return 1;
1463    }
1464
1465      
1466    switch (find_arg_keyword(ua, keywords)) {
1467    case 0:
1468       delete_volume(ua);     
1469       return 1;
1470    case 1:
1471       delete_pool(ua);
1472       return 1;
1473    case 2:
1474       delete_job(ua);
1475       return 1;
1476    default:
1477       break;
1478    }
1479
1480    bsendmsg(ua, _(
1481 "In general it is not a good idea to delete either a\n"
1482 "Pool or a Volume since they may contain data.\n\n"));
1483
1484    switch (do_keyword_prompt(ua, _("Choose catalog item to delete"), keywords)) {
1485    case 0:
1486       delete_volume(ua);
1487       break;
1488    case 1:
1489       delete_pool(ua);
1490       break;
1491    case 2:
1492       delete_job(ua);
1493       return 1;
1494    default:
1495       bsendmsg(ua, _("Nothing done.\n"));
1496       break;
1497    }
1498    return 1;
1499 }
1500
1501 static int delete_job(UAContext *ua)
1502 {
1503    POOLMEM *query = get_pool_memory(PM_MESSAGE);
1504    JobId_t JobId;
1505
1506    int i = find_arg_with_value(ua, "jobid");
1507    if (i >= 0) {
1508       JobId = str_to_int64(ua->argv[i]);
1509    } else if (!get_pint(ua, _("Enter JobId to delete: "))) {
1510       return 0;
1511    } else {
1512       JobId = ua->pint32_val; 
1513    }
1514    Mmsg(&query, "DELETE FROM Job WHERE JobId=%u", JobId);
1515    db_sql_query(ua->db, query, NULL, (void *)NULL);
1516    Mmsg(&query, "DELETE FROM File WHERE JobId=%u", JobId);
1517    db_sql_query(ua->db, query, NULL, (void *)NULL);
1518    Mmsg(&query, "DELETE FROM JobMedia WHERE JobId=%u", JobId);
1519    db_sql_query(ua->db, query, NULL, (void *)NULL);
1520    free_pool_memory(query);
1521    bsendmsg(ua, _("Job %u and associated records deleted from the catalog.\n"), JobId);
1522    return 1;
1523 }
1524
1525 /*
1526  * Delete media records from database -- dangerous 
1527  */
1528 static int delete_volume(UAContext *ua)
1529 {
1530    MEDIA_DBR mr;
1531
1532    if (!select_media_dbr(ua, &mr)) {
1533       return 1;
1534    }
1535    bsendmsg(ua, _("\nThis command will delete volume %s\n"
1536       "and all Jobs saved on that volume from the Catalog\n"),
1537       mr.VolumeName);
1538
1539    if (!get_yesno(ua, _("Are you sure you want to delete this Volume? (yes/no): "))) {
1540       return 1;
1541    }
1542    if (ua->pint32_val) {
1543       db_delete_media_record(ua->jcr, ua->db, &mr);
1544    }
1545    return 1;
1546 }
1547
1548 /*
1549  * Delete a pool record from the database -- dangerous   
1550  */
1551 static int delete_pool(UAContext *ua)
1552 {
1553    POOL_DBR  pr;
1554    
1555    memset(&pr, 0, sizeof(pr));
1556
1557    if (!get_pool_dbr(ua, &pr)) {
1558       return 1;
1559    }
1560    if (!get_yesno(ua, _("Are you sure you want to delete this Pool? (yes/no): "))) {
1561       return 1;
1562    }
1563    if (ua->pint32_val) {
1564       db_delete_pool_record(ua->jcr, ua->db, &pr);
1565    }
1566    return 1;
1567 }
1568
1569
1570 static void do_mount_cmd(UAContext *ua, char *command)
1571 {
1572    STORE *store;
1573    BSOCK *sd;
1574    char dev_name[MAX_NAME_LENGTH];
1575
1576
1577    if (!open_db(ua)) {
1578       return;
1579    }
1580    Dmsg2(120, "%s: %s\n", command, ua->UA_sock->msg);
1581
1582    store = get_storage_resource(ua, 1);
1583    if (!store) {
1584       return;
1585    }
1586
1587    Dmsg2(120, "Found storage, MediaType=%s DevName=%s\n",
1588       store->media_type, store->dev_name);
1589
1590    ua->jcr->store = store;
1591    if (!connect_to_storage_daemon(ua->jcr, 10, SDConnectTimeout, 1)) {
1592       bsendmsg(ua, _("Failed to connect to Storage daemon.\n"));
1593       return;
1594    }
1595    sd = ua->jcr->store_bsock;
1596    strcpy(dev_name, store->dev_name);
1597    bash_spaces(dev_name);
1598    bnet_fsend(sd, "%s %s", command, dev_name);
1599    while (bnet_recv(sd) >= 0) {
1600       bsendmsg(ua, "%s", sd->msg);
1601    }
1602    bnet_sig(sd, BNET_TERMINATE);
1603    bnet_close(sd);
1604    ua->jcr->store_bsock = NULL;
1605 }
1606
1607 /*
1608  * mount [storage | device] <name>
1609  */
1610 static int mount_cmd(UAContext *ua, char *cmd)
1611 {
1612    do_mount_cmd(ua, "mount");          /* mount */
1613    return 1;
1614 }
1615
1616
1617 /*
1618  * unmount [storage | device] <name>
1619  */
1620 static int unmount_cmd(UAContext *ua, char *cmd)
1621 {
1622    do_mount_cmd(ua, "unmount");          /* unmount */
1623    return 1;
1624 }
1625
1626
1627 /*
1628  * release [storage | device] <name>
1629  */
1630 static int release_cmd(UAContext *ua, char *cmd)
1631 {
1632    do_mount_cmd(ua, "release");          /* release */
1633    return 1;
1634 }
1635
1636
1637 /*
1638  * Switch databases
1639  *   use catalog=<name>
1640  */
1641 static int use_cmd(UAContext *ua, char *cmd)
1642 {
1643    CAT *oldcatalog, *catalog;
1644
1645
1646    close_db(ua);                      /* close any previously open db */
1647    oldcatalog = ua->catalog;
1648
1649    if (!(catalog = get_catalog_resource(ua))) {
1650       ua->catalog = oldcatalog;
1651    } else {
1652       ua->catalog = catalog;
1653    }
1654    if (open_db(ua)) {
1655       bsendmsg(ua, _("Using Catalog name=%s DB=%s\n"),
1656          ua->catalog->hdr.name, ua->catalog->db_name);
1657    }
1658    return 1;
1659 }
1660
1661 int quit_cmd(UAContext *ua, char *cmd) 
1662 {
1663    ua->quit = TRUE;
1664    return 1;
1665 }
1666
1667 /*
1668  * Wait until no job is running 
1669  */
1670 int wait_cmd(UAContext *ua, char *cmd) 
1671 {
1672    bmicrosleep(0, 200000);            /* let job actually start */
1673    for (int running=1; running; ) {
1674       running = 0;
1675       lock_jcr_chain();
1676       for (JCR *jcr=NULL; (jcr=get_next_jcr(jcr)); ) {
1677          if (jcr->JobId != 0) {
1678             running = 1;
1679             free_locked_jcr(jcr);
1680             break;
1681          }
1682          free_locked_jcr(jcr);
1683       }
1684       unlock_jcr_chain();
1685       if (running) {
1686          bmicrosleep(1, 0);
1687       }
1688    }
1689    return 1;
1690 }
1691
1692
1693 static int help_cmd(UAContext *ua, char *cmd)
1694 {
1695    unsigned int i;
1696
1697    bsendmsg(ua, _("  Command    Description\n  =======    ===========\n"));
1698    for (i=0; i<comsize; i++) {
1699       bsendmsg(ua, _("  %-10s %s\n"), _(commands[i].key), _(commands[i].help));
1700    }
1701    bsendmsg(ua, _("\nWhen at a prompt, entering a period cancels the command.\n\n"));
1702    return 1;
1703 }
1704
1705 static int version_cmd(UAContext *ua, char *cmd)
1706 {
1707    bsendmsg(ua, "%s Version: " VERSION " (" BDATE ")\n", my_name);
1708    return 1;
1709 }
1710
1711
1712 /* A bit brain damaged in that if the user has not done
1713  * a "use catalog xxx" command, we simply find the first
1714  * catalog resource and open it.
1715  */
1716 int open_db(UAContext *ua)
1717 {
1718    if (ua->db) {
1719       return 1;
1720    }
1721    if (!ua->catalog) {
1722       LockRes();
1723       ua->catalog = (CAT *)GetNextRes(R_CATALOG, NULL);
1724       UnlockRes();
1725       if (!ua->catalog) {    
1726          bsendmsg(ua, _("Could not find a Catalog resource\n"));
1727          return 0;
1728       } else {
1729          bsendmsg(ua, _("Using default Catalog name=%s DB=%s\n"), 
1730             ua->catalog->hdr.name, ua->catalog->db_name);
1731       }
1732    }
1733
1734    ua->jcr->catalog = ua->catalog;
1735
1736    Dmsg0(150, "Open database\n");
1737    ua->db = db_init_database(ua->jcr, ua->catalog->db_name, ua->catalog->db_user,
1738                              ua->catalog->db_password, ua->catalog->db_address,
1739                              ua->catalog->db_port, ua->catalog->db_socket);
1740    if (!ua->db || !db_open_database(ua->jcr, ua->db)) {
1741       bsendmsg(ua, _("Could not open database \"%s\".\n"),
1742                  ua->catalog->db_name);
1743       if (ua->db) {
1744          bsendmsg(ua, "%s", db_strerror(ua->db));
1745       }
1746       close_db(ua);
1747       return 0;
1748    }
1749    ua->jcr->db = ua->db;
1750    Dmsg1(150, "DB %s opened\n", ua->catalog->db_name);
1751    return 1;
1752 }
1753
1754 void close_db(UAContext *ua)
1755 {
1756    if (ua->db) {
1757       db_close_database(ua->jcr, ua->db);
1758    }
1759    ua->db = NULL;
1760 }