accaee35045d815f9e1b29b19694a4bf6a9a7c82
[collectd.git] / src / oracle.c
1 /**
2  * collectd - src/oracle.c
3  * Copyright (C) 2008,2009  Florian octo Forster
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Linking src/oracle.c ("the oracle plugin") statically or dynamically with
19  * other modules is making a combined work based on the oracle plugin. Thus,
20  * the terms and conditions of the GNU General Public License cover the whole
21  * combination.
22  *
23  * In addition, as a special exception, the copyright holders of the oracle
24  * plugin give you permission to combine the oracle plugin with free software
25  * programs or libraries that are released under the GNU LGPL and with code
26  * included in the standard release of the Oracle® Call Interface (OCI) under
27  * the Oracle® Technology Network (OTN) License (or modified versions of such
28  * code, with unchanged license). You may copy and distribute such a system
29  * following the terms of the GNU GPL for the oracle plugin and the licenses of
30  * the other code concerned.
31  *
32  * Note that people who make modified versions of the oracle plugin are not
33  * obligated to grant this special exception for their modified versions; it is
34  * their choice whether to do so. The GNU General Public License gives
35  * permission to release a modified version without this exception; this
36  * exception also makes it possible to release a modified version which carries
37  * forward this exception. However, without this exception the OTN License does
38  * not allow linking with code licensed under the GNU General Public License.
39  *
40  * Oracle® is a registered trademark of Oracle Corporation and/or its
41  * affiliates. Other names may be trademarks of their respective owners.
42  *
43  * Authors:
44  *   Florian octo Forster <octo at noris.net>
45  **/
46
47 #include "collectd.h"
48 #include "common.h"
49 #include "plugin.h"
50 #include "configfile.h"
51 #include "utils_db_query.h"
52
53 #include <oci.h>
54
55 /*
56  * Data types
57  */
58 struct o_database_s
59 {
60   char *name;
61   char *connect_id;
62   char *username;
63   char *password;
64
65   udb_query_t **queries;
66   size_t        queries_num;
67
68   OCISvcCtx *oci_service_context;
69 };
70 typedef struct o_database_s o_database_t;
71
72 /*
73  * Global variables
74  */
75 static udb_query_t  **queries       = NULL;
76 static size_t         queries_num   = 0;
77 static o_database_t **databases     = NULL;
78 static size_t         databases_num = 0;
79
80 OCIEnv   *oci_env = NULL;
81 OCIError *oci_error = NULL;
82
83 /*
84  * Functions
85  */
86 static void o_report_error (const char *where, /* {{{ */
87     const char *what, OCIError *eh)
88 {
89   char buffer[2048];
90   sb4 error_code;
91   int status;
92
93   status = OCIErrorGet (eh, /* record number = */ 1,
94       /* sqlstate = */ NULL,
95       &error_code,
96       (text *) &buffer[0],
97       (ub4) sizeof (buffer),
98       OCI_HTYPE_ERROR);
99   buffer[sizeof (buffer) - 1] = 0;
100
101   if (status == OCI_SUCCESS)
102   {
103     size_t buffer_length;
104
105     buffer_length = strlen (buffer);
106     while ((buffer_length > 0) && (buffer[buffer_length - 1] < 32))
107     {
108       buffer_length--;
109       buffer[buffer_length] = 0;
110     }
111
112     ERROR ("oracle plugin: %s: %s failed: %s",
113         where, what, buffer);
114   }
115   else
116   {
117     ERROR ("oracle plugin: %s: %s failed. Additionally, OCIErrorGet failed with status %i.",
118         where, what, status);
119   }
120 } /* }}} void o_report_error */
121
122 static void o_database_free (o_database_t *db) /* {{{ */
123 {
124   if (db == NULL)
125     return;
126
127   sfree (db->name);
128   sfree (db->connect_id);
129   sfree (db->username);
130   sfree (db->password);
131   sfree (db->queries);
132
133   sfree (db);
134 } /* }}} void o_database_free */
135
136 /* Configuration handling functions {{{
137  *
138  * <Plugin oracle>
139  *   <Query "plugin_instance0">
140  *     Statement "SELECT name, value FROM table"
141  *     <Result>
142  *       Type "gauge"
143  *       InstancesFrom "name"
144  *       ValuesFrom "value"
145  *     </Result>
146  *   </Query>
147  *     
148  *   <Database "plugin_instance1">
149  *     ConnectID "db01"
150  *     Username "oracle"
151  *     Password "secret"
152  *     Query "plugin_instance0"
153  *   </Database>
154  * </Plugin>
155  */
156
157 static int o_config_set_string (char **ret_string, /* {{{ */
158     oconfig_item_t *ci)
159 {
160   char *string;
161
162   if ((ci->values_num != 1)
163       || (ci->values[0].type != OCONFIG_TYPE_STRING))
164   {
165     WARNING ("oracle plugin: The `%s' config option "
166         "needs exactly one string argument.", ci->key);
167     return (-1);
168   }
169
170   string = strdup (ci->values[0].value.string);
171   if (string == NULL)
172   {
173     ERROR ("oracle plugin: strdup failed.");
174     return (-1);
175   }
176
177   if (*ret_string != NULL)
178     free (*ret_string);
179   *ret_string = string;
180
181   return (0);
182 } /* }}} int o_config_set_string */
183
184 static int o_config_add_database (oconfig_item_t *ci) /* {{{ */
185 {
186   o_database_t *db;
187   int status;
188   int i;
189
190   if ((ci->values_num != 1)
191       || (ci->values[0].type != OCONFIG_TYPE_STRING))
192   {
193     WARNING ("oracle plugin: The `Database' block "
194         "needs exactly one string argument.");
195     return (-1);
196   }
197
198   db = (o_database_t *) malloc (sizeof (*db));
199   if (db == NULL)
200   {
201     ERROR ("oracle plugin: malloc failed.");
202     return (-1);
203   }
204   memset (db, 0, sizeof (*db));
205
206   status = o_config_set_string (&db->name, ci);
207   if (status != 0)
208   {
209     sfree (db);
210     return (status);
211   }
212
213   /* Fill the `o_database_t' structure.. */
214   for (i = 0; i < ci->children_num; i++)
215   {
216     oconfig_item_t *child = ci->children + i;
217
218     if (strcasecmp ("ConnectID", child->key) == 0)
219       status = o_config_set_string (&db->connect_id, child);
220     else if (strcasecmp ("Username", child->key) == 0)
221       status = o_config_set_string (&db->username, child);
222     else if (strcasecmp ("Password", child->key) == 0)
223       status = o_config_set_string (&db->password, child);
224     else if (strcasecmp ("Query", child->key) == 0)
225       status = udb_query_pick_from_list (child, queries, queries_num,
226           &db->queries, &db->queries_num);
227     else
228     {
229       WARNING ("oracle plugin: Option `%s' not allowed here.", child->key);
230       status = -1;
231     }
232
233     if (status != 0)
234       break;
235   }
236
237   /* Check that all necessary options have been given. */
238   while (status == 0)
239   {
240     if (db->connect_id == NULL)
241     {
242       WARNING ("oracle plugin: `ConnectID' not given for query `%s'", db->name);
243       status = -1;
244     }
245     if (db->username == NULL)
246     {
247       WARNING ("oracle plugin: `Username' not given for query `%s'", db->name);
248       status = -1;
249     }
250     if (db->password == NULL)
251     {
252       WARNING ("oracle plugin: `Password' not given for query `%s'", db->name);
253       status = -1;
254     }
255
256     break;
257   } /* while (status == 0) */
258
259   /* If all went well, add this query to the list of queries within the
260    * database structure. */
261   if (status == 0)
262   {
263     o_database_t **temp;
264
265     temp = (o_database_t **) realloc (databases,
266         sizeof (*databases) * (databases_num + 1));
267     if (temp == NULL)
268     {
269       ERROR ("oracle plugin: realloc failed");
270       status = -1;
271     }
272     else
273     {
274       databases = temp;
275       databases[databases_num] = db;
276       databases_num++;
277     }
278   }
279
280   if (status != 0)
281   {
282     o_database_free (db);
283     return (-1);
284   }
285
286   return (0);
287 } /* }}} int o_config_add_database */
288
289 static int o_config (oconfig_item_t *ci) /* {{{ */
290 {
291   int i;
292
293   for (i = 0; i < ci->children_num; i++)
294   {
295     oconfig_item_t *child = ci->children + i;
296     if (strcasecmp ("Query", child->key) == 0)
297       udb_query_create (&queries, &queries_num, child);
298     else if (strcasecmp ("Database", child->key) == 0)
299       o_config_add_database (child);
300     else
301     {
302       WARNING ("oracle plugin: Ignoring unknown config option `%s'.", child->key);
303     }
304
305     if (queries_num > 0)
306     {
307       DEBUG ("oracle plugin: o_config: queries_num = %zu; queries[0] = %p; udb_query_get_user_data (queries[0]) = %p;",
308           queries_num, (void *) queries[0], udb_query_get_user_data (queries[0]));
309     }
310   } /* for (ci->children) */
311
312   return (0);
313 } /* }}} int o_config */
314
315 /* }}} End of configuration handling functions */
316
317 static int o_init (void) /* {{{ */
318 {
319   int status;
320
321   if (oci_env != NULL)
322     return (0);
323
324   status = OCIEnvCreate (&oci_env,
325       /* mode = */ OCI_THREADED,
326       /* context        = */ NULL,
327       /* malloc         = */ NULL,
328       /* realloc        = */ NULL,
329       /* free           = */ NULL,
330       /* user_data_size = */ 0,
331       /* user_data_ptr  = */ NULL);
332   if (status != 0)
333   {
334     ERROR ("oracle plugin: OCIEnvCreate failed with status %i.", status);
335     return (-1);
336   }
337
338   status = OCIHandleAlloc (oci_env, (void *) &oci_error, OCI_HTYPE_ERROR,
339       /* user_data_size = */ 0, /* user_data = */ NULL);
340   if (status != OCI_SUCCESS)
341   {
342     ERROR ("oracle plugin: OCIHandleAlloc (OCI_HTYPE_ERROR) failed "
343         "with status %i.", status);
344     return (-1);
345   }
346
347   return (0);
348 } /* }}} int o_init */
349
350 static int o_read_database_query (o_database_t *db, /* {{{ */
351     udb_query_t *q)
352 {
353   char **column_names;
354   char **column_values;
355   size_t column_num;
356
357   OCIStmt *oci_statement;
358
359   /* List of `OCIDefine' pointers. These defines map columns to the buffer
360    * space declared above. */
361   OCIDefine **oci_defines;
362
363   int status;
364   size_t i;
365
366   oci_statement = udb_query_get_user_data (q);
367
368   /* Prepare the statement */
369   if (oci_statement == NULL) /* {{{ */
370   {
371     const char *statement;
372
373     statement = udb_query_get_statement (q);
374     assert (statement != NULL);
375
376     status = OCIHandleAlloc (oci_env, (void *) &oci_statement,
377         OCI_HTYPE_STMT, /* user_data_size = */ 0, /* user_data = */ NULL);
378     if (status != OCI_SUCCESS)
379     {
380       o_report_error ("o_read_database_query", "OCIHandleAlloc", oci_error);
381       oci_statement = NULL;
382       return (-1);
383     }
384
385     status = OCIStmtPrepare (oci_statement, oci_error,
386         (text *) statement, (ub4) strlen (statement),
387         /* language = */ OCI_NTV_SYNTAX,
388         /* mode     = */ OCI_DEFAULT);
389     if (status != OCI_SUCCESS)
390     {
391       o_report_error ("o_read_database_query", "OCIStmtPrepare", oci_error);
392       OCIHandleFree (oci_statement, OCI_HTYPE_STMT);
393       oci_statement = NULL;
394       return (-1);
395     }
396     udb_query_set_user_data (q, oci_statement);
397
398     DEBUG ("oracle plugin: o_read_database_query (%s, %s): "
399         "Successfully allocated statement handle.",
400         db->name, udb_query_get_name (q));
401   } /* }}} */
402
403   assert (oci_statement != NULL);
404
405   /* Execute the statement */
406   status = OCIStmtExecute (db->oci_service_context, /* {{{ */
407       oci_statement,
408       oci_error,
409       /* iters = */ 0,
410       /* rowoff = */ 0,
411       /* snap_in = */ NULL, /* snap_out = */ NULL,
412       /* mode = */ OCI_DEFAULT);
413   if (status != OCI_SUCCESS)
414   {
415     DEBUG ("oracle plugin: o_read_database_query: status = %i (%#x)", status, status);
416     o_report_error ("o_read_database_query", "OCIStmtExecute", oci_error);
417     ERROR ("oracle plugin: o_read_database_query: "
418         "Failing statement was: %s", udb_query_get_statement (q));
419     return (-1);
420   } /* }}} */
421
422   /* Acquire the number of columns returned. */
423   do /* {{{ */
424   {
425     ub4 param_counter = 0;
426     status = OCIAttrGet (oci_statement, OCI_HTYPE_STMT, /* {{{ */
427         &param_counter, /* size pointer = */ NULL, 
428         OCI_ATTR_PARAM_COUNT, oci_error);
429     if (status != OCI_SUCCESS)
430     {
431       o_report_error ("o_read_database_query", "OCIAttrGet", oci_error);
432       return (-1);
433     } /* }}} */
434
435     column_num = (size_t) param_counter;
436   } while (0); /* }}} */
437
438   /* Allocate the following buffers:
439    * 
440    *  +---------------+-----------------------------------+
441    *  ! Name          ! Size                              !
442    *  +---------------+-----------------------------------+
443    *  ! column_names  ! column_num x DATA_MAX_NAME_LEN    !
444    *  ! column_values ! column_num x DATA_MAX_NAME_LEN    !
445    *  ! oci_defines   ! column_num x sizeof (OCIDefine *) !
446    *  +---------------+-----------------------------------+
447    *
448    * {{{ */
449 #define NUMBER_BUFFER_SIZE 64
450
451 #define FREE_ALL \
452   if (column_names != NULL) { \
453     sfree (column_names[0]); \
454     sfree (column_names); \
455   } \
456   if (column_values != NULL) { \
457     sfree (column_values[0]); \
458     sfree (column_values); \
459   } \
460   sfree (oci_defines)
461
462 #define ALLOC_OR_FAIL(ptr, ptr_size) \
463   do { \
464     size_t alloc_size = (size_t) ((ptr_size)); \
465     (ptr) = malloc (alloc_size); \
466     if ((ptr) == NULL) { \
467       FREE_ALL; \
468       ERROR ("oracle plugin: o_read_database_query: malloc failed."); \
469       return (-1); \
470     } \
471     memset ((ptr), 0, alloc_size); \
472   } while (0)
473
474   /* Initialize everything to NULL so the above works. */
475   column_names  = NULL;
476   column_values = NULL;
477   oci_defines   = NULL;
478
479   ALLOC_OR_FAIL (column_names, column_num * sizeof (char *));
480   ALLOC_OR_FAIL (column_names[0], column_num * DATA_MAX_NAME_LEN
481       * sizeof (char));
482   for (i = 1; i < column_num; i++)
483     column_names[i] = column_names[i - 1] + DATA_MAX_NAME_LEN;
484
485   ALLOC_OR_FAIL (column_values, column_num * sizeof (char *));
486   ALLOC_OR_FAIL (column_values[0], column_num * DATA_MAX_NAME_LEN
487       * sizeof (char));
488   for (i = 1; i < column_num; i++)
489     column_values[i] = column_values[i - 1] + DATA_MAX_NAME_LEN;
490
491   ALLOC_OR_FAIL (oci_defines, column_num * sizeof (OCIDefine *));
492   /* }}} End of buffer allocations. */
493
494   /* ``Define'' the returned data, i. e. bind the columns to the buffers
495    * allocated above. */
496   for (i = 0; i < column_num; i++) /* {{{ */
497   {
498     char *column_name;
499     size_t column_name_length;
500     OCIParam *oci_param;
501
502     oci_param = NULL;
503
504     status = OCIParamGet (oci_statement, OCI_HTYPE_STMT, oci_error,
505         (void *) &oci_param, (ub4) (i + 1));
506     if (status != OCI_SUCCESS)
507     {
508       /* This is probably alright */
509       DEBUG ("oracle plugin: o_read_database_query: status = %#x (= %i);", status, status);
510       o_report_error ("o_read_database_query", "OCIParamGet", oci_error);
511       status = OCI_SUCCESS;
512       break;
513     }
514
515     column_name = NULL;
516     column_name_length = 0;
517     status = OCIAttrGet (oci_param, OCI_DTYPE_PARAM,
518         &column_name, &column_name_length, OCI_ATTR_NAME, oci_error);
519     if (status != OCI_SUCCESS)
520     {
521       o_report_error ("o_read_database_query", "OCIAttrGet (OCI_ATTR_NAME)",
522           oci_error);
523       continue;
524     }
525
526     /* Copy the name to column_names. Warning: The ``string'' returned by OCI
527      * may not be null terminated! */
528     memset (column_names[i], 0, DATA_MAX_NAME_LEN);
529     if (column_name_length >= DATA_MAX_NAME_LEN)
530       column_name_length = DATA_MAX_NAME_LEN - 1;
531     memcpy (column_names[i], column_name, column_name_length);
532     column_names[i][column_name_length] = 0;
533
534     DEBUG ("oracle plugin: o_read_database_query: column_names[%zu] = %s; "
535         "column_name_length = %zu;",
536         i, column_names[i], column_name_length);
537
538     status = OCIDefineByPos (oci_statement,
539         &oci_defines[i], oci_error, (ub4) (i + 1),
540         column_values[i], DATA_MAX_NAME_LEN, SQLT_STR,
541         NULL, NULL, NULL, OCI_DEFAULT);
542     if (status != OCI_SUCCESS)
543     {
544       o_report_error ("o_read_database_query", "OCIDefineByPos", oci_error);
545       continue;
546     }
547   } /* for (j = 1; j <= param_counter; j++) */
548   /* }}} End of the ``define'' stuff. */
549
550   status = udb_query_prepare_result (q, hostname_g, /* plugin = */ "oracle",
551       db->name, column_names, column_num);
552   if (status != 0)
553   {
554     ERROR ("oracle plugin: o_read_database_query (%s, %s): "
555         "udb_query_prepare_result failed.",
556         db->name, udb_query_get_name (q));
557     FREE_ALL;
558     return (-1);
559   }
560
561   /* Fetch and handle all the rows that matched the query. */
562   while (42) /* {{{ */
563   {
564     status = OCIStmtFetch2 (oci_statement, oci_error,
565         /* nrows = */ 1, /* orientation = */ OCI_FETCH_NEXT,
566         /* fetch offset = */ 0, /* mode = */ OCI_DEFAULT);
567     if (status == OCI_NO_DATA)
568     {
569       status = OCI_SUCCESS;
570       break;
571     }
572     else if ((status != OCI_SUCCESS) && (status != OCI_SUCCESS_WITH_INFO))
573     {
574       o_report_error ("o_read_database_query", "OCIStmtFetch2", oci_error);
575       break;
576     }
577
578     status = udb_query_handle_result (q, column_values);
579     if (status != 0)
580     {
581       WARNING ("oracle plugin: o_read_database_query (%s, %s): "
582           "udb_query_handle_result failed.",
583           db->name, udb_query_get_name (q));
584     }
585   } /* }}} while (42) */
586
587   /* DEBUG ("oracle plugin: o_read_database_query: This statement succeeded: %s", q->statement); */
588   FREE_ALL;
589
590   return (0);
591 #undef FREE_ALL
592 #undef ALLOC_OR_FAIL
593 } /* }}} int o_read_database_query */
594
595 static int o_read_database (o_database_t *db) /* {{{ */
596 {
597   size_t i;
598   int status;
599
600   if (db->oci_service_context == NULL)
601   {
602     status = OCILogon (oci_env, oci_error,
603         &db->oci_service_context,
604         (OraText *) db->username, (ub4) strlen (db->username),
605         (OraText *) db->password, (ub4) strlen (db->password),
606         (OraText *) db->connect_id, (ub4) strlen (db->connect_id));
607     if (status != OCI_SUCCESS)
608     {
609       o_report_error ("o_read_database", "OCILogon", oci_error);
610       DEBUG ("oracle plugin: OCILogon (%s): db->oci_service_context = %p;",
611           db->connect_id, db->oci_service_context);
612       db->oci_service_context = NULL;
613       return (-1);
614     }
615     assert (db->oci_service_context != NULL);
616   }
617
618   DEBUG ("oracle plugin: o_read_database: db->connect_id = %s; db->oci_service_context = %p;",
619       db->connect_id, db->oci_service_context);
620
621   for (i = 0; i < db->queries_num; i++)
622     o_read_database_query (db, db->queries[i]);
623
624   return (0);
625 } /* }}} int o_read_database */
626
627 static int o_read (void) /* {{{ */
628 {
629   size_t i;
630
631   for (i = 0; i < databases_num; i++)
632     o_read_database (databases[i]);
633
634   return (0);
635 } /* }}} int o_read */
636
637 static int o_shutdown (void) /* {{{ */
638 {
639   size_t i;
640
641   for (i = 0; i < databases_num; i++)
642     if (databases[i]->oci_service_context != NULL)
643     {
644       OCIHandleFree (databases[i]->oci_service_context, OCI_HTYPE_SVCCTX);
645       databases[i]->oci_service_context = NULL;
646     }
647   
648   for (i = 0; i < queries_num; i++)
649   {
650     OCIStmt *oci_statement;
651
652     oci_statement = udb_query_get_user_data (queries[i]);
653     if (oci_statement != NULL)
654     {
655       OCIHandleFree (oci_statement, OCI_HTYPE_STMT);
656       udb_query_set_user_data (queries[i], NULL);
657     }
658   }
659   
660   OCIHandleFree (oci_env, OCI_HTYPE_ENV);
661
662   udb_query_free (queries, queries_num);
663   queries = NULL;
664   queries_num = 0;
665
666   return (0);
667 } /* }}} int o_shutdown */
668
669 void module_register (void) /* {{{ */
670 {
671   plugin_register_complex_config ("oracle", o_config);
672   plugin_register_init ("oracle", o_init);
673   plugin_register_read ("oracle", o_read);
674   plugin_register_shutdown ("oracle", o_shutdown);
675 } /* }}} void module_register */
676
677 /*
678  * vim: shiftwidth=2 softtabstop=2 et fdm=marker
679  */