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