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