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