]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/ua_cmds.c
First cut AutoPrune
[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, 2001, 2002 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 #include "ua.h"
33
34 /* Imported subroutines */
35 extern void run_job(JCR *jcr);
36
37 /* Imported variables */
38 extern int r_first;
39 extern int r_last;
40 extern struct s_res resources[];
41 extern int console_msg_pending;
42 extern FILE *con_fd;
43 extern char my_name[];
44
45 /* Imported functions */
46 extern int statuscmd(UAContext *ua, char *cmd);
47 extern int listcmd(UAContext *ua, char *cmd);
48 extern int showcmd(UAContext *ua, char *cmd);
49 extern int messagescmd(UAContext *ua, char *cmd);
50 extern int autodisplaycmd(UAContext *ua, char *cmd);
51 extern int sqlquerycmd(UAContext *ua, char *cmd);
52 extern int querycmd(UAContext *ua, char *cmd);
53 extern int runcmd(UAContext *ua, char *cmd);
54 extern int retentioncmd(UAContext *ua, char *cmd);
55 extern int prunecmd(UAContext *ua, char *cmd);
56 extern int purgecmd(UAContext *ua, char *cmd);
57
58 /* Forward referenced functions */
59 static int addcmd(UAContext *ua, char *cmd),  createcmd(UAContext *ua, char *cmd), cancelcmd(UAContext *ua, char *cmd);
60 static int setdebugcmd(UAContext *ua, char *cmd);
61 static int helpcmd(UAContext *ua, char *cmd);
62 static int deletecmd(UAContext *ua, char *cmd);
63 static int usecmd(UAContext *ua, char *cmd),  unmountcmd(UAContext *ua, char *cmd);
64 static int labelcmd(UAContext *ua, char *cmd), mountcmd(UAContext *ua, char *cmd), updatecmd(UAContext *ua, char *cmd);
65 static int versioncmd(UAContext *ua, char *cmd), automountcmd(UAContext *ua, char *cmd);
66 static int update_volume(UAContext *ua);
67 static int update_pool(UAContext *ua);
68 static int delete_volume(UAContext *ua);
69 static int delete_pool(UAContext *ua);
70
71 int quitcmd(UAContext *ua, char *cmd);
72
73
74 struct cmdstruct { char *key; int (*func)(UAContext *ua, char *cmd); char *help; }; 
75 static struct cmdstruct commands[] = {
76  { N_("add"),        addcmd,       _("add media to a pool")},
77  { N_("autodisplay"), autodisplaycmd, _("autodisplay [on/off] -- console messages")},
78  { N_("automount"),   automountcmd,   _("automount [on/off] -- after label")},
79  { N_("cancel"),     cancelcmd,    _("cancel job=nnn -- cancel a job")},
80  { N_("create"),     createcmd,    _("create DB Pool from resource")},  
81  { N_("delete"),     deletecmd,    _("delete [pool=<pool-name> | media volume=<volume-name>]")},    
82  { N_("help"),       helpcmd,      _("print this command")},
83  { N_("label"),      labelcmd,     _("label a tape")},
84  { N_("list"),       listcmd,      _("list [pools | jobs | jobtotals | media <pool> | files job=<nn>]; from catalog")},
85  { N_("messages"),   messagescmd,  _("messages")},
86  { N_("mount"),      mountcmd,     _("mount <storage-name>")},
87  { N_("prune"),      prunecmd,     _("prune expired records from catalog")},
88  { N_("purge"),      purgecmd,     _("purge records from catalog")},
89  { N_("run"),        runcmd,       _("run <job-name>")},
90  { N_("setdebug"),   setdebugcmd,  _("sets debug level")},
91  { N_("show"),       showcmd,      _("show (resource records) [jobs | pools | ... | all]")},
92  { N_("sqlquery"),   sqlquerycmd,  _("use SQL to query catalog")}, 
93  { N_("status"),     statuscmd,    _("status [storage | client]=<name>")},
94  { N_("unmount"),    unmountcmd,   _("unmount <storage-name>")},
95  { N_("update"),     updatecmd,    _("update DB Pool from resource")},
96  { N_("use"),        usecmd,       _("use catalog xxx")},
97  { N_("version"),    versioncmd,   _("print Director version")},
98  { N_("quit"),       quitcmd,      _("quit")},
99  { N_("query"),      querycmd,     _("query catalog")},
100  { N_("exit"),       quitcmd,      _("exit = quit")},
101              };
102 #define comsize (sizeof(commands)/sizeof(struct cmdstruct))
103
104 /*
105  * Execute a command from the UA
106  */
107 int do_a_command(UAContext *ua, char *cmd)
108 {
109    unsigned int i;
110    int len, stat;
111    int found;
112
113    found = 0;
114    stat = 1;
115
116    Dmsg1(20, "Command: %s\n", ua->UA_sock->msg);
117    if (ua->argc == 0) {
118       return 1;
119    }
120
121    len = strlen(ua->argk[0]);
122    for (i=0; i<comsize; i++)       /* search for command */
123       if (strncasecmp(ua->argk[0],  _(commands[i].key), len) == 0) {
124          stat = (*commands[i].func)(ua, cmd);   /* go execute command */
125          found = 1;
126          break;
127       }
128    if (!found) {
129       strcat(ua->UA_sock->msg, _(": is an illegal command\n"));
130       ua->UA_sock->msglen = strlen(ua->UA_sock->msg);
131       bnet_send(ua->UA_sock);
132    }
133    return stat;
134 }
135
136
137 /*
138  *  Add Volumes to an existing Pool
139  *
140  */
141 static int addcmd(UAContext *ua, char *cmd) 
142 {
143    POOL_DBR pr;
144    MEDIA_DBR mr;
145    int num, i, max, startnum;
146    int first_id = 0;
147    char name[MAX_NAME_LENGTH];
148
149    bsendmsg(ua, _(
150 "You probably don't want to be using this command since it\n"
151 "creates database records without labeling the Volumes.\n"
152 "You probably want to use the label command.\n\n"));
153
154    if (!open_db(ua)) {
155       return 1;
156    }
157
158    memset(&pr, 0, sizeof(pr));
159    memset(&mr, 0, sizeof(mr));
160
161    if (!get_pool_dbr(ua, &pr)) {
162       return 1;
163    }
164
165    Dmsg4(20, "id=%d Num=%d Max=%d type=%s\n", pr.PoolId, pr.NumVols,
166       pr.MaxVols, pr.PoolType);
167
168    while (pr.MaxVols > 0 && pr.NumVols >= pr.MaxVols) {
169       bsendmsg(ua, _("Pool already has maximum volumes = %d\n"), pr.MaxVols);
170       for (;;) {
171          if (!get_cmd(ua, _("Enter new maximum (zero for unlimited): "))) {
172             return 1;
173          }
174          pr.MaxVols = atoi(ua->cmd);
175          if (pr.MaxVols < 0) {
176             bsendmsg(ua, _("Max vols must be zero or greater.\n"));
177             continue;
178          }
179          break;
180       }
181    }
182
183    if (!get_media_type(ua, mr.MediaType)) {
184       return 1;
185    }
186
187    if (pr.MaxVols == 0) {
188       max = 1000;
189    } else {
190       max = pr.MaxVols - pr.NumVols;
191    }
192    for (;;) {
193       char buf[100]; 
194       sprintf(buf, _("Enter number of Volumes to create. 0=>fixed name. Max=%d: "), max);
195       if (!get_cmd(ua, buf)) {
196          return 1;
197       }
198       num = atoi(ua->cmd);
199       if (num < 0 || num > max) {
200          bsendmsg(ua, _("The number must be between 0 and %d\n"), max);
201          continue;
202       }
203       break;
204    }
205 getVolName:
206    if (num == 0) {
207       if (!get_cmd(ua, _("Enter Volume name: "))) {
208          return 1;
209       }
210    } else {
211       if (!get_cmd(ua, _("Enter base volume name: "))) {
212          return 1;
213       }
214    }
215    if (strchr(ua->cmd, '|')) {
216       bsendmsg(ua, _("Illegal character | in a volume name.\n"));
217       goto getVolName;
218    }
219    if (strlen(ua->cmd) >= MAX_NAME_LENGTH-10) {
220       bsendmsg(ua, _("Volume name too long.\n"));
221       goto getVolName;
222    }
223
224    strcpy(name, ua->cmd);
225    if (num > 0) {
226       strcat(name, "%04d");
227
228       for (;;) {
229          if (!get_cmd(ua, _("Enter the starting number: "))) {
230             return 1;
231          }
232          startnum = atoi(ua->cmd);
233          if (startnum < 1) {
234             bsendmsg(ua, _("Start number must be greater than zero.\n"));
235             continue;
236          }
237          break;
238       }
239    } else {
240       startnum = 1;
241       num = 1;
242    }
243            
244    mr.PoolId = pr.PoolId;
245    strcpy(mr.VolStatus, "Append");
246    mr.Recycle = pr.Recycle;
247    mr.VolRetention = pr.VolRetention;
248    for (i=startnum; i < num+startnum; i++) { 
249       sprintf(mr.VolumeName, name, i);
250       Dmsg1(200, "Create Volume %s\n", mr.VolumeName);
251       if (!db_create_media_record(ua->db, &mr)) {
252          bsendmsg(ua, db_strerror(ua->db));
253          return 1;
254       }
255       if (i == startnum) {
256          first_id = mr.PoolId;
257       }
258    }
259    pr.NumVols += num;
260    Dmsg0(200, "Update pool record.\n"); 
261    if (db_update_pool_record(ua->db, &pr) != 1) {
262       bsendmsg(ua, db_strerror(ua->db));
263       return 1;
264    }
265    bsendmsg(ua, _("%d Volumes created in pool %s\n"), num, pr.Name);
266
267    return 1;
268 }
269
270 /*
271  * Turn auto mount on/off  
272  * 
273  *  automount on 
274  *  automount off
275  */
276 int automountcmd(UAContext *ua, char *cmd)
277 {
278    char *onoff;
279
280    if (ua->argc != 2) {
281       if (!get_cmd(ua, _("Turn on or off? "))) {
282             return 1;
283       }
284       onoff = ua->cmd;
285    } else {
286       onoff = ua->argk[1];
287    }
288
289    ua->automount = (strcasecmp(onoff, _("off")) == 0) ? 0 : 1;
290    return 1; 
291 }
292
293
294 /*
295  * Cancel a job
296  */
297 static int cancelcmd(UAContext *ua, char *cmd)
298 {
299    int i;
300    int njobs = 0;
301    BSOCK *sd, *fd;
302    JCR *jcr = NULL;
303    char JobName[MAX_NAME_LENGTH];
304
305    if (!open_db(ua)) {
306       return 1;
307    }
308
309    for (i=1; i<ua->argc; i++) {
310       if (strcasecmp(ua->argk[i], _("jobid")) == 0) {
311          if (!ua->argv[i]) {
312             break;
313          }
314          if (!(jcr=get_jcr_by_id(atoi(ua->argv[i])))) {
315             bsendmsg(ua, _("JobId %d is not running.\n"), atoi(ua->argv[i]));
316             return 1;
317          }
318          break;
319       } else if (strcasecmp(ua->argk[i], _("job")) == 0) {
320          if (!ua->argv[i]) {
321             break;
322          }
323          if (!(jcr=get_jcr_by_partial_name(ua->argv[i]))) {
324             bsendmsg(ua, _("Job %s is not running.\n"), ua->argv[i]);
325             return 1;
326          }
327          break;
328       }
329    }
330    /* If we still do not have a jcr,
331     *   throw up a list and ask the user to select one.
332     */
333    if (!jcr) {
334       /* Count Jobs running */
335       lock_jcr_chain();
336       for (jcr=NULL; (jcr=get_next_jcr(jcr)); njobs++) {
337          if (jcr->JobId == 0) {      /* this is us */
338             free_locked_jcr(jcr);
339             njobs--;
340             continue;
341          }
342          free_locked_jcr(jcr);
343       }
344       unlock_jcr_chain();
345       if (njobs == 0) {
346          bsendmsg(ua, _("No Jobs running.\n"));
347          return 1;
348       }
349       start_prompt(ua, _("Select Job:\n"));
350       lock_jcr_chain();
351       for (jcr=NULL; (jcr=get_next_jcr(jcr)); ) {
352          if (jcr->JobId == 0) {      /* this is us */
353             free_locked_jcr(jcr);
354             continue;
355          }
356          add_prompt(ua, jcr->Job);
357          free_locked_jcr(jcr);
358       }
359       unlock_jcr_chain();
360       if (do_prompt(ua, _("Choose Job to cancel"), JobName) < 0) {
361          return 1;
362       }
363       if (njobs == 1) {
364          if (!get_cmd(ua, _("Confirm cancel (yes/no): "))) {
365             return 1;
366          }
367          if (strcasecmp(ua->cmd, _("yes")) != 0) {
368             return 1;
369          }
370       }
371       jcr = get_jcr_by_full_name(JobName);
372       if (!jcr) {
373          bsendmsg(ua, _("Job %s not found.\n"), JobName);
374          return 1;
375       }
376    }
377      
378    switch (jcr->JobStatus) {
379    case JS_Created:
380       jcr->JobStatus = JS_Cancelled;
381       bsendmsg(ua, _("JobId %d, Job %s marked to be cancelled.\n"),
382               jcr->JobId, jcr->Job);
383       free_jcr(jcr);
384       return 1;
385          
386    default:
387
388       jcr->JobStatus = JS_Cancelled;
389       /* Cancel File daemon */
390       ua->jcr->client = jcr->client;
391       if (!connect_to_file_daemon(ua->jcr, 10, FDConnectTimeout, 1)) {
392          bsendmsg(ua, _("Failed to connect to File daemon.\n"));
393          free_jcr(jcr);
394          return 1;
395       }
396       Dmsg0(200, "Connected to file daemon\n");
397       fd = ua->jcr->file_bsock;
398       bnet_fsend(fd, "cancel Job=%s\n", jcr->Job);
399       while (bnet_recv(fd) > 0) {
400          bsendmsg(ua, "%s", fd->msg);
401       }
402       bnet_sig(fd, BNET_TERMINATE);
403       bnet_close(fd);
404       ua->jcr->file_bsock = NULL;
405
406       /* Cancel Storage daemon */
407       ua->jcr->store = jcr->store;
408       if (!connect_to_storage_daemon(ua->jcr, 10, SDConnectTimeout, 1)) {
409          bsendmsg(ua, _("Failed to connect to Storage daemon.\n"));
410          free_jcr(jcr);
411          return 1;
412       }
413       Dmsg0(200, "Connected to storage daemon\n");
414       sd = ua->jcr->store_bsock;
415       bnet_fsend(sd, "cancel Job=%s\n", jcr->Job);
416       while (bnet_recv(sd) > 0) {
417          bsendmsg(ua, "%s", sd->msg);
418       }
419       bnet_sig(sd, BNET_TERMINATE);
420       bnet_close(sd);
421       ua->jcr->store_bsock = NULL;
422
423    }
424    free_jcr(jcr);
425
426    return 1; 
427 }
428
429 /*
430  * Create a pool record from a given Pool resource
431  *   Also called from backup.c
432  * Returns: -1  on error
433  *           0  record already exists
434  *           1  record created
435  */
436
437 int create_pool(B_DB *db, POOL *pool)
438 {
439    POOL_DBR  pr;
440
441    memset(&pr, 0, sizeof(POOL_DBR));
442
443    strcpy(pr.Name, pool->hdr.name);
444
445    if (db_get_pool_record(db, &pr)) {
446       return 0;                       /* exists */
447    }
448
449    strcpy(pr.PoolType, pool->pool_type);
450    pr.MaxVols = pool->max_volumes;
451    pr.NumVols = 0;
452    pr.UseOnce = pool->use_volume_once;
453    pr.UseCatalog = pool->use_catalog;
454    pr.AcceptAnyVolume = pool->accept_any_volume;
455    pr.Recycle = pool->Recycle;
456    pr.VolRetention = pool->VolRetention;
457    pr.AutoPrune = pool->AutoPrune;
458    if (pool->label_format) {
459       strcpy(pr.LabelFormat, pool->label_format);
460    } else {
461       strcpy(pr.LabelFormat, "*");    /* none */
462    }
463
464    if (!db_create_pool_record(db, &pr)) {
465       return -1;                      /* error */
466    }
467    return 1;
468 }
469
470
471
472 /*
473  * Create a Pool Record in the database.
474  *  It is always created from the Resource record.
475  */
476 static int createcmd(UAContext *ua, char *cmd) 
477 {
478    POOL *pool;
479
480    if (!open_db(ua)) {
481       return 1;
482    }
483
484    pool = get_pool_resource(ua);
485    if (!pool) {
486       return 1;
487    }
488
489    switch (create_pool(ua->db, pool)) {
490    case 0:
491       bsendmsg(ua, _("Error: Pool %s already exists.\n\
492 Use update to change it.\n"), pool->hdr.name);
493       break;
494
495    case -1:
496       bsendmsg(ua, db_strerror(ua->db));
497       break;
498
499    default:
500      break;
501    }
502    return 1;
503 }
504
505
506
507
508 /*
509  * Update a Pool Record in the database.
510  *  It is always updated from the Resource record.
511  *
512  *    update pool=<pool-name>
513  *         updates pool from Pool resource
514  *    update media pool=<pool-name> volume=<volume-name>
515  *         changes pool info for volume
516  */
517 static int updatecmd(UAContext *ua, char *cmd) 
518 {
519    static char *kw[] = {
520       N_("media"),
521       N_("volume"),
522       N_("pool"),
523       NULL};
524
525    if (!open_db(ua)) {
526       return 1;
527    }
528
529    switch (find_arg_keyword(ua, kw)) {
530       case 0:
531       case 1:
532          update_volume(ua);
533          return 1;
534       case 2:
535          update_pool(ua);
536          return 1;
537       default:
538          break;
539    }
540     
541    start_prompt(ua, _("Update choice:\n"));
542    add_prompt(ua, _("pool"));
543    add_prompt(ua, _("volume"));
544    switch (do_prompt(ua, _("Choose catalog item to update"), NULL)) {
545       case 0:
546          update_pool(ua);
547          break;
548       case 1:
549          update_volume(ua);
550          break;
551       default:
552          break;
553    }
554    return 1;
555 }
556
557 /*
558  * Update a media record -- allows you to change the
559  *  Volume status. E.g. if you want Bacula to stop
560  *  writing on the volume, set it to anything other
561  *  than Append.
562  */              
563 static int update_volume(UAContext *ua)
564 {
565    POOL_DBR pr;
566    MEDIA_DBR mr;
567    int i;
568    static char *kw[] = {
569       "volume",
570       NULL};
571    char *query;
572    char ed1[30];
573
574    memset(&pr, 0, sizeof(pr));
575    memset(&mr, 0, sizeof(mr));
576    if (!get_pool_dbr(ua, &pr)) {
577       return 0;
578    }
579    mr.PoolId = pr.PoolId;
580    mr.VolumeName[0] = 0;
581
582    i = find_arg_keyword(ua, kw);
583    if (i == 0 && ua->argv[i]) {
584       strcpy(mr.VolumeName, ua->argv[i]);
585    }
586    if (mr.VolumeName[0] == 0) {
587       db_list_media_records(ua->db, &mr, prtit, ua);
588       if (!get_cmd(ua, _("Enter Volume name to update: "))) {
589          return 0;
590       }
591       strcpy(mr.VolumeName, ua->cmd);
592    }
593    mr.MediaId = 0;
594    if (!db_get_media_record(ua->db, &mr)) {
595       bsendmsg(ua, _("Volume record for %s not found.\n"), mr.VolumeName);
596       return 0;
597    }
598
599    for (int done=0; !done; ) {
600       start_prompt(ua, _("Parameters to modify:\n"));
601       add_prompt(ua, _("Volume Status"));
602       add_prompt(ua, _("Volume Retention"));
603       add_prompt(ua, _("Done"));
604       switch (do_prompt(ua, _("Select paramter to modify"), NULL)) {
605       case 0:                         /* Volume Status */
606          /* Modify Volume */
607          bsendmsg(ua, _("Current value is: %s\n"), mr.VolStatus);
608          start_prompt(ua, _("Possible Values are:\n"));
609          add_prompt(ua, "Append");
610          add_prompt(ua, "Archive");
611          add_prompt(ua, "Disabled");
612          add_prompt(ua, "Full");
613          if (strcmp(mr.VolStatus, "Purged") == 0) {
614             add_prompt(ua, "Recycle");
615          }
616          add_prompt(ua, "Read-Only");
617          if (do_prompt(ua, _("Choose new Volume Status"), ua->cmd) < 0) {
618             return 1;
619          }
620          strcpy(mr.VolStatus, ua->cmd);
621          query = (char *)get_pool_memory(PM_MESSAGE);
622          Mmsg(&query, "UPDATE Media SET VolStatus=\"%s\" WHERE MediaId=%d",
623             mr.VolStatus, mr.MediaId);
624          if (!db_sql_query(ua->db, query, NULL, NULL)) {  
625             bsendmsg(ua, "%s", db_strerror(ua->db));
626          }       
627          free_pool_memory(query);
628          break;
629       case 1:                         /* Retention */
630          bsendmsg(ua, _("Current value is: %s\n"),
631             edit_btime(mr.VolRetention, ed1));
632          if (!get_cmd(ua, _("Enter Volume Retention period: "))) {
633             return 0;
634          }
635          if (!string_to_btime(ua->cmd, &mr.VolRetention)) {
636             bsendmsg(ua, _("Invalid retention period specified.\n"));
637             break;
638          }
639          query = (char *)get_pool_memory(PM_MESSAGE);
640          Mmsg(&query, "UPDATE Media SET VolRetention=%s WHERE MediaId=%d",
641             edit_uint64(mr.VolRetention, ed1), mr.MediaId);
642          if (!db_sql_query(ua->db, query, NULL, NULL)) {  
643             bsendmsg(ua, "%s", db_strerror(ua->db));
644          }       
645          free_pool_memory(query);
646          break;
647       default:                        /* Done or error */
648          return 0;
649       }
650    }
651    return 1;
652 }
653
654 /* 
655  * Update pool record -- pull info from current POOL resource
656  */
657 static int update_pool(UAContext *ua)
658 {
659    POOL_DBR  pr;
660    int id;
661    POOL *pool;
662    
663    memset(&pr, 0, sizeof(pr));
664    if (!get_pool_dbr(ua, &pr)) {
665       return 1;
666    }
667
668    strcpy(pr.PoolType, pool->pool_type);
669    if (pr.MaxVols != (uint32_t) (pool->max_volumes)) {
670       pr.MaxVols = pool->max_volumes;
671    }
672    if (pr.MaxVols != 0 && pr.MaxVols < pr.NumVols) {
673       pr.MaxVols = pr.NumVols;
674    }
675    pr.UseOnce = pool->use_volume_once;
676    pr.UseCatalog = pool->use_catalog;
677    pr.AcceptAnyVolume = pool->accept_any_volume;
678    if (pool->label_format) {
679       strcpy(pr.LabelFormat, pool->label_format);
680    } else {
681       strcpy(pr.LabelFormat, "*");    /* none */
682    }
683    id = db_update_pool_record(ua->db, &pr);
684    if (id <= 0) {
685       bsendmsg(ua, "Error: db_update_pool_record returned %d\n", id);
686    }
687    return 1;
688 }
689
690
691 static void do_storage_setdebug(UAContext *ua, STORE *store, int level)
692 {
693    BSOCK *sd;
694
695    ua->jcr->store = store;
696    /* Try connecting for up to 15 seconds */
697    bsendmsg(ua, _("Connecting to Storage daemon %s at %s:%d\n"), 
698       store->hdr.name, store->address, store->SDport);
699    if (!connect_to_storage_daemon(ua->jcr, 1, 15, 0)) {
700       bsendmsg(ua, _("Failed to connect to Storage daemon.\n"));
701       return;
702    }
703    Dmsg0(20, _("Connected to storage daemon\n"));
704    sd = ua->jcr->store_bsock;
705    bnet_fsend(sd, "setdebug=%d\n", level);
706    if (bnet_recv(sd) > 0) {
707       bsendmsg(ua, "%s", sd->msg);
708    }
709    bnet_sig(sd, BNET_TERMINATE);
710    bnet_close(sd);
711    ua->jcr->store_bsock = NULL;
712    return;  
713 }
714    
715 static void do_client_setdebug(UAContext *ua, CLIENT *client, int level)
716 {
717    BSOCK *fd;
718
719    /* Connect to File daemon */
720
721    ua->jcr->client = client;
722    /* Try to connect for 15 seconds */
723    bsendmsg(ua, _("Connecting to Client %s at %s:%d\n"), 
724       client->hdr.name, client->address, client->FDport);
725    if (!connect_to_file_daemon(ua->jcr, 1, 15, 0)) {
726       bsendmsg(ua, _("Failed to connect to Client.\n"));
727       return;
728    }
729    Dmsg0(20, "Connected to file daemon\n");
730    fd = ua->jcr->file_bsock;
731    bnet_fsend(fd, "setdebug=%d\n", level);
732    if (bnet_recv(fd) > 0) {
733       bsendmsg(ua, "%s", fd->msg);
734    }
735    bnet_sig(fd, BNET_TERMINATE);
736    bnet_close(fd);
737    ua->jcr->file_bsock = NULL;
738
739    return;  
740 }
741
742
743 static void do_all_setdebug(UAContext *ua, int level)
744 {
745    STORE *store, **unique_store;
746    CLIENT *client, **unique_client;
747    int i, j, found;
748
749    /* Director */
750    debug_level = level;
751
752    /* Count Storage items */
753    LockRes();
754    store = NULL;
755    for (i=0; (store = (STORE *)GetNextRes(R_STORAGE, (RES *)store)); i++)
756       { }
757    unique_store = (STORE **) malloc(i * sizeof(STORE));
758    /* Find Unique Storage address/port */         
759    store = (STORE *)GetNextRes(R_STORAGE, NULL);
760    i = 0;
761    unique_store[i++] = store;
762    while ((store = (STORE *)GetNextRes(R_STORAGE, (RES *)store))) {
763       found = 0;
764       for (j=0; j<i; j++) {
765          if (strcmp(unique_store[j]->address, store->address) == 0 &&
766              unique_store[j]->SDport == store->SDport) {
767             found = 1;
768             break;
769          }
770       }
771       if (!found) {
772          unique_store[i++] = store;
773          Dmsg2(40, "Stuffing: %s:%d\n", store->address, store->SDport);
774       }
775    }
776    UnlockRes();
777
778    /* Call each unique Storage daemon */
779    for (j=0; j<i; j++) {
780       do_storage_setdebug(ua, unique_store[j], level);
781    }
782    free(unique_store);
783
784    /* Count Client items */
785    LockRes();
786    client = NULL;
787    for (i=0; (client = (CLIENT *)GetNextRes(R_CLIENT, (RES *)client)); i++)
788       { }
789    unique_client = (CLIENT **) malloc(i * sizeof(CLIENT));
790    /* Find Unique Client address/port */         
791    client = (CLIENT *)GetNextRes(R_CLIENT, NULL);
792    i = 0;
793    unique_client[i++] = client;
794    while ((client = (CLIENT *)GetNextRes(R_CLIENT, (RES *)client))) {
795       found = 0;
796       for (j=0; j<i; j++) {
797          if (strcmp(unique_client[j]->address, client->address) == 0 &&
798              unique_client[j]->FDport == client->FDport) {
799             found = 1;
800             break;
801          }
802       }
803       if (!found) {
804          unique_client[i++] = client;
805          Dmsg2(40, "Stuffing: %s:%d\n", client->address, client->FDport);
806       }
807    }
808    UnlockRes();
809
810    /* Call each unique File daemon */
811    for (j=0; j<i; j++) {
812       do_client_setdebug(ua, unique_client[j], level);
813    }
814    free(unique_client);
815 }
816
817 /*
818  * setdebug level=nn all
819  */
820 static int setdebugcmd(UAContext *ua, char *cmd)
821 {
822    STORE *store;
823    CLIENT *client;
824    int level;
825    int i;
826
827    if (!open_db(ua)) {
828       return 1;
829    }
830    Dmsg1(20, "setdebug:%s:\n", cmd);
831
832    level = -1;
833    for (i=1; i<ua->argc; i++) {
834       if (strcasecmp(ua->argk[i], _("level")) == 0 && ua->argv[i]) {
835          level = atoi(ua->argv[i]);
836          break;
837       }
838    }
839    if (level < 0) {
840       if (!get_cmd(ua, _("Enter new debug level: "))) {
841          return 1;
842       }
843       level = atoi(ua->cmd);
844    }
845    if (level < 0) {
846       bsendmsg(ua, _("level cannot be negative.\n"));
847       return 1;
848    }
849
850    /* General debug? */
851    for (i=1; i<ua->argc; i++) {
852       if (strcasecmp(ua->argk[i], _("all")) == 0) {
853          do_all_setdebug(ua, level);
854          return 1;
855       }
856       if (strcasecmp(ua->argk[i], _("dir")) == 0 ||
857           strcasecmp(ua->argk[i], _("director")) == 0) {
858          debug_level = level;
859          return 1;
860       }
861       if (strcasecmp(ua->argk[i], _("client")) == 0) {
862          client = NULL;
863          if (ua->argv[i]) {
864             client = (CLIENT *) GetResWithName(R_CLIENT, ua->argv[i]);
865             if (client) {
866                do_client_setdebug(ua, client, level);
867                return 1;
868             }
869          }
870          client = select_client_resource(ua);   
871          if (client) {
872             do_client_setdebug(ua, client, level);
873             return 1;
874          }
875
876          store = get_storage_resource(ua, cmd);
877          if (store) {
878             do_storage_setdebug(ua, store, level);
879             return 1;
880          }
881       }
882    } 
883    /*
884     * We didn't find an appropriate keyword above, so
885     * prompt the user.
886     */
887    start_prompt(ua, _("Available daemons are: \n"));
888    add_prompt(ua, _("Director"));
889    add_prompt(ua, _("Storage"));
890    add_prompt(ua, _("Client"));
891    add_prompt(ua, _("All"));
892    switch(do_prompt(ua, _("Select daemon type to set debug level"), NULL)) {
893       case 0:                         /* Director */
894          debug_level = level;
895          break;
896       case 1:
897          store = get_storage_resource(ua, cmd);
898          if (store) {
899             do_storage_setdebug(ua, store, level);
900          }
901          break;
902       case 2:
903          client = select_client_resource(ua);
904          if (client) {
905             do_client_setdebug(ua, client, level);
906          }
907          break;
908       case 3:
909          do_all_setdebug(ua, level);
910          break;
911       default:
912          break;
913    }
914    return 1;
915 }
916
917
918
919 /*
920  * Delete Pool records (should purge Media with it).
921  *
922  *  delete pool=<pool-name>
923  *  delete media pool=<pool-name> volume=<name>
924  */
925 static int deletecmd(UAContext *ua, char *cmd)
926 {
927    static char *keywords[] = {
928       N_("media"),
929       N_("pool"),
930       NULL};
931
932    if (!open_db(ua)) {
933       return 1;
934    }
935
936    bsendmsg(ua, _(
937 "In general it is not a good idea to delete either a\n"
938 "Pool or Media since in both cases, you may delete Media\n"
939 "that contain data.\n\n"));
940      
941    switch (find_arg_keyword(ua, keywords)) {
942       case 0:
943          delete_volume(ua);     
944          return 1;
945       case 1:
946          delete_pool(ua);
947          return 1;
948       default:
949          break;
950    }
951    switch (do_keyword_prompt(ua, _("Choose catalog item to delete"), keywords)) {
952       case 0:
953          delete_volume(ua);
954          break;
955       case 1:
956          delete_pool(ua);
957          break;
958       default:
959          bsendmsg(ua, _("Nothing done.\n"));
960          break;
961    }
962    return 1;
963 }
964
965 /*
966  * Delete media records from database -- dangerous 
967  */
968 static int delete_volume(UAContext *ua)
969 {
970    POOL_DBR pr;
971    MEDIA_DBR mr;
972
973    if (!select_pool_and_media_dbr(ua, &pr, &mr)) {
974       return 1;
975    }
976    bsendmsg(ua, _("\nThis command will delete volume %s\n"
977       "and all Jobs saved on that volume from the Catalog\n"),
978       mr.VolumeName);
979
980    if (!get_cmd(ua, _("If you want to continue enter pretty please: "))) {
981       return 1;
982    }
983    if (strcmp(ua->cmd, _("pretty please")) == 0) {
984       db_delete_media_record(ua->db, &mr);
985    }
986    return 1;
987 }
988
989 /*
990  * Delete a pool record from the database -- dangerous   
991  */
992 static int delete_pool(UAContext *ua)
993 {
994    POOL_DBR  pr;
995    
996    memset(&pr, 0, sizeof(pr));
997
998    if (!get_pool_dbr(ua, &pr)) {
999       return 1;
1000    }
1001    if (!get_cmd(ua, _("If you want to continue enter pretty please: "))) {
1002       return 1;
1003    }
1004    if (strcmp(ua->cmd, _("pretty please")) == 0) {
1005       db_delete_pool_record(ua->db, &pr);
1006    }
1007    return 1;
1008 }
1009
1010
1011 /*
1012  * Label a tape 
1013  *  
1014  *   label storage=xxx volume=vvv
1015  */
1016 static int labelcmd(UAContext *ua, char *cmd)
1017 {
1018    STORE *store;
1019    BSOCK *sd;
1020    char dev_name[MAX_NAME_LENGTH];
1021    MEDIA_DBR mr;
1022    POOL_DBR pr;
1023    int ok = FALSE;
1024    int mounted = FALSE;
1025    int i;
1026    static char *keyword[] = {
1027       "volume",
1028       NULL};
1029
1030    if (!open_db(ua)) {
1031       return 1;
1032    }
1033    store = get_storage_resource(ua, cmd);
1034    if (!store) {
1035       return 1;
1036    }
1037
1038    i = find_arg_keyword(ua, keyword);
1039    if (i >=0 && ua->argv[i]) {
1040       strcpy(ua->cmd, ua->argv[i]);
1041       goto gotVol;
1042    }
1043
1044 getVol:
1045    if (!get_cmd(ua, _("Enter new Volume name: "))) {
1046       return 1;
1047    }
1048 gotVol:
1049    if (strchr(ua->cmd, '|')) {
1050       bsendmsg(ua, _("Illegal character | in a volume name.\n"));
1051       goto getVol;
1052    }
1053    if (strlen(ua->cmd) >= MAX_NAME_LENGTH) {
1054       bsendmsg(ua, _("Volume name too long.\n"));
1055       goto getVol;
1056    }
1057
1058    memset(&mr, 0, sizeof(mr));
1059    strcpy(mr.VolumeName, ua->cmd);
1060    if (db_get_media_record(ua->db, &mr)) {
1061        bsendmsg(ua, _("Media record for Volume %s already exists.\n"), 
1062           mr.VolumeName);
1063        return 1;
1064    }
1065    strcpy(mr.MediaType, store->media_type);
1066
1067    memset(&pr, 0, sizeof(pr));
1068    if (!select_pool_dbr(ua, &pr)) {
1069       return 1;
1070    }
1071    mr.PoolId = pr.PoolId;
1072    strcpy(mr.VolStatus, "Append");
1073    mr.Recycle = pr.Recycle;
1074    mr.VolRetention = pr.VolRetention;
1075
1076    ua->jcr->store = store;
1077    bsendmsg(ua, _("Connecting to Storage daemon %s at %s:%d ...\n"), 
1078       store->hdr.name, store->address, store->SDport);
1079    if (!connect_to_storage_daemon(ua->jcr, 10, SDConnectTimeout, 1)) {
1080       bsendmsg(ua, _("Failed to connect to Storage daemon.\n"));
1081       return 1;   
1082    }
1083    sd = ua->jcr->store_bsock;
1084    strcpy(dev_name, store->dev_name);
1085    bash_spaces(dev_name);
1086    bash_spaces(mr.VolumeName);
1087    bash_spaces(mr.MediaType);
1088    bash_spaces(pr.Name);
1089    bnet_fsend(sd, _("label %s VolumeName=%s PoolName=%s MediaType=%s"), 
1090       dev_name, mr.VolumeName, pr.Name, mr.MediaType);
1091    bsendmsg(ua, "Sending label command ...\n");
1092    while (bget_msg(sd, 0) > 0) {
1093       bsendmsg(ua, "%s", sd->msg);
1094       if (strncmp(sd->msg, "3000 OK label.", 14) == 0) {
1095          ok = TRUE;
1096       }
1097    }
1098    ua->jcr->store_bsock = NULL;
1099    unbash_spaces(dev_name);
1100    unbash_spaces(mr.VolumeName);
1101    unbash_spaces(mr.MediaType);
1102    unbash_spaces(pr.Name);
1103    if (ok) {
1104       if (db_create_media_record(ua->db, &mr)) {
1105          bsendmsg(ua, _("Media record for Volume=%s successfully created.\n"),
1106             mr.VolumeName);
1107          if (ua->automount) {
1108             bsendmsg(ua, _("Requesting mount %s ...\n"), dev_name);
1109             bash_spaces(dev_name);
1110             bnet_fsend(sd, "mount %s", dev_name);
1111             unbash_spaces(dev_name);
1112             while (bnet_recv(sd) > 0) {
1113                bsendmsg(ua, "%s", sd->msg);
1114                /* Here we can get
1115                 *  3001 OK mount. Device=xxx      or
1116                 *  3001 Mounted Volume vvvv
1117                 */
1118                if (strncmp(sd->msg, "3001 ", 5) == 0) {
1119                   mounted = TRUE;
1120                   /***** ****FIXME***** find job waiting for  
1121                    ***** mount, and change to waiting for SD  
1122                    */
1123                }
1124             }
1125          }
1126       } else {
1127          bsendmsg(ua, "%s", db_strerror(ua->db));
1128       }
1129    }
1130    if (!mounted) {
1131       bsendmsg(ua, _("Do not forget to mount the drive!!!\n"));
1132    }
1133    bnet_sig(sd, BNET_TERMINATE);
1134    bnet_close(sd);
1135    return 1;
1136 }
1137
1138 static void do_mount_cmd(int mount, UAContext *ua, char *cmd)
1139 {
1140    STORE *store;
1141    BSOCK *sd;
1142    char dev_name[MAX_NAME_LENGTH];
1143
1144
1145    if (!open_db(ua)) {
1146       return;
1147    }
1148    Dmsg1(20, "mount: %s\n", ua->UA_sock->msg);
1149
1150    store = get_storage_resource(ua, cmd);
1151    if (!store) {
1152       return;
1153    }
1154
1155    Dmsg2(20, "Found storage, MediaType=%s DevName=%s\n",
1156       store->media_type, store->dev_name);
1157
1158    ua->jcr->store = store;
1159    if (!connect_to_storage_daemon(ua->jcr, 10, SDConnectTimeout, 1)) {
1160       bsendmsg(ua, _("Failed to connect to Storage daemon.\n"));
1161       return;
1162    }
1163    sd = ua->jcr->store_bsock;
1164    strcpy(dev_name, store->dev_name);
1165    bash_spaces(dev_name);
1166    if (mount) {
1167       bnet_fsend(sd, "mount %s", dev_name);
1168    } else {
1169       bnet_fsend(sd, "unmount %s", dev_name);
1170    }
1171    while (bnet_recv(sd) > 0) {
1172       bsendmsg(ua, "%s", sd->msg);
1173       if (strncmp(sd->msg, "3001 OK mount.", 14) == 0) {
1174           /***** ****FIXME**** fix JobStatus */
1175       }
1176    }
1177    bnet_sig(sd, BNET_TERMINATE);
1178    bnet_close(sd);
1179    ua->jcr->store_bsock = NULL;
1180 }
1181
1182 /*
1183  * mount [storage | device] <name>
1184  */
1185 static int mountcmd(UAContext *ua, char *cmd)
1186 {
1187    do_mount_cmd(1, ua, cmd);          /* mount */
1188    return 1;
1189 }
1190
1191
1192 /*
1193  * unmount [storage | device] <name>
1194  */
1195 static int unmountcmd(UAContext *ua, char *cmd)
1196 {
1197    do_mount_cmd(0, ua, cmd);          /* unmount */
1198    return 1;
1199 }
1200
1201
1202 /*
1203  * Switch databases
1204  *   use catalog=<name>
1205  */
1206 static int usecmd(UAContext *ua, char *cmd)
1207 {
1208    CAT *oldcatalog, *catalog;
1209
1210
1211    close_db(ua);                      /* close any previously open db */
1212    oldcatalog = ua->catalog;
1213
1214    if (!(catalog = get_catalog_resource(ua))) {
1215       ua->catalog = oldcatalog;
1216    } else {
1217       ua->catalog = catalog;
1218    }
1219    if (open_db(ua)) {
1220       bsendmsg(ua, _("Using Catalog name=%s DB=%s\n"),
1221          ua->catalog->hdr.name, ua->catalog->db_name);
1222    }
1223    return 1;
1224 }
1225
1226 int quitcmd(UAContext *ua, char *cmd) 
1227 {
1228    ua->quit = TRUE;
1229    return 1;
1230 }
1231
1232 static int helpcmd(UAContext *ua, char *cmd)
1233 {
1234    unsigned int i;
1235
1236 /* usage(); */
1237    bnet_fsend(ua->UA_sock, _("  Command    Description\n  =======    ===========\n"));
1238    for (i=0; i<comsize; i++) {
1239       bnet_fsend(ua->UA_sock, _("  %-10s %s\n"), _(commands[i].key), _(commands[i].help));
1240    }
1241    bnet_fsend(ua->UA_sock, "\n");
1242    return 1;
1243 }
1244
1245 static int versioncmd(UAContext *ua, char *cmd)
1246 {
1247    bsendmsg(ua, "%s Version: " VERSION " (" DATE ")\n", my_name);
1248    return 1;
1249 }
1250
1251
1252 /* A bit brain damaged in that if the user has not done
1253  * a "use catalog xxx" command, we simply find the first
1254  * catalog resource and open it.
1255  */
1256 int open_db(UAContext *ua)
1257 {
1258    if (ua->db) {
1259       return 1;
1260    }
1261    if (!ua->catalog) {
1262       LockRes();
1263       ua->catalog = (CAT *)GetNextRes(R_CATALOG, NULL);
1264       UnlockRes();
1265       if (!ua->catalog) {    
1266          bnet_fsend(ua->UA_sock, _("Could not find a Catalog resource\n"));
1267          return 0;
1268       } else {
1269          bnet_fsend(ua->UA_sock, _("Using default Catalog name=%s DB=%s\n"), 
1270             ua->catalog->hdr.name, ua->catalog->db_name);
1271       }
1272    }
1273
1274    Dmsg0(50, "Open database\n");
1275    ua->db = db_init_database(ua->catalog->db_name, ua->catalog->db_user,
1276                              ua->catalog->db_password);
1277    if (!db_open_database(ua->db)) {
1278       bnet_fsend(ua->UA_sock, _("Could not open DB %s: ERR=%s"), 
1279          ua->catalog->db_name, db_strerror(ua->db));
1280       close_db(ua);
1281       return 0;
1282    }
1283    ua->jcr->db = ua->db;
1284    Dmsg1(50, "DB %s opened\n", ua->catalog->db_name);
1285    return 1;
1286 }
1287
1288 void close_db(UAContext *ua)
1289 {
1290    if (ua->db) {
1291       db_close_database(ua->db);
1292    }
1293    ua->db = NULL;
1294    ua->jcr->db = NULL;
1295 }