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