]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/cats/mysql.c
kes Apply Eric's scratch patch that moves a purged Volume to
[bacula/bacula] / bacula / src / cats / mysql.c
1 /*
2  * Bacula Catalog Database routines specific to MySQL
3  *   These are MySQL specific routines -- hopefully all
4  *    other files are generic.
5  *
6  *    Kern Sibbald, March 2000
7  *
8  *    Version $Id$
9  */
10 /*
11    Bacula® - The Network Backup Solution
12
13    Copyright (C) 2000-2006 Free Software Foundation Europe e.V.
14
15    The main author of Bacula is Kern Sibbald, with contributions from
16    many others, a complete list can be found in the file AUTHORS.
17    This program is Free Software; you can redistribute it and/or
18    modify it under the terms of version two of the GNU General Public
19    License as published by the Free Software Foundation plus additions
20    that are listed in the file LICENSE.
21
22    This program is distributed in the hope that it will be useful, but
23    WITHOUT ANY WARRANTY; without even the implied warranty of
24    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
25    General Public License for more details.
26
27    You should have received a copy of the GNU General Public License
28    along with this program; if not, write to the Free Software
29    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
30    02110-1301, USA.
31
32    Bacula® is a registered trademark of John Walker.
33    The licensor of Bacula is the Free Software Foundation Europe
34    (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
35    Switzerland, email:ftf@fsfeurope.org.
36 */
37
38
39 /* The following is necessary so that we do not include
40  * the dummy external definition of DB.
41  */
42 #define __SQL_C                       /* indicate that this is sql.c */
43
44 #include "bacula.h"
45 #include "cats.h"
46
47 #ifdef HAVE_MYSQL
48
49 /* -----------------------------------------------------------------------
50  *
51  *   MySQL dependent defines and subroutines
52  *
53  * -----------------------------------------------------------------------
54  */
55
56 /* List of open databases */
57 static BQUEUE db_list = {&db_list, &db_list};
58
59 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
60
61 /*
62  * Retrieve database type
63  */
64 const char *
65 db_get_type(void)
66 {
67    return "MySQL";
68 }
69
70 /*
71  * Initialize database data structure. In principal this should
72  * never have errors, or it is really fatal.
73  */
74 B_DB *
75 db_init_database(JCR *jcr, const char *db_name, const char *db_user, const char *db_password,
76                  const char *db_address, int db_port, const char *db_socket,
77                  int mult_db_connections)
78 {
79    B_DB *mdb;
80
81    if (!db_user) {
82       Jmsg(jcr, M_FATAL, 0, _("A user name for MySQL must be supplied.\n"));
83       return NULL;
84    }
85    P(mutex);                          /* lock DB queue */
86    /* Look to see if DB already open */
87    if (!mult_db_connections) {
88       for (mdb=NULL; (mdb=(B_DB *)qnext(&db_list, &mdb->bq)); ) {
89          if (bstrcmp(mdb->db_name, db_name) &&
90              bstrcmp(mdb->db_address, db_address) &&
91              mdb->db_port == db_port) {
92             Dmsg2(100, "DB REopen %d %s\n", mdb->ref_count, db_name);
93             mdb->ref_count++;
94             V(mutex);
95             return mdb;                  /* already open */
96          }
97       }
98    }
99    Dmsg0(100, "db_open first time\n");
100    mdb = (B_DB *) malloc(sizeof(B_DB));
101    memset(mdb, 0, sizeof(B_DB));
102    mdb->db_name = bstrdup(db_name);
103    mdb->db_user = bstrdup(db_user);
104    if (db_password) {
105       mdb->db_password = bstrdup(db_password);
106    }
107    if (db_address) {
108       mdb->db_address = bstrdup(db_address);
109    }
110    if (db_socket) {
111       mdb->db_socket = bstrdup(db_socket);
112    }
113    mdb->db_port = db_port;
114    mdb->have_insert_id = TRUE;
115    mdb->errmsg = get_pool_memory(PM_EMSG); /* get error message buffer */
116    *mdb->errmsg = 0;
117    mdb->cmd = get_pool_memory(PM_EMSG);    /* get command buffer */
118    mdb->cached_path = get_pool_memory(PM_FNAME);
119    mdb->cached_path_id = 0;
120    mdb->ref_count = 1;
121    mdb->fname = get_pool_memory(PM_FNAME);
122    mdb->path = get_pool_memory(PM_FNAME);
123    mdb->esc_name = get_pool_memory(PM_FNAME);
124    mdb->esc_name2 = get_pool_memory(PM_FNAME);
125    qinsert(&db_list, &mdb->bq);            /* put db in list */
126    V(mutex);
127    return mdb;
128 }
129
130 /*
131  * Now actually open the database.  This can generate errors,
132  *  which are returned in the errmsg
133  *
134  * DO NOT close the database or free(mdb) here !!!!
135  */
136 int
137 db_open_database(JCR *jcr, B_DB *mdb)
138 {
139    int errstat;
140
141    P(mutex);
142    if (mdb->connected) {
143       V(mutex);
144       return 1;
145    }
146    mdb->connected = FALSE;
147
148    if ((errstat=rwl_init(&mdb->lock)) != 0) {
149       Mmsg1(&mdb->errmsg, _("Unable to initialize DB lock. ERR=%s\n"),
150             strerror(errstat));
151       V(mutex);
152       return 0;
153    }
154
155    /* connect to the database */
156 #ifdef HAVE_EMBEDDED_MYSQL
157    mysql_server_init(0, NULL, NULL);
158 #endif
159    mysql_init(&(mdb->mysql));
160    Dmsg0(50, "mysql_init done\n");
161    /* If connection fails, try at 5 sec intervals for 30 seconds. */
162    for (int retry=0; retry < 6; retry++) {
163       mdb->db = mysql_real_connect(
164            &(mdb->mysql),                /* db */
165            mdb->db_address,              /* default = localhost */
166            mdb->db_user,                 /*  login name */
167            mdb->db_password,             /*  password */
168            mdb->db_name,                 /* database name */
169            mdb->db_port,                 /* default port */
170            mdb->db_socket,               /* default = socket */
171            CLIENT_FOUND_ROWS);           /* flags */
172
173       /* If no connect, try once more in case it is a timing problem */
174       if (mdb->db != NULL) {
175          break;
176       }
177       bmicrosleep(5,0);
178    }
179
180    mdb->mysql.reconnect = 1;             /* so connection does not timeout */
181    Dmsg0(50, "mysql_real_connect done\n");
182    Dmsg3(50, "db_user=%s db_name=%s db_password=%s\n", mdb->db_user, mdb->db_name,
183             mdb->db_password==NULL?"(NULL)":mdb->db_password);
184
185    if (mdb->db == NULL) {
186       Mmsg2(&mdb->errmsg, _("Unable to connect to MySQL server. \n"
187 "Database=%s User=%s\n"
188 "It is probably not running or your password is incorrect.\n"),
189          mdb->db_name, mdb->db_user);
190       V(mutex);
191       return 0;
192    }
193
194    if (!check_tables_version(jcr, mdb)) {
195       V(mutex);
196       return 0;
197    }
198
199 #ifdef HAVE_THREAD_SAFE_MYSQL
200    my_thread_init();
201 #endif
202
203    mdb->connected = TRUE;
204    V(mutex);
205    return 1;
206 }
207
208 void
209 db_close_database(JCR *jcr, B_DB *mdb)
210 {
211    if (!mdb) {
212       return;
213    }
214    db_end_transaction(jcr, mdb);
215    P(mutex);
216    mdb->ref_count--;
217 #if defined(HAVE_THREAD_SAFE_MYSQL)
218    my_thread_end();
219 #endif
220    if (mdb->ref_count == 0) {
221       qdchain(&mdb->bq);
222       if (mdb->connected && mdb->db) {
223          sql_close(mdb);
224 #ifdef HAVE_EMBEDDED_MYSQL
225          mysql_server_end();
226 #endif
227       }
228       rwl_destroy(&mdb->lock);
229       free_pool_memory(mdb->errmsg);
230       free_pool_memory(mdb->cmd);
231       free_pool_memory(mdb->cached_path);
232       free_pool_memory(mdb->fname);
233       free_pool_memory(mdb->path);
234       free_pool_memory(mdb->esc_name);
235       free_pool_memory(mdb->esc_name2);
236       if (mdb->db_name) {
237          free(mdb->db_name);
238       }
239       if (mdb->db_user) {
240          free(mdb->db_user);
241       }
242       if (mdb->db_password) {
243          free(mdb->db_password);
244       }
245       if (mdb->db_address) {
246          free(mdb->db_address);
247       }
248       if (mdb->db_socket) {
249          free(mdb->db_socket);
250       }
251       free(mdb);
252    }
253    V(mutex);
254 }
255
256 /*
257  * Return the next unique index (auto-increment) for
258  * the given table.  Return NULL on error.
259  *
260  * For MySQL, NULL causes the auto-increment value
261  *  to be updated.
262  */
263 int db_next_index(JCR *jcr, B_DB *mdb, char *table, char *index)
264 {
265    strcpy(index, "NULL");
266    return 1;
267 }
268
269
270 /*
271  * Escape strings so that MySQL is happy
272  *
273  *   NOTE! len is the length of the old string. Your new
274  *         string must be long enough (max 2*old+1) to hold
275  *         the escaped output.
276  */
277 void
278 db_escape_string(char *snew, char *old, int len)
279 {
280    mysql_escape_string(snew, old, len);
281
282 #ifdef DO_IT_MYSELF
283
284 /* Should use mysql_real_escape_string ! */
285 unsigned long mysql_real_escape_string(MYSQL *mysql, char *to, const char *from, unsigned long length);
286
287    char *n, *o;
288
289    n = snew;
290    o = old;
291    while (len--) {
292       switch (*o) {
293       case 0:
294          *n++= '\\';
295          *n++= '0';
296          o++;
297          break;
298       case '\n':
299          *n++= '\\';
300          *n++= 'n';
301          o++;
302          break;
303       case '\r':
304          *n++= '\\';
305          *n++= 'r';
306          o++;
307          break;
308       case '\\':
309          *n++= '\\';
310          *n++= '\\';
311          o++;
312          break;
313       case '\'':
314          *n++= '\\';
315          *n++= '\'';
316          o++;
317          break;
318       case '"':
319          *n++= '\\';
320          *n++= '"';
321          o++;
322          break;
323       case '\032':
324          *n++= '\\';
325          *n++= 'Z';
326          o++;
327          break;
328       default:
329          *n++= *o++;
330       }
331    }
332    *n = 0;
333 #endif
334 }
335
336 /*
337  * Submit a general SQL command (cmd), and for each row returned,
338  *  the sqlite_handler is called with the ctx.
339  */
340 int db_sql_query(B_DB *mdb, const char *query, DB_RESULT_HANDLER *result_handler, void *ctx)
341 {
342    SQL_ROW row;
343    bool send = true;
344
345    db_lock(mdb);
346    if (sql_query(mdb, query) != 0) {
347       Mmsg(mdb->errmsg, _("Query failed: %s: ERR=%s\n"), query, sql_strerror(mdb));
348       db_unlock(mdb);
349       return 0;
350    }
351    if (result_handler != NULL) {
352       if ((mdb->result = sql_use_result(mdb)) != NULL) {
353          int num_fields = 0;
354
355          /* We *must* fetch all rows */
356          while ((row = sql_fetch_row(mdb)) != NULL) {
357             if (send) {
358                /* the result handler returns 1 when it has
359                 *  seen all the data it wants.  However, we
360                 *  loop to the end of the data.
361                 */
362                num_fields++;
363                if (result_handler(ctx, num_fields, row)) {
364                   send = false;
365                }
366             }
367          }
368
369          sql_free_result(mdb);
370       }
371    }
372    db_unlock(mdb);
373    return 1;
374
375 }
376
377 char *my_mysql_batch_lock_path_query = "LOCK TABLES Path write,     " 
378                                        "            batch write,    " 
379                                        "            Path as p write ";
380
381
382 char *my_mysql_batch_lock_filename_query = "LOCK TABLES Filename write,     "
383                                            "            batch write,        "
384                                            "            Filename as f write ";
385
386 char *my_mysql_batch_unlock_tables_query = "UNLOCK TABLES";
387
388 char *my_mysql_batch_fill_path_query = "INSERT IGNORE INTO Path (Path) "
389                                        " SELECT a.Path FROM            " 
390                                        "  (SELECT DISTINCT Path        "
391                                        "     FROM batch) AS a          " 
392                                        " WHERE NOT EXISTS              "
393                                        "  (SELECT Path                 "
394                                        "     FROM Path AS p            "
395                                        "    WHERE p.Path = a.Path)     ";     
396
397 char *my_mysql_batch_fill_filename_query = "INSERT IGNORE INTO Filename (Name)"
398                                            "  SELECT a.Name FROM              " 
399                                            "   (SELECT DISTINCT Name          "
400                                            "      FROM batch) AS a            " 
401                                            "  WHERE NOT EXISTS                "
402                                            "   (SELECT Name                   "
403                                            "      FROM Filename AS f          "
404                                            "      WHERE f.Name = a.Name)      ";
405
406 #endif /* HAVE_MYSQL */
407