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