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