]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/tree.c
tree performance improvements
[bacula/bacula] / bacula / src / lib / tree.c
1 /*
2  * Directory tree build/traverse routines
3  * 
4  *    Kern Sibbald, June MMII
5  *
6 */
7 /*
8    Copyright (C) 2002-2004 Kern Sibbald and John Walker
9
10    This program is free software; you can redistribute it and/or
11    modify it under the terms of the GNU General Public License as
12    published by the Free Software Foundation; either version 2 of
13    the License, or (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18    General Public License for more details.
19
20    You should have received a copy of the GNU General Public
21    License along with this program; if not, write to the Free
22    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
23    MA 02111-1307, USA.
24
25  */
26
27
28 #include "bacula.h"
29 #include "findlib/find.h"
30              
31 /*
32  * Define PREPEND if you want the sibling list to
33  *  be prepended otherwise it will be appended when
34  *  a new entry is added.
35  */
36 // #define PREPEND
37
38
39 /* Forward referenced subroutines */
40 static TREE_NODE *search_and_insert_tree_node(char *fname, int type, 
41                TREE_NODE *node, TREE_ROOT *root, TREE_NODE *parent);
42
43 /*
44  * NOTE !!!!! we turn off Debug messages for performance reasons.
45  */
46 #undef Dmsg0
47 #undef Dmsg1
48 #undef Dmsg2
49 #undef Dmsg3
50 #define Dmsg0(n,f)
51 #define Dmsg1(n,f,a1)
52 #define Dmsg2(n,f,a1,a2)
53 #define Dmsg3(n,f,a1,a2,a3)
54
55 /*
56  * This subroutine gets a big buffer.
57  */
58 static void malloc_buf(TREE_ROOT *root, int size)
59 {
60    struct s_mem *mem;
61
62    mem = (struct s_mem *)malloc(size);
63    root->total_size += size;
64    root->blocks++;
65    mem->next = root->mem;
66    root->mem = mem;
67    mem->mem = mem->first;
68    mem->rem = (char *)mem + size - mem->mem;
69    Dmsg2(200, "malloc buf size=%d rem=%d\n", size, mem->rem);
70 }
71
72
73 /*
74  * Note, we allocate a big buffer in the tree root
75  *  from which we allocate nodes. This runs more
76  *  than 100 times as fast as directly using malloc()
77  *  for each of the nodes.
78  */
79 TREE_ROOT *new_tree(int count)
80 {
81    TREE_ROOT *root;
82    uint32_t size;
83
84    if (count < 1000) {                /* minimum tree size */
85       count = 1000;
86    }
87    root = (TREE_ROOT *)malloc(sizeof(TREE_ROOT));
88    memset(root, 0, sizeof(TREE_ROOT));
89    root->type = TN_ROOT;
90    /* Assume filename + node  = 40 characters average length */
91    size = count * (BALIGN(sizeof(TREE_NODE)) + 40);
92    if (count > 1000000 || size > 10000000) {
93       size = 10000000;
94    }
95    Dmsg2(400, "count=%d size=%d\n", count, size);
96    malloc_buf(root, size);
97    root->cached_path = get_pool_memory(PM_FNAME);
98    return root;
99 }
100
101 /* 
102  * Create a new tree node. Size depends on type.
103  */
104 TREE_NODE *new_tree_node(TREE_ROOT *root, int type)
105 {
106    TREE_NODE *node;
107    int asize = BALIGN(sizeof(TREE_NODE));
108
109    if (root->mem->rem < asize) {
110       uint32_t mb_size;
111       if (root->total_size >= 1000000) {
112          mb_size = 1000000;
113       } else {
114          mb_size = 100000;
115       }
116       malloc_buf(root, mb_size);
117    }
118    root->mem->rem -= asize;
119    node = (TREE_NODE *)root->mem->mem;
120    root->mem->mem += asize;
121    memset(node, 0, sizeof(TREE_NODE));
122    node->type = type;
123    return node;
124 }
125
126
127 /*
128  * Allocate bytes for filename in tree structure.
129  *  Keep the pointers properly aligned by allocating
130  *  sizes that are aligned.
131  */
132 static char *tree_alloc(TREE_ROOT *root, int size)
133 {
134    char *buf;
135    int asize = BALIGN(size);
136
137    if (root->mem->rem < asize) {
138       uint32_t mb_size;
139       if (root->total_size >= 1000000) {
140          mb_size = 1000000;
141       } else {
142          mb_size = 100000;
143       }
144       malloc_buf(root, mb_size);
145    }
146    root->mem->rem -= asize;
147    buf = root->mem->mem;
148    root->mem->mem += asize;
149    return buf;
150 }
151
152
153 /* This routine frees the whole tree */
154 void free_tree(TREE_ROOT *root)
155 {
156    struct s_mem *mem, *rel;
157
158    for (mem=root->mem; mem; ) {
159       rel = mem;
160       mem = mem->next;
161       free(rel);
162    }
163    if (root->cached_path) {
164       free_pool_memory(root->cached_path);
165    }
166    Dmsg2(400, "Total size=%u blocks=%d\n", root->total_size, root->blocks);
167    free(root);
168    return;
169 }
170
171
172
173 /* 
174  * Insert a node in the tree. This is the main subroutine
175  *   called when building a tree.
176  *
177  */
178 TREE_NODE *insert_tree_node(char *path, TREE_NODE *node, 
179                             TREE_ROOT *root, TREE_NODE *parent)
180 {
181    char *p, *q, *fname;
182    int path_len = strlen(path);
183
184    Dmsg1(100, "insert_tree_node: %s\n", path);
185    /*
186     * If trailing slash, strip it
187     */
188    if (path_len > 0) {
189       q = path + path_len - 1;
190       if (*q == '/') {
191          *q = 0;                      /* strip trailing slash */
192       } else {
193          q = NULL;                    /* no trailing slash */
194       }
195    } else {
196       q = NULL;                       /* no trailing slash */
197    }
198    p = strrchr(path, '/');            /* separate path and filename */
199    if (p) {
200       fname = p + 1;
201       if (!parent) {                  /* if no parent, we need to make one */
202          *p = 0;                      /* terminate path */
203          Dmsg1(100, "make_tree_path for %s\n", path);
204          path_len = strlen(path);     /* get new length */
205          if (path_len == root->cached_path_len &&
206              strcmp(path, root->cached_path) == 0) {
207             parent = root->cached_parent;
208          } else {
209             root->cached_path_len = path_len;
210             pm_strcpy(&root->cached_path, path);
211             parent = make_tree_path(path, root);
212             root->cached_parent = parent; 
213          }
214          Dmsg1(100, "parent=%s\n", parent->fname);
215          *p = '/';                    /* restore full path */
216       }
217    } else {
218       fname = path;
219       if (!parent) {
220          parent = (TREE_NODE *)root;
221          node->type = TN_DIR_NLS;
222       }
223       Dmsg1(100, "No / found: %s\n", path);
224    }
225
226    node = search_and_insert_tree_node(fname, 0, node, root, parent);
227    if (q) {                           /* if trailing slash on entry */
228       *q = '/';                       /*  restore it */
229    }
230    return node;
231 }
232
233 /*
234  * Ensure that all appropriate nodes for a full path exist in
235  *  the tree.
236  */
237 TREE_NODE *make_tree_path(char *path, TREE_ROOT *root)
238 {
239    TREE_NODE *parent, *node;
240    char *fname, *p;
241    int type = TN_NEWDIR;
242
243    Dmsg1(100, "make_tree_path: %s\n", path);
244    if (*path == 0) {
245       Dmsg0(100, "make_tree_path: parent=*root*\n");
246       return (TREE_NODE *)root;
247    }
248    p = strrchr(path, '/');           /* get last dir component of path */
249    if (p) {
250       fname = p + 1;
251       *p = 0;                         /* terminate path */
252       parent = make_tree_path(path, root);
253       *p = '/';                       /* restore full name */
254    } else {
255       fname = path;
256       parent = (TREE_NODE *)root;
257       type = TN_DIR_NLS;
258    }
259    node = search_and_insert_tree_node(fname, type, NULL, root, parent);
260    return node;
261 }  
262
263 /*
264  *  See if the fname already exists. If not insert a new node for it.
265  */
266 static TREE_NODE *search_and_insert_tree_node(char *fname, int type, 
267                TREE_NODE *node, TREE_ROOT *root, TREE_NODE *parent)
268 {
269    TREE_NODE *sibling, *last_sibling;
270    uint16_t fname_len = strlen(fname);
271
272    /* Is it already a sibling? */
273    for (sibling=parent->child; sibling; sibling=sibling->sibling) {
274       Dmsg2(100, "sibling->fname=%s fname=%s\n", sibling->fname, fname);
275       if (sibling->fname_len == fname_len &&
276           strcmp(sibling->fname, fname) == 0) {
277          Dmsg1(100, "make_tree_path: found parent=%s\n", parent->fname);
278          return sibling;
279       }
280       last_sibling = sibling;
281    }
282    /* Must add */
283    if (!node) {
284       node = new_tree_node(root, type);
285    }
286    Dmsg1(100, "append_tree_node: %s\n", fname);
287    node->fname_len = fname_len;
288    node->fname = tree_alloc(root, node->fname_len + 1);
289    strcpy(node->fname, fname);
290    node->parent = parent;
291    if (!parent->child) {
292       parent->child = node;
293       goto item_link;                 /* No children, so skip search */
294    }
295
296 #ifdef  PREPEND
297    /* Add node to head of sibling chain */
298    node->sibling = parent->child;
299    parent->child = node;
300 #else
301    last_sibling = node;
302 #endif
303
304    /* Maintain a linear chain of nodes */
305 item_link:
306    if (!root->first) {
307       root->first = node;
308       root->last = node;
309    } else {
310       root->last->next = node;
311       root->last = node;
312    }
313    return node;
314 }
315
316 #ifdef SLOW_WAY
317 /* Moved to tree.h to eliminate subroutine call */
318 TREE_NODE *first_tree_node(TREE_ROOT *root)
319 {
320    return root->first;
321 }
322
323 TREE_NODE *next_tree_node(TREE_NODE *node)
324 {
325    return node->next;
326 }
327 #endif
328
329
330
331 int tree_getpath(TREE_NODE *node, char *buf, int buf_size)
332 {
333    if (!node) {
334       buf[0] = 0;
335       return 1;
336    }
337    tree_getpath(node->parent, buf, buf_size);
338    /* 
339     * Fixup for Win32. If we have a Win32 directory and 
340     *    there is only a / in the buffer, remove it since
341     *    win32 names don't generally start with /
342     */
343    if (node->type == TN_DIR_NLS && buf[0] == '/' && buf[1] == 0) {
344       buf[0] = 0;   
345    }
346    bstrncat(buf, node->fname, buf_size);
347    /* Add a slash for all directories unless we are at the root,
348     *  also add a slash to a soft linked file if it has children
349     *  i.e. it is linked to a directory.
350     */
351    if ((node->type != TN_FILE && !(buf[0] == '/' && buf[1] == 0)) ||
352        (node->soft_link && node->child)) {
353       bstrncat(buf, "/", buf_size);
354    }
355    return 1;
356 }
357
358 /* 
359  * Change to specified directory
360  */
361 TREE_NODE *tree_cwd(char *path, TREE_ROOT *root, TREE_NODE *node)
362 {
363    if (strcmp(path, ".") == 0) {
364       return node;
365    }
366    if (strcmp(path, "..") == 0) {
367       if (node->parent) {
368          return node->parent;
369       } else {
370          return node;
371       }
372    }
373    if (path[0] == '/') {
374       Dmsg0(100, "Doing absolute lookup.\n");
375       return tree_relcwd(path+1, root, (TREE_NODE *)root);
376    }
377    Dmsg0(100, "Doing relative lookup.\n");
378    return tree_relcwd(path, root, node);
379 }
380
381
382 /*
383  * Do a relative cwd -- i.e. relative to current node rather than root node
384  */
385 TREE_NODE *tree_relcwd(char *path, TREE_ROOT *root, TREE_NODE *node)
386 {
387    char *p;
388    int len;
389    TREE_NODE *cd;
390
391    if (*path == 0) {
392       return node;
393    }
394    /* Check the current segment only */
395    p = strchr(path, '/');
396    if (p) {
397       len = p - path;
398    } else {
399       len = strlen(path);
400    }
401    Dmsg2(100, "tree_relcwd: len=%d path=%s\n", len, path);
402    for (cd=node->child; cd; cd=cd->sibling) {
403       Dmsg1(100, "tree_relcwd: test cd=%s\n", cd->fname);
404       if (cd->fname[0] == path[0] && len == (int)strlen(cd->fname)    
405           && strncmp(cd->fname, path, len) == 0) {
406          break;
407       }
408    }
409    if (!cd || (cd->type == TN_FILE && !cd->child)) {
410       return NULL;
411    }
412    if (!p) {
413       Dmsg0(100, "tree_relcwd: no more to lookup. found.\n");
414       return cd;
415    }
416    Dmsg2(100, "recurse tree_relcwd with path=%s, cd=%s\n", p+1, cd->fname);
417    /* Check the next segment if any */
418    return tree_relcwd(p+1, root, cd);
419 }
420
421
422
423 #ifdef BUILD_TEST_PROGRAM
424
425 void FillDirectoryTree(char *path, TREE_ROOT *root, TREE_NODE *parent);
426
427 static uint32_t FileIndex = 0;
428 /*
429  * Simple test program for tree routines
430  */
431 int main(int argc, char *argv[])
432 {
433     TREE_ROOT *root;
434     TREE_NODE *node;
435     char buf[MAXPATHLEN];
436
437     root = new_tree();
438     root->fname = tree_alloc(root, 1);
439     *root->fname = 0;
440     root->fname_len = 0;
441
442     FillDirectoryTree("/home/kern/bacula/k", root, NULL);
443
444     for (node = first_tree_node(root); node; node=next_tree_node(node)) {
445        tree_getpath(node, buf, sizeof(buf));
446        Dmsg2(100, "%d: %s\n", node->FileIndex, buf);
447     }
448
449     node = (TREE_NODE *)root;
450     Pmsg0(000, "doing cd /home/kern/bacula/k/techlogs\n");
451     node = tree_cwd("/home/kern/bacula/k/techlogs", root, node);
452     if (node) {
453        tree_getpath(node, buf, sizeof(buf));
454        Dmsg2(100, "findex=%d: cwd=%s\n", node->FileIndex, buf);
455     }
456
457     Pmsg0(000, "doing cd /home/kern/bacula/k/src/testprogs\n");
458     node = tree_cwd("/home/kern/bacula/k/src/testprogs", root, node);
459     if (node) {
460        tree_getpath(node, buf, sizeof(buf));
461        Dmsg2(100, "findex=%d: cwd=%s\n", node->FileIndex, buf);
462     } else {
463        Dmsg0(100, "testprogs not found.\n");
464     }
465
466     free_tree((TREE_NODE *)root);
467
468     return 0;
469 }
470
471 void FillDirectoryTree(char *path, TREE_ROOT *root, TREE_NODE *parent)
472 {
473    TREE_NODE *newparent = NULL;
474    TREE_NODE *node;
475    struct stat statbuf;
476    DIR *dp;
477    struct dirent *dir;
478    char pathbuf[MAXPATHLEN];
479    char file[MAXPATHLEN];
480    int type;
481    int i;
482    
483    Dmsg1(100, "FillDirectoryTree: %s\n", path);
484    dp = opendir(path);
485    if (!dp) {
486       return;
487    }
488    while ((dir = readdir(dp))) {
489       if (strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0) {
490          continue;
491       }
492       bstrncpy(file, dir->d_name, sizeof(file));
493       snprintf(pathbuf, MAXPATHLEN-1, "%s/%s", path, file);
494       if (lstat(pathbuf, &statbuf) < 0) {
495          printf("lstat() failed. ERR=%s\n", strerror(errno));
496          continue;
497       }
498 //      printf("got file=%s, pathbuf=%s\n", file, pathbuf);
499       type = TN_FILE;
500       if (S_ISLNK(statbuf.st_mode))
501          type =  TN_FILE;  /* link */
502       else if (S_ISREG(statbuf.st_mode))
503          type = TN_FILE;
504       else if (S_ISDIR(statbuf.st_mode)) {
505          type = TN_DIR;
506       } else if (S_ISCHR(statbuf.st_mode))
507          type = TN_FILE; /* char dev */
508       else if (S_ISBLK(statbuf.st_mode))
509          type = TN_FILE; /* block dev */
510       else if (S_ISFIFO(statbuf.st_mode))
511          type = TN_FILE; /* fifo */
512       else if (S_ISSOCK(statbuf.st_mode))
513          type = TN_FILE; /* sock */
514       else {
515          type = TN_FILE;
516          printf("Unknown file type: 0x%x\n", statbuf.st_mode);
517       }
518
519       Dmsg2(100, "Doing: %d %s\n", type, pathbuf);
520       node = new_tree_node(root, type);
521       node->FileIndex = ++FileIndex;
522       parent = insert_tree_node(pathbuf, node, root, parent);
523       if (S_ISDIR(statbuf.st_mode) && !S_ISLNK(statbuf.st_mode)) {
524          Dmsg2(100, "calling fill. pathbuf=%s, file=%s\n", pathbuf, file);
525          FillDirectoryTree(pathbuf, root, node);
526       }
527    }
528    closedir(dp);
529 }
530
531 #ifndef MAXPATHLEN
532 #define MAXPATHLEN 2000
533 #endif
534
535 void print_tree(char *path, TREE_NODE *tree)
536 {
537    char buf[MAXPATHLEN];
538    char *termchr;
539
540    if (!tree) {
541       return;
542    }
543    switch (tree->type) {
544    case TN_DIR_NLS:
545    case TN_DIR:
546    case TN_NEWDIR:  
547       termchr = "/";
548       break;
549    case TN_ROOT:
550    case TN_FILE:
551    default:
552       termchr = "";
553       break;
554    }
555    Dmsg3(-1, "%s/%s%s\n", path, tree->fname, termchr);
556    switch (tree->type) {
557    case TN_FILE:
558    case TN_NEWDIR:
559    case TN_DIR:
560    case TN_DIR_NLS:
561       bsnprintf(buf, sizeof(buf), "%s/%s", path, tree->fname);
562       print_tree(buf, tree->child);
563       break;
564    case TN_ROOT:
565       print_tree(path, tree->child);
566       break;
567    default:
568       Pmsg1(000, "Unknown node type %d\n", tree->type);
569    }
570    print_tree(path, tree->sibling);
571    return;
572 }
573
574 #endif