]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/ua_prune.c
DB changes for Retention Periods
[bacula/bacula] / bacula / src / dird / ua_prune.c
1 /*
2  *
3  *   Bacula Director -- User Agent Database prune Command
4  *      Applies retention periods
5  *
6  *     Kern Sibbald, February MMII
7  */
8
9 /*
10    Copyright (C) 2002 Kern Sibbald and John Walker
11
12    This program is free software; you can redistribute it and/or
13    modify it under the terms of the GNU General Public License as
14    published by the Free Software Foundation; either version 2 of
15    the License, or (at your option) any later version.
16
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20    General Public License for more details.
21
22    You should have received a copy of the GNU General Public
23    License along with this program; if not, write to the Free
24    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25    MA 02111-1307, USA.
26
27  */
28
29 #include "bacula.h"
30 #include "dird.h"
31 #include "ua.h"
32
33 /* Forward referenced functions */
34 int prune_files(UAContext *ua, CLIENT *client);
35 int prune_jobs(UAContext *ua, CLIENT *client);
36 int prune_volume(UAContext *ua, POOL_DBR *pr, MEDIA_DBR *mr);
37 static int mark_media_purged(UAContext *ua, MEDIA_DBR *mr);
38
39
40 #define MAX_DEL_LIST_LEN 1000000
41
42 /*
43  * Select JobIds for File deletion.
44  */
45 static char *select_job =
46    "SELECT JobId from Job "    
47    "WHERE JobTDate < %s "
48    "AND ClientId=%d "
49    "AND PurgedFiles=0";
50
51 /*
52  * List of SQL commands terminated by NULL for deleting
53  *  temporary tables and indicies 
54  */
55 static char *drop_deltabs[] = {
56    "DROP TABLE DelCandidates",
57    "DROP INDEX DelInx1",
58    NULL};
59
60 /*
61  * List of SQL commands to create temp table and indicies
62  */
63 static char *create_deltabs[] = {
64    "CREATE TABLE DelCandidates ("
65       "JobId INTEGER UNSIGNED NOT NULL, "
66       "PurgedFiles TINYINT, "
67       "FileSetId INTEGER UNSIGNED)",
68    "CREATE INDEX DelInx1 ON DelCandidates (JobId)",
69    NULL};
70
71
72 /*
73  * Fill candidates table with all Files subject to being deleted
74  */
75 static char *insert_delcand = 
76    "INSERT INTO DelCandidates "
77    "SELECT JobId, PurgedFiles, FileSetId FROM Job "
78    "WHERE JobTDate < %s " 
79    "AND ClientId=%d";
80
81 /*
82  * Select files from the DelCandidates table that have a
83  * more recent backup -- i.e. are not the only backup.
84  * This is the list of files to delete.
85  */
86 static char *select_del =
87    "SELECT DelCandidates.JobId "
88    "FROM Job,DelCandidates "
89    "WHERE Job.JobTDate >= %s "
90    "AND Job.ClientId=%d "
91    "AND Job.Level='F' "
92    "AND Job.JobStatus='T' "
93    "AND Job.FileSetId=DelCandidates.FileSetId";
94
95 /* In memory list of JobIds */
96 struct s_file_del_ctx {
97    JobId_t *JobId;
98    int num_ids;                       /* ids stored */
99    int max_ids;                       /* size of array */
100    int num_del;                       /* number deleted */
101    int tot_ids;                       /* total to process */
102 };
103
104 struct s_job_del_ctx {
105    JobId_t *JobId;                    /* array of JobIds */
106    char *PurgedFiles;                 /* Array of PurgedFile flags */
107    int num_ids;                       /* ids stored */
108    int max_ids;                       /* size of array */
109    int num_del;                       /* number deleted */
110    int tot_ids;                       /* total to process */
111 };
112
113 struct s_count_ctx {
114    int count;
115 };
116
117
118 /*
119  * Called here to count entries to be deleted 
120  */
121 static int count_handler(void *ctx, int num_fields, char **row)
122 {
123    struct s_count_ctx *cnt = (struct s_count_ctx *)ctx;
124
125    if (row[0]) {
126       cnt->count = atoi(row[0]);
127    } else {
128       cnt->count = 0;
129    }
130    return 0;
131 }
132
133
134 /*
135  * Called here to count entries to be deleted 
136  */
137 static int file_count_handler(void *ctx, int num_fields, char **row)
138 {
139    struct s_file_del_ctx *del = (struct s_file_del_ctx *)ctx;
140    del->tot_ids++;
141    return 0;
142 }
143
144
145 /*
146  * Called here to make in memory list of JobIds to be
147  *  deleted and the associated PurgedFiles flag.
148  *  The in memory list will then be transversed
149  *  to issue the SQL DELETE commands.  Note, the list
150  *  is allowed to get to MAX_DEL_LIST_LEN to limit the
151  *  maximum malloc'ed memory.
152  */
153 static int job_delete_handler(void *ctx, int num_fields, char **row)
154 {
155    struct s_job_del_ctx *del = (struct s_job_del_ctx *)ctx;
156
157    if (del->num_ids == MAX_DEL_LIST_LEN) {  
158       return 1;
159    }
160    if (del->num_ids == del->max_ids) {
161       del->max_ids = (del->max_ids * 3) / 2;
162       del->JobId = (JobId_t *)brealloc(del->JobId, sizeof(JobId_t) * del->max_ids);
163       del->PurgedFiles = (char *)brealloc(del->PurgedFiles, del->max_ids);
164    }
165    del->JobId[del->num_ids] = (JobId_t)strtod(row[0], NULL);
166    del->PurgedFiles[del->num_ids++] = (char)atoi(row[0]);
167    return 0;
168 }
169
170 static int file_delete_handler(void *ctx, int num_fields, char **row)
171 {
172    struct s_file_del_ctx *del = (struct s_file_del_ctx *)ctx;
173
174    if (del->num_ids == MAX_DEL_LIST_LEN) {  
175       return 1;
176    }
177    if (del->num_ids == del->max_ids) {
178       del->max_ids = (del->max_ids * 3) / 2;
179       del->JobId = (JobId_t *)brealloc(del->JobId, sizeof(JobId_t) *
180          del->max_ids);
181    }
182    del->JobId[del->num_ids++] = (JobId_t)strtod(row[0], NULL);
183    return 0;
184 }
185
186 /*
187  *   Prune records from database
188  *
189  *    prune files (from) client=xxx
190  *    prune jobs (from) client=xxx
191  *    prune volume=xxx  
192  */
193 int prunecmd(UAContext *ua, char *cmd)
194 {
195    CLIENT *client;
196    POOL_DBR pr;
197    MEDIA_DBR mr;
198
199    static char *keywords[] = {
200       N_("Files"),
201       N_("Jobs"),
202       N_("Volume"),
203       NULL};
204    if (!open_db(ua)) {
205       return 1;
206    }
207    switch (find_arg_keyword(ua, keywords)) {
208    case 0:
209       client = select_client_resource(ua);
210       prune_files(ua, client);
211       return 1;
212    case 1:
213       client = select_client_resource(ua);
214       prune_jobs(ua, client);
215       return 1;
216    case 2:
217       if (!select_pool_and_media_dbr(ua, &pr, &mr)) {
218          return 1;
219       }
220       prune_volume(ua, &pr, &mr);
221       return 1;
222    default:
223       break;
224    }
225    switch (do_keyword_prompt(ua, _("Choose item to prune"), keywords)) {
226    case 0:
227       client = select_client_resource(ua);
228       if (!client) {
229          return 1;
230       }
231       prune_files(ua, client);
232       break;
233    case 1:
234       client = select_client_resource(ua);
235       if (!client) {
236          return 1;
237       }
238       prune_jobs(ua, client);
239       break;
240    case 2:
241       if (!select_pool_and_media_dbr(ua, &pr, &mr)) {
242          return 1;
243       }
244       prune_volume(ua, &pr, &mr);
245       return 1;
246    }
247    return 1;
248 }
249
250 /*
251  * Prune File records from the database. For any Job which
252  * is older than the retention period, we unconditionally delete
253  * all File records for that Job.  This is simple enough that no
254  * temporary tables are needed. We simply make an in memory list of
255  * the JobIds meeting the prune conditions, then delete all File records
256  * pointing to each of those JobIds.
257  */
258 int prune_files(UAContext *ua, CLIENT *client)
259 {
260    struct s_file_del_ctx del;
261    char *query = (char *)get_pool_memory(PM_MESSAGE);
262    int i;
263    btime_t now, period;
264    CLIENT_DBR cr;
265    char ed1[50];
266
267    memset(&cr, 0, sizeof(cr));
268    memset(&del, 0, sizeof(del));
269    strcpy(cr.Name, client->hdr.name);
270    if (!db_create_client_record(ua->db, &cr)) {
271       return 0;
272    }
273
274    period = client->FileRetention;
275    now = (btime_t)time(NULL);
276        
277    Mmsg(&query, select_job, edit_uint64(now - period, ed1), cr.ClientId);
278
279    Dmsg1(050, "select sql=%s\n", query);
280  
281    if (!db_sql_query(ua->db, query, file_count_handler, (void *)&del)) {
282       bsendmsg(ua, "%s", db_strerror(ua->db));
283       Dmsg0(050, "Count failed\n");
284       goto bail_out;
285    }
286       
287    if (del.tot_ids == 0) {
288       bsendmsg(ua, _("No Files found for client %s to prune from %s catalog.\n"),
289          client->hdr.name, client->catalog->hdr.name);
290       goto bail_out;
291    }
292
293    if (del.tot_ids < MAX_DEL_LIST_LEN) {
294       del.max_ids = del.tot_ids + 1;
295    } else {
296       del.max_ids = MAX_DEL_LIST_LEN; 
297    }
298    del.tot_ids = 0;
299
300    del.JobId = (JobId_t *)malloc(sizeof(JobId_t) * del.max_ids);
301
302    db_sql_query(ua->db, query, file_delete_handler, (void *)&del);
303
304    for (i=0; i < del.num_ids; i++) {
305       Dmsg1(050, "Delete JobId=%d\n", del.JobId[i]);
306       Mmsg(&query, "DELETE FROM File WHERE JobId=%d", del.JobId[i]);
307       db_sql_query(ua->db, query, NULL, (void *)NULL);
308       /* 
309        * Now mark Job as having files purged. This is necessary to
310        * avoid having too many Jobs to process in future prunings. If
311        * we don't do this, the number of JobId's in our in memory list
312        * will grow very large.
313        */
314       Mmsg(&query, "UPDATE Job Set PurgedFiles=1 WHERE JobId=%d", del.JobId[i]);
315       db_sql_query(ua->db, query, NULL, (void *)NULL);
316       Dmsg1(050, "Del sql=%s\n", query);
317    }
318    bsendmsg(ua, _("%d Files for client %s pruned from %s catalog.\n"), del.num_ids,
319       client->hdr.name, client->catalog->hdr.name);
320    
321 bail_out:
322    if (del.JobId) {
323       free(del.JobId);
324    }
325    free_pool_memory(query);
326    return 1;
327 }
328
329
330 static void drop_temp_tables(UAContext *ua) 
331 {
332    int i;
333    for (i=0; drop_deltabs[i]; i++) {
334       db_sql_query(ua->db, drop_deltabs[i], NULL, (void *)NULL);
335    }
336 }
337
338 static int create_temp_tables(UAContext *ua) 
339 {
340    int i;
341    /* Create temp tables and indicies */
342    for (i=0; create_deltabs[i]; i++) {
343       if (!db_sql_query(ua->db, create_deltabs[i], NULL, (void *)NULL)) {
344          bsendmsg(ua, "%s", db_strerror(ua->db));
345          Dmsg0(050, "create DelTables table failed\n");
346          return 0;
347       }
348    }
349    return 1;
350 }
351
352
353
354 /*
355  * Purging Jobs is a bit more complicated than purging Files
356  * because we delete Job records only if there is a more current
357  * backup of the FileSet. Otherwise, we keep the Job record.
358  * In other words, we never delete the only Job record that
359  * contains a current backup of a FileSet. This prevents the
360  * Volume from being recycled and destroying a current backup.
361  */
362 int prune_jobs(UAContext *ua, CLIENT *client)
363 {
364    struct s_job_del_ctx del;
365    struct s_count_ctx cnt;
366    char *query = (char *)get_pool_memory(PM_MESSAGE);
367    int i;
368    btime_t now, period;
369    CLIENT_DBR cr;
370    char ed1[50];
371
372    memset(&cr, 0, sizeof(cr));
373    memset(&del, 0, sizeof(del));
374    strcpy(cr.Name, client->hdr.name);
375    if (!db_create_client_record(ua->db, &cr)) {
376       return 0;
377    }
378
379    period = client->JobRetention;
380    now = (btime_t)time(NULL);
381
382    /* Drop any previous temporary tables still there */
383    drop_temp_tables(ua);
384
385    /* Create temp tables and indicies */
386    if (!create_temp_tables(ua)) {
387       goto bail_out;
388    }
389
390    /* 
391     * Select all files that are older than the JobRetention period
392     *  and stuff them into the "DeletionCandidates" table.
393     */
394    edit_uint64(now - period, ed1);
395    Mmsg(&query, insert_delcand, ed1, cr.ClientId);
396
397    if (!db_sql_query(ua->db, query, NULL, (void *)NULL)) {
398       bsendmsg(ua, "%s", db_strerror(ua->db));
399       Dmsg0(050, "insert delcand failed\n");
400       goto bail_out;
401    }
402
403    strcpy(query, "SELECT count(*) FROM DelCandidates");
404    
405    Dmsg1(100, "select sql=%s\n", query);
406  
407    if (!db_sql_query(ua->db, query, count_handler, (void *)&cnt)) {
408       bsendmsg(ua, "%s", db_strerror(ua->db));
409       Dmsg0(050, "Count failed\n");
410       goto bail_out;
411    }
412       
413    if (cnt.count == 0) {
414       bsendmsg(ua, _("No Jobs for client %s found to prune from %s catalog.\n"),
415          client->hdr.name, client->catalog->hdr.name);
416       goto bail_out;
417    }
418
419    if (cnt.count < MAX_DEL_LIST_LEN) {
420       del.max_ids = cnt.count + 1;
421    } else {
422       del.max_ids = MAX_DEL_LIST_LEN; 
423    }
424    del.JobId = (JobId_t *)malloc(sizeof(JobId_t) * del.max_ids);
425    del.PurgedFiles = (char *)malloc(del.max_ids);
426
427    Mmsg(&query, select_del, ed1, cr.ClientId);
428    db_sql_query(ua->db, query, job_delete_handler, (void *)&del);
429
430    /* 
431     * OK, now we have the list of JobId's to be pruned, first check
432     * if the Files have been purged, if not, purge (delete) them.
433     * Then delete the Job entry, and finally and JobMedia records.
434     */
435    for (i=0; i < del.num_ids; i++) {
436       Dmsg1(050, "Delete JobId=%d\n", del.JobId[i]);
437       if (!del.PurgedFiles[i]) {
438          Mmsg(&query, "DELETE FROM File WHERE JobId=%d", del.JobId[i]);
439          db_sql_query(ua->db, query, NULL, (void *)NULL);
440          Dmsg1(050, "Del sql=%s\n", query);
441       }
442
443       Mmsg(&query, "DELETE FROM Job WHERE JobId=%d", del.JobId[i]);
444       db_sql_query(ua->db, query, NULL, (void *)NULL);
445       Dmsg1(050, "Del sql=%s\n", query);
446
447       Mmsg(&query, "DELETE FROM JobMedia WHERE JobId=%d", del.JobId[i]);
448       db_sql_query(ua->db, query, NULL, (void *)NULL);
449       Dmsg1(050, "Del sql=%s\n", query);
450    }
451    bsendmsg(ua, _("%d Jobs for client %s pruned from %s catalog.\n"), del.num_ids,
452       client->hdr.name, client->catalog->hdr.name);
453    
454 bail_out:
455    drop_temp_tables(ua);
456    if (del.JobId) {
457       free(del.JobId);
458    }
459    if (del.PurgedFiles) {
460       free(del.PurgedFiles);
461    }
462    free_pool_memory(query);
463    return 1;
464 }
465
466 /*
467  * Prune volumes
468  */
469 int prune_volume(UAContext *ua, POOL_DBR *pr, MEDIA_DBR *mr)
470 {
471    char *query = (char *)get_pool_memory(PM_MESSAGE);
472    struct s_count_ctx cnt;
473    struct s_file_del_ctx del;
474    int i;
475    JOB_DBR jr;
476    btime_t now, period;
477
478    memset(&jr, 0, sizeof(jr));
479    memset(&del, 0, sizeof(del));
480    cnt.count = 0;
481    Mmsg(&query, "SELECT count(*) FROM JobMedia WHERE MediaId=%d", mr->MediaId);
482    if (!db_sql_query(ua->db, query, count_handler, (void *)&cnt)) {
483       bsendmsg(ua, "%s", db_strerror(ua->db));
484       Dmsg0(050, "Count failed\n");
485       goto bail_out;
486    }
487       
488    if (cnt.count == 0) {
489       bsendmsg(ua, "There are no Jobs associated with Volume %s. It is purged.\n",
490          mr->VolumeName);
491       if (!mark_media_purged(ua, mr)) {
492          goto bail_out;
493       }
494       goto bail_out;
495    }
496
497    if (cnt.count < MAX_DEL_LIST_LEN) {
498       del.max_ids = cnt.count + 1;
499    } else {
500       del.max_ids = MAX_DEL_LIST_LEN; 
501    }
502
503    del.JobId = (JobId_t *)malloc(sizeof(JobId_t) * del.max_ids);
504
505    Mmsg(&query, "SELECT JobId FROM JobMedia WHERE MediaId=%d", mr->MediaId);
506    if (!db_sql_query(ua->db, query, file_delete_handler, (void *)&del)) {
507       bsendmsg(ua, "%s", db_strerror(ua->db));
508       Dmsg0(050, "Count failed\n");
509       goto bail_out;
510    }
511
512    /* Use Volume Retention to purge Jobs and Files */
513    period = mr->VolRetention;
514    now = (btime_t)time(NULL);
515
516    for (i=0; i < del.num_ids; i++) {
517       jr.JobId = del.JobId[i];
518       if (!db_get_job_record(ua->db, &jr)) {
519          continue;
520       }
521       if (jr.JobTDate >= (now - period)) {
522          continue;
523       }
524       Dmsg1(050, "Delete JobId=%d\n", del.JobId[i]);
525       Mmsg(&query, "DELETE FROM File WHERE JobId=%d", del.JobId[i]);
526       db_sql_query(ua->db, query, NULL, (void *)NULL);
527       Mmsg(&query, "DELETE FROM Job WHERE JobId=%d", del.JobId[i]);
528       db_sql_query(ua->db, query, NULL, (void *)NULL);
529       Mmsg(&query, "DELETE FROM JobMedia WHERE JobId=%d", del.JobId[i]);
530       db_sql_query(ua->db, query, NULL, (void *)NULL);
531       Dmsg1(050, "Del sql=%s\n", query);
532       del.num_del++;
533    }
534    if (del.JobId) {
535       free(del.JobId);
536    }
537    bsendmsg(ua, _("%d Jobs on Volume %s pruned from catalog.\n"), del.num_del,
538       mr->VolumeName);
539
540    /* If purged, mark it so */
541    if (del.num_ids == del.num_del) {
542       mark_media_purged(ua, mr);
543    }
544
545 bail_out:   
546    free_pool_memory(query);
547    return 1;
548 }
549
550 static int mark_media_purged(UAContext *ua, MEDIA_DBR *mr)
551 {
552    if (strcmp(mr->VolStatus, "Append") == 0 || 
553        strcmp(mr->VolStatus, "Full")   == 0) {
554       strcpy(mr->VolStatus, "Purged");
555       if (!db_update_media_record(ua->db, mr)) {
556          bsendmsg(ua, "%s", db_strerror(ua->db));
557          return 0;
558       }
559    }
560    return 1;
561 }