]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/ua_cmds.c
Make Recycle work -- kes25May02
[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    
664    pool = get_pool_resource(ua);
665    if (!pool) {
666       return 0;
667    }
668
669    memset(&pr, 0, sizeof(pr));
670    strcpy(pr.Name, pool->hdr.name);
671    if (!get_pool_dbr(ua, &pr)) {
672       return 0;
673    }
674    strcpy(pr.PoolType, pool->pool_type);
675    if (pr.MaxVols != (uint32_t) (pool->max_volumes)) {
676       pr.MaxVols = pool->max_volumes;
677    }
678    if (pr.MaxVols != 0 && pr.MaxVols < pr.NumVols) {
679       pr.MaxVols = pr.NumVols;
680    }
681    pr.UseOnce = pool->use_volume_once;
682    pr.UseCatalog = pool->use_catalog;
683    pr.AcceptAnyVolume = pool->accept_any_volume;
684    if (pool->label_format) {
685       strcpy(pr.LabelFormat, pool->label_format);
686    } else {
687       strcpy(pr.LabelFormat, "*");    /* none */
688    }
689    id = db_update_pool_record(ua->db, &pr);
690    if (id <= 0) {
691       bsendmsg(ua, "Error: db_update_pool_record returned %d\n", id);
692    }
693    return 1;
694 }
695
696
697 static void do_storage_setdebug(UAContext *ua, STORE *store, int level)
698 {
699    BSOCK *sd;
700
701    ua->jcr->store = store;
702    /* Try connecting for up to 15 seconds */
703    bsendmsg(ua, _("Connecting to Storage daemon %s at %s:%d\n"), 
704       store->hdr.name, store->address, store->SDport);
705    if (!connect_to_storage_daemon(ua->jcr, 1, 15, 0)) {
706       bsendmsg(ua, _("Failed to connect to Storage daemon.\n"));
707       return;
708    }
709    Dmsg0(20, _("Connected to storage daemon\n"));
710    sd = ua->jcr->store_bsock;
711    bnet_fsend(sd, "setdebug=%d\n", level);
712    if (bnet_recv(sd) > 0) {
713       bsendmsg(ua, "%s", sd->msg);
714    }
715    bnet_sig(sd, BNET_TERMINATE);
716    bnet_close(sd);
717    ua->jcr->store_bsock = NULL;
718    return;  
719 }
720    
721 static void do_client_setdebug(UAContext *ua, CLIENT *client, int level)
722 {
723    BSOCK *fd;
724
725    /* Connect to File daemon */
726
727    ua->jcr->client = client;
728    /* Try to connect for 15 seconds */
729    bsendmsg(ua, _("Connecting to Client %s at %s:%d\n"), 
730       client->hdr.name, client->address, client->FDport);
731    if (!connect_to_file_daemon(ua->jcr, 1, 15, 0)) {
732       bsendmsg(ua, _("Failed to connect to Client.\n"));
733       return;
734    }
735    Dmsg0(20, "Connected to file daemon\n");
736    fd = ua->jcr->file_bsock;
737    bnet_fsend(fd, "setdebug=%d\n", level);
738    if (bnet_recv(fd) > 0) {
739       bsendmsg(ua, "%s", fd->msg);
740    }
741    bnet_sig(fd, BNET_TERMINATE);
742    bnet_close(fd);
743    ua->jcr->file_bsock = NULL;
744
745    return;  
746 }
747
748
749 static void do_all_setdebug(UAContext *ua, int level)
750 {
751    STORE *store, **unique_store;
752    CLIENT *client, **unique_client;
753    int i, j, found;
754
755    /* Director */
756    debug_level = level;
757
758    /* Count Storage items */
759    LockRes();
760    store = NULL;
761    for (i=0; (store = (STORE *)GetNextRes(R_STORAGE, (RES *)store)); i++)
762       { }
763    unique_store = (STORE **) malloc(i * sizeof(STORE));
764    /* Find Unique Storage address/port */         
765    store = (STORE *)GetNextRes(R_STORAGE, NULL);
766    i = 0;
767    unique_store[i++] = store;
768    while ((store = (STORE *)GetNextRes(R_STORAGE, (RES *)store))) {
769       found = 0;
770       for (j=0; j<i; j++) {
771          if (strcmp(unique_store[j]->address, store->address) == 0 &&
772              unique_store[j]->SDport == store->SDport) {
773             found = 1;
774             break;
775          }
776       }
777       if (!found) {
778          unique_store[i++] = store;
779          Dmsg2(40, "Stuffing: %s:%d\n", store->address, store->SDport);
780       }
781    }
782    UnlockRes();
783
784    /* Call each unique Storage daemon */
785    for (j=0; j<i; j++) {
786       do_storage_setdebug(ua, unique_store[j], level);
787    }
788    free(unique_store);
789
790    /* Count Client items */
791    LockRes();
792    client = NULL;
793    for (i=0; (client = (CLIENT *)GetNextRes(R_CLIENT, (RES *)client)); i++)
794       { }
795    unique_client = (CLIENT **) malloc(i * sizeof(CLIENT));
796    /* Find Unique Client address/port */         
797    client = (CLIENT *)GetNextRes(R_CLIENT, NULL);
798    i = 0;
799    unique_client[i++] = client;
800    while ((client = (CLIENT *)GetNextRes(R_CLIENT, (RES *)client))) {
801       found = 0;
802       for (j=0; j<i; j++) {
803          if (strcmp(unique_client[j]->address, client->address) == 0 &&
804              unique_client[j]->FDport == client->FDport) {
805             found = 1;
806             break;
807          }
808       }
809       if (!found) {
810          unique_client[i++] = client;
811          Dmsg2(40, "Stuffing: %s:%d\n", client->address, client->FDport);
812       }
813    }
814    UnlockRes();
815
816    /* Call each unique File daemon */
817    for (j=0; j<i; j++) {
818       do_client_setdebug(ua, unique_client[j], level);
819    }
820    free(unique_client);
821 }
822
823 /*
824  * setdebug level=nn all
825  */
826 static int setdebugcmd(UAContext *ua, char *cmd)
827 {
828    STORE *store;
829    CLIENT *client;
830    int level;
831    int i;
832
833    if (!open_db(ua)) {
834       return 1;
835    }
836    Dmsg1(20, "setdebug:%s:\n", cmd);
837
838    level = -1;
839    for (i=1; i<ua->argc; i++) {
840       if (strcasecmp(ua->argk[i], _("level")) == 0 && ua->argv[i]) {
841          level = atoi(ua->argv[i]);
842          break;
843       }
844    }
845    if (level < 0) {
846       if (!get_cmd(ua, _("Enter new debug level: "))) {
847          return 1;
848       }
849       level = atoi(ua->cmd);
850    }
851    if (level < 0) {
852       bsendmsg(ua, _("level cannot be negative.\n"));
853       return 1;
854    }
855
856    /* General debug? */
857    for (i=1; i<ua->argc; i++) {
858       if (strcasecmp(ua->argk[i], _("all")) == 0) {
859          do_all_setdebug(ua, level);
860          return 1;
861       }
862       if (strcasecmp(ua->argk[i], _("dir")) == 0 ||
863           strcasecmp(ua->argk[i], _("director")) == 0) {
864          debug_level = level;
865          return 1;
866       }
867       if (strcasecmp(ua->argk[i], _("client")) == 0) {
868          client = NULL;
869          if (ua->argv[i]) {
870             client = (CLIENT *) GetResWithName(R_CLIENT, ua->argv[i]);
871             if (client) {
872                do_client_setdebug(ua, client, level);
873                return 1;
874             }
875          }
876          client = select_client_resource(ua);   
877          if (client) {
878             do_client_setdebug(ua, client, level);
879             return 1;
880          }
881
882          store = get_storage_resource(ua, cmd);
883          if (store) {
884             do_storage_setdebug(ua, store, level);
885             return 1;
886          }
887       }
888    } 
889    /*
890     * We didn't find an appropriate keyword above, so
891     * prompt the user.
892     */
893    start_prompt(ua, _("Available daemons are: \n"));
894    add_prompt(ua, _("Director"));
895    add_prompt(ua, _("Storage"));
896    add_prompt(ua, _("Client"));
897    add_prompt(ua, _("All"));
898    switch(do_prompt(ua, _("Select daemon type to set debug level"), NULL)) {
899       case 0:                         /* Director */
900          debug_level = level;
901          break;
902       case 1:
903          store = get_storage_resource(ua, cmd);
904          if (store) {
905             do_storage_setdebug(ua, store, level);
906          }
907          break;
908       case 2:
909          client = select_client_resource(ua);
910          if (client) {
911             do_client_setdebug(ua, client, level);
912          }
913          break;
914       case 3:
915          do_all_setdebug(ua, level);
916          break;
917       default:
918          break;
919    }
920    return 1;
921 }
922
923
924
925 /*
926  * Delete Pool records (should purge Media with it).
927  *
928  *  delete pool=<pool-name>
929  *  delete media pool=<pool-name> volume=<name>
930  */
931 static int deletecmd(UAContext *ua, char *cmd)
932 {
933    static char *keywords[] = {
934       N_("media"),
935       N_("pool"),
936       NULL};
937
938    if (!open_db(ua)) {
939       return 1;
940    }
941
942    bsendmsg(ua, _(
943 "In general it is not a good idea to delete either a\n"
944 "Pool or Media since in both cases, you may delete Media\n"
945 "that contain data.\n\n"));
946      
947    switch (find_arg_keyword(ua, keywords)) {
948       case 0:
949          delete_volume(ua);     
950          return 1;
951       case 1:
952          delete_pool(ua);
953          return 1;
954       default:
955          break;
956    }
957    switch (do_keyword_prompt(ua, _("Choose catalog item to delete"), keywords)) {
958       case 0:
959          delete_volume(ua);
960          break;
961       case 1:
962          delete_pool(ua);
963          break;
964       default:
965          bsendmsg(ua, _("Nothing done.\n"));
966          break;
967    }
968    return 1;
969 }
970
971 /*
972  * Delete media records from database -- dangerous 
973  */
974 static int delete_volume(UAContext *ua)
975 {
976    POOL_DBR pr;
977    MEDIA_DBR mr;
978
979    if (!select_pool_and_media_dbr(ua, &pr, &mr)) {
980       return 1;
981    }
982    bsendmsg(ua, _("\nThis command will delete volume %s\n"
983       "and all Jobs saved on that volume from the Catalog\n"),
984       mr.VolumeName);
985
986    if (!get_cmd(ua, _("If you want to continue enter pretty please: "))) {
987       return 1;
988    }
989    if (strcmp(ua->cmd, _("pretty please")) == 0) {
990       db_delete_media_record(ua->db, &mr);
991    }
992    return 1;
993 }
994
995 /*
996  * Delete a pool record from the database -- dangerous   
997  */
998 static int delete_pool(UAContext *ua)
999 {
1000    POOL_DBR  pr;
1001    
1002    memset(&pr, 0, sizeof(pr));
1003
1004    if (!get_pool_dbr(ua, &pr)) {
1005       return 1;
1006    }
1007    if (!get_cmd(ua, _("If you want to continue enter pretty please: "))) {
1008       return 1;
1009    }
1010    if (strcmp(ua->cmd, _("pretty please")) == 0) {
1011       db_delete_pool_record(ua->db, &pr);
1012    }
1013    return 1;
1014 }
1015
1016
1017 /*
1018  * Label a tape 
1019  *  
1020  *   label storage=xxx volume=vvv
1021  */
1022 static int labelcmd(UAContext *ua, char *cmd)
1023 {
1024    STORE *store;
1025    BSOCK *sd;
1026    char dev_name[MAX_NAME_LENGTH];
1027    MEDIA_DBR mr;
1028    POOL_DBR pr;
1029    int ok = FALSE;
1030    int mounted = FALSE;
1031    int i;
1032    static char *keyword[] = {
1033       "volume",
1034       NULL};
1035
1036    if (!open_db(ua)) {
1037       return 1;
1038    }
1039    store = get_storage_resource(ua, cmd);
1040    if (!store) {
1041       return 1;
1042    }
1043
1044    i = find_arg_keyword(ua, keyword);
1045    if (i >=0 && ua->argv[i]) {
1046       strcpy(ua->cmd, ua->argv[i]);
1047       goto gotVol;
1048    }
1049
1050 getVol:
1051    if (!get_cmd(ua, _("Enter new Volume name: "))) {
1052       return 1;
1053    }
1054 gotVol:
1055    if (strchr(ua->cmd, '|')) {
1056       bsendmsg(ua, _("Illegal character | in a volume name.\n"));
1057       goto getVol;
1058    }
1059    if (strlen(ua->cmd) >= MAX_NAME_LENGTH) {
1060       bsendmsg(ua, _("Volume name too long.\n"));
1061       goto getVol;
1062    }
1063
1064    memset(&mr, 0, sizeof(mr));
1065    strcpy(mr.VolumeName, ua->cmd);
1066    if (db_get_media_record(ua->db, &mr)) {
1067        bsendmsg(ua, _("Media record for Volume %s already exists.\n"), 
1068           mr.VolumeName);
1069        return 1;
1070    }
1071    strcpy(mr.MediaType, store->media_type);
1072
1073    memset(&pr, 0, sizeof(pr));
1074    if (!select_pool_dbr(ua, &pr)) {
1075       return 1;
1076    }
1077    mr.PoolId = pr.PoolId;
1078    strcpy(mr.VolStatus, "Append");
1079    mr.Recycle = pr.Recycle;
1080    mr.VolRetention = pr.VolRetention;
1081
1082    ua->jcr->store = store;
1083    bsendmsg(ua, _("Connecting to Storage daemon %s at %s:%d ...\n"), 
1084       store->hdr.name, store->address, store->SDport);
1085    if (!connect_to_storage_daemon(ua->jcr, 10, SDConnectTimeout, 1)) {
1086       bsendmsg(ua, _("Failed to connect to Storage daemon.\n"));
1087       return 1;   
1088    }
1089    sd = ua->jcr->store_bsock;
1090    strcpy(dev_name, store->dev_name);
1091    bash_spaces(dev_name);
1092    bash_spaces(mr.VolumeName);
1093    bash_spaces(mr.MediaType);
1094    bash_spaces(pr.Name);
1095    bnet_fsend(sd, _("label %s VolumeName=%s PoolName=%s MediaType=%s"), 
1096       dev_name, mr.VolumeName, pr.Name, mr.MediaType);
1097    bsendmsg(ua, "Sending label command ...\n");
1098    while (bget_msg(sd, 0) > 0) {
1099       bsendmsg(ua, "%s", sd->msg);
1100       if (strncmp(sd->msg, "3000 OK label.", 14) == 0) {
1101          ok = TRUE;
1102       }
1103    }
1104    ua->jcr->store_bsock = NULL;
1105    unbash_spaces(dev_name);
1106    unbash_spaces(mr.VolumeName);
1107    unbash_spaces(mr.MediaType);
1108    unbash_spaces(pr.Name);
1109    if (ok) {
1110       if (db_create_media_record(ua->db, &mr)) {
1111          bsendmsg(ua, _("Media record for Volume=%s successfully created.\n"),
1112             mr.VolumeName);
1113          if (ua->automount) {
1114             bsendmsg(ua, _("Requesting mount %s ...\n"), dev_name);
1115             bash_spaces(dev_name);
1116             bnet_fsend(sd, "mount %s", dev_name);
1117             unbash_spaces(dev_name);
1118             while (bnet_recv(sd) > 0) {
1119                bsendmsg(ua, "%s", sd->msg);
1120                /* Here we can get
1121                 *  3001 OK mount. Device=xxx      or
1122                 *  3001 Mounted Volume vvvv
1123                 */
1124                if (strncmp(sd->msg, "3001 ", 5) == 0) {
1125                   mounted = TRUE;
1126                   /***** ****FIXME***** find job waiting for  
1127                    ***** mount, and change to waiting for SD  
1128                    */
1129                }
1130             }
1131          }
1132       } else {
1133          bsendmsg(ua, "%s", db_strerror(ua->db));
1134       }
1135    }
1136    if (!mounted) {
1137       bsendmsg(ua, _("Do not forget to mount the drive!!!\n"));
1138    }
1139    bnet_sig(sd, BNET_TERMINATE);
1140    bnet_close(sd);
1141    return 1;
1142 }
1143
1144 static void do_mount_cmd(int mount, UAContext *ua, char *cmd)
1145 {
1146    STORE *store;
1147    BSOCK *sd;
1148    char dev_name[MAX_NAME_LENGTH];
1149
1150
1151    if (!open_db(ua)) {
1152       return;
1153    }
1154    Dmsg1(20, "mount: %s\n", ua->UA_sock->msg);
1155
1156    store = get_storage_resource(ua, cmd);
1157    if (!store) {
1158       return;
1159    }
1160
1161    Dmsg2(20, "Found storage, MediaType=%s DevName=%s\n",
1162       store->media_type, store->dev_name);
1163
1164    ua->jcr->store = store;
1165    if (!connect_to_storage_daemon(ua->jcr, 10, SDConnectTimeout, 1)) {
1166       bsendmsg(ua, _("Failed to connect to Storage daemon.\n"));
1167       return;
1168    }
1169    sd = ua->jcr->store_bsock;
1170    strcpy(dev_name, store->dev_name);
1171    bash_spaces(dev_name);
1172    if (mount) {
1173       bnet_fsend(sd, "mount %s", dev_name);
1174    } else {
1175       bnet_fsend(sd, "unmount %s", dev_name);
1176    }
1177    while (bnet_recv(sd) > 0) {
1178       bsendmsg(ua, "%s", sd->msg);
1179       if (strncmp(sd->msg, "3001 OK mount.", 14) == 0) {
1180           /***** ****FIXME**** fix JobStatus */
1181       }
1182    }
1183    bnet_sig(sd, BNET_TERMINATE);
1184    bnet_close(sd);
1185    ua->jcr->store_bsock = NULL;
1186 }
1187
1188 /*
1189  * mount [storage | device] <name>
1190  */
1191 static int mountcmd(UAContext *ua, char *cmd)
1192 {
1193    do_mount_cmd(1, ua, cmd);          /* mount */
1194    return 1;
1195 }
1196
1197
1198 /*
1199  * unmount [storage | device] <name>
1200  */
1201 static int unmountcmd(UAContext *ua, char *cmd)
1202 {
1203    do_mount_cmd(0, ua, cmd);          /* unmount */
1204    return 1;
1205 }
1206
1207
1208 /*
1209  * Switch databases
1210  *   use catalog=<name>
1211  */
1212 static int usecmd(UAContext *ua, char *cmd)
1213 {
1214    CAT *oldcatalog, *catalog;
1215
1216
1217    close_db(ua);                      /* close any previously open db */
1218    oldcatalog = ua->catalog;
1219
1220    if (!(catalog = get_catalog_resource(ua))) {
1221       ua->catalog = oldcatalog;
1222    } else {
1223       ua->catalog = catalog;
1224    }
1225    if (open_db(ua)) {
1226       bsendmsg(ua, _("Using Catalog name=%s DB=%s\n"),
1227          ua->catalog->hdr.name, ua->catalog->db_name);
1228    }
1229    return 1;
1230 }
1231
1232 int quitcmd(UAContext *ua, char *cmd) 
1233 {
1234    ua->quit = TRUE;
1235    return 1;
1236 }
1237
1238 static int helpcmd(UAContext *ua, char *cmd)
1239 {
1240    unsigned int i;
1241
1242 /* usage(); */
1243    bnet_fsend(ua->UA_sock, _("  Command    Description\n  =======    ===========\n"));
1244    for (i=0; i<comsize; i++) {
1245       bnet_fsend(ua->UA_sock, _("  %-10s %s\n"), _(commands[i].key), _(commands[i].help));
1246    }
1247    bnet_fsend(ua->UA_sock, "\n");
1248    return 1;
1249 }
1250
1251 static int versioncmd(UAContext *ua, char *cmd)
1252 {
1253    bsendmsg(ua, "%s Version: " VERSION " (" DATE ")\n", my_name);
1254    return 1;
1255 }
1256
1257
1258 /* A bit brain damaged in that if the user has not done
1259  * a "use catalog xxx" command, we simply find the first
1260  * catalog resource and open it.
1261  */
1262 int open_db(UAContext *ua)
1263 {
1264    if (ua->db) {
1265       return 1;
1266    }
1267    if (!ua->catalog) {
1268       LockRes();
1269       ua->catalog = (CAT *)GetNextRes(R_CATALOG, NULL);
1270       UnlockRes();
1271       if (!ua->catalog) {    
1272          bnet_fsend(ua->UA_sock, _("Could not find a Catalog resource\n"));
1273          return 0;
1274       } else {
1275          bnet_fsend(ua->UA_sock, _("Using default Catalog name=%s DB=%s\n"), 
1276             ua->catalog->hdr.name, ua->catalog->db_name);
1277       }
1278    }
1279
1280    Dmsg0(50, "Open database\n");
1281    ua->db = db_init_database(ua->catalog->db_name, ua->catalog->db_user,
1282                              ua->catalog->db_password);
1283    if (!db_open_database(ua->db)) {
1284       bnet_fsend(ua->UA_sock, _("Could not open DB %s: ERR=%s"), 
1285          ua->catalog->db_name, db_strerror(ua->db));
1286       close_db(ua);
1287       return 0;
1288    }
1289    ua->jcr->db = ua->db;
1290    Dmsg1(50, "DB %s opened\n", ua->catalog->db_name);
1291    return 1;
1292 }
1293
1294 void close_db(UAContext *ua)
1295 {
1296    if (ua->db) {
1297       db_close_database(ua->db);
1298    }
1299    ua->db = NULL;
1300    ua->jcr->db = NULL;
1301 }