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