]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/pythonlib.c
- Fix seg fault in SD when referencing Alert Command.
[bacula/bacula] / bacula / src / lib / pythonlib.c
1 /*
2  *
3  * Bacula common code library interface to Python
4  *
5  * Kern Sibbald, November MMIV
6  *
7  *   Version $Id$
8  *
9  */
10
11 /*
12    Copyright (C) 2004-2005 Kern Sibbald
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 "jcr.h"
33
34 #ifdef HAVE_PYTHON
35
36 #undef _POSIX_C_SOURCE
37 #include <Python.h>
38
39 /* Imported subroutines */
40 extern PyMethodDef JobMethods[];
41
42 static PyObject *bacula_module = NULL;    /* We create this */
43 static PyObject *StartUp_module = NULL;   /* We import this */
44
45 /* These are the daemon events or methods that are defined */
46 static PyObject *JobStart_method = NULL;
47 static PyObject *JobEnd_method = NULL;
48 static PyObject *Exit_method = NULL;
49
50 static PyObject *set_bacula_events(PyObject *self, PyObject *args);
51 static PyObject *bacula_write(PyObject *self, PyObject *args);
52
53 PyObject *find_method(PyObject *eventsObject, PyObject *method, const char *name);
54
55 /* Define Bacula daemon method entry points */
56 static PyMethodDef BaculaMethods[] = {
57     {"set_events", set_bacula_events, METH_VARARGS, "Define Bacula events."},
58     {"write", bacula_write, METH_VARARGS, "Write output."},
59     {NULL, NULL, 0, NULL}             /* last item */
60 };
61
62
63 /*
64  * This is a Bacula Job type as defined in Python. We store a pointer
65  *   to the jcr. That is all we need, but the user's script may keep
66  *   local data attached to this. 
67  */
68 typedef struct s_JobObject {
69     PyObject_HEAD
70     JCR *jcr;
71 } JobObject;
72
73 static PyTypeObject JobType = {
74     PyObject_HEAD_INIT(NULL)
75     0,                         /*ob_size*/
76     "bacula.jcr",              /*tp_name*/
77     sizeof(JobObject),         /*tp_basicsize*/
78     0,                         /*tp_itemsize*/
79     0,                         /*tp_dealloc*/
80     0,                         /*tp_print*/
81     0,                         /*tp_getattr*/
82     0,                         /*tp_setattr*/
83     0,                         /*tp_compare*/
84     0,                         /*tp_repr*/
85     0,                         /*tp_as_number*/
86     0,                         /*tp_as_sequence*/
87     0,                         /*tp_as_mapping*/
88     0,                         /*tp_hash */
89     0,                         /*tp_call*/
90     0,                         /*tp_str*/
91     0,                         /*tp_getattro*/
92     0,                         /*tp_setattro*/
93     0,                         /*tp_as_buffer*/
94     Py_TPFLAGS_DEFAULT, /*tp_flags*/
95     "Job objects",             /* tp_doc */
96     0,                         /* tp_traverse */
97     0,                         /* tp_clear */
98     0,                         /* tp_richcompare */
99     0,                         /* tp_weaklistoffset */
100     0,                         /* tp_iter */
101     0,                         /* tp_iternext */
102     JobMethods,                /* tp_methods */
103     0,                         /* tp_members */
104     0,                         /* tp_getset */
105     0,                         /* tp_base */
106     0,                         /* tp_dict */
107     0,                         /* tp_descr_get */
108     0,                         /* tp_descr_set */
109     0,                         /* tp_dictoffset */
110     0,                         /* tp_init */
111     0,                         /* tp_alloc */
112     0,                         /* tp_new */
113 };
114
115 /* Return the JCR pointer from the JobObject */
116 JCR *get_jcr_from_PyObject(PyObject *self)
117 {
118    return ((JobObject *)self)->jcr;
119 }
120
121
122 /* Start the interpreter */
123 void init_python_interpreter(const char *progname, const char *scripts,
124     const char *module)
125 {
126    char buf[MAXSTRING];
127
128    if (!scripts || scripts[0] == 0) {
129       return;
130    }
131
132    Py_SetProgramName((char *)progname);
133    Py_Initialize();
134    PyEval_InitThreads();
135    bacula_module = Py_InitModule("bacula", BaculaMethods);
136    if (!bacula_module) {
137       Jmsg0(NULL, M_ERROR_TERM, 0, "Could not initialize Python\n");
138    }
139    bsnprintf(buf, sizeof(buf), "import sys\n"
140             "sys.path.append('%s')\n", scripts);
141    if (PyRun_SimpleString(buf) != 0) {
142       Jmsg1(NULL, M_ERROR_TERM, 0, "Could not Run Python string %s\n", buf);
143    }   
144    JobType.tp_methods = JobMethods;
145    if (PyType_Ready(&JobType) != 0) {
146       Jmsg0(NULL, M_ERROR_TERM, 0, "Could not initialize Python Job type.\n");
147       PyErr_Print();
148    }   
149    StartUp_module = PyImport_ImportModule((char *)module);
150    if (!StartUp_module) {
151       Emsg2(M_ERROR, 0, "Could not import Python script %s/%s. Python disabled.\n",
152            scripts, module);
153       if (PyErr_Occurred()) {
154          PyErr_Print();
155          Dmsg0(000, "Python Import error.\n");
156       }
157    }
158    PyEval_ReleaseLock();
159 }
160
161
162 void term_python_interpreter()
163 {
164    if (StartUp_module) {
165       Py_XDECREF(StartUp_module);
166       Py_Finalize();
167    }
168 }
169
170 static PyObject *set_bacula_events(PyObject *self, PyObject *args)
171 {
172    PyObject *eObject;
173
174    Dmsg0(100, "In set_bacula_events.\n");
175    if (!PyArg_ParseTuple(args, "O:set_bacula_events", &eObject)) {
176       return NULL;
177    }
178    JobStart_method = find_method(eObject, JobStart_method, "JobStart");
179    JobEnd_method = find_method(eObject, JobEnd_method, "JobEnd");
180    Exit_method = find_method(eObject, Exit_method, "Exit");
181
182    Py_XINCREF(eObject);
183    Py_INCREF(Py_None);
184    return Py_None;
185 }
186
187 /* Write text to daemon output */
188 static PyObject *bacula_write(PyObject *self, PyObject *args)
189 {
190    char *text;
191    if (!PyArg_ParseTuple(args, "s:write", &text)) {
192       return NULL;
193    }
194    if (text) {
195       Jmsg(NULL, M_INFO, 0, "%s", text);
196    }
197    Py_INCREF(Py_None);
198    return Py_None;
199 }
200
201
202 /*
203  * Check that a method exists and is callable.
204  */
205 PyObject *find_method(PyObject *eventsObject, PyObject *method, const char *name)
206 {
207    Py_XDECREF(method);             /* release old method if any */
208    method = PyObject_GetAttrString(eventsObject, (char *)name);
209    if (method == NULL) {
210        Dmsg1(000, "Python method %s not found\n", name);
211    } else if (PyCallable_Check(method) == 0) {
212        Dmsg1(000, "Python object %s found but not a method.\n", name);
213        Py_XDECREF(method);
214        method = NULL;
215    } else {
216        Dmsg1(100, "Got method %s\n", name);
217    }
218    return method; 
219 }
220
221
222 /*
223  * Generate and process a Bacula event by importing a Python
224  *  module and running it.
225  *
226  *  Returns: 0 if Python not configured or module not found
227  *          -1 on Python error
228  *           1 OK
229  */
230 int generate_daemon_event(JCR *jcr, const char *event)
231 {
232    PyObject *pJob;
233    int stat = -1;
234    PyObject *result = NULL;
235
236    if (!StartUp_module) {
237       return 0;
238    }
239
240    PyEval_AcquireLock();
241    if (strcmp(event, "JobStart") == 0) {
242       if (!JobStart_method) {
243          stat = 0;
244          goto bail_out;
245       }
246       /* Create JCR argument to send to function */
247       pJob = (PyObject *)PyObject_New(JobObject, &JobType);
248       if (!pJob) {
249          Jmsg(jcr, M_ERROR, 0, "Could not create Python Job Object.\n");
250          goto bail_out;
251       }
252       ((JobObject *)pJob)->jcr = jcr;
253       bstrncpy(jcr->event, event, sizeof(jcr->event));
254       result = PyObject_CallFunction(JobStart_method, "O", pJob);
255       jcr->event[0] = 0;             /* no event in progress */
256       if (result == NULL) {
257          JobStart_method = NULL;
258          if (PyErr_Occurred()) {
259             PyErr_Print();
260             Dmsg0(000, "Python JobStart error.\n");
261          }
262          Jmsg(jcr, M_ERROR, 0, "Python function \"%s\" not found.\n", event);
263          Py_XDECREF(pJob);
264          goto bail_out;
265       }
266       jcr->Python_job = (void *)pJob;
267       stat = 1;                       /* OK */
268       goto jobstart_ok;
269
270    } else if (strcmp(event, "JobEnd") == 0) {
271       if (!JobEnd_method) {
272          stat = 0;
273          goto bail_out;
274       }
275       bstrncpy(jcr->event, event, sizeof(jcr->event));
276       result = PyObject_CallFunction(JobEnd_method, "O", jcr->Python_job);
277       jcr->event[0] = 0;             /* no event in progress */
278       if (result == NULL) {
279          JobEnd_method = NULL;
280          if (PyErr_Occurred()) {
281             PyErr_Print();
282             Dmsg1(000, "Python JobEnd error. JobId=%d\n", jcr->JobId);
283          }
284          Jmsg(jcr, M_ERROR, 0, "Python function \"%s\" not found.\n", event);
285          goto bail_out;
286       }
287       stat = 1;                    /* OK */
288    } else if (strcmp(event, "Exit") == 0) {
289       if (!Exit_method) {
290          stat = 0;
291          goto bail_out;
292       }
293       result = PyObject_CallFunction(JobEnd_method, NULL);
294       if (result == NULL) {
295          goto bail_out;
296       }
297       stat = 1;                    /* OK */
298    } else {
299       Emsg1(M_ABORT, 0, "Unknown Python daemon event %s\n", event);
300    }
301
302 bail_out:
303    Py_XDECREF((PyObject *)jcr->Python_job);
304    jcr->Python_job = NULL;
305    Py_XDECREF((PyObject *)jcr->Python_events);
306    jcr->Python_events = NULL;
307    /* Fall through */
308 jobstart_ok:
309    Py_XDECREF(result);
310    PyEval_ReleaseLock();
311    return stat; 
312 }
313
314 #ifdef xxx
315    PyObject *pName, *pModule, *pDict, *pFunc;
316    PyObject *pArgs, *pJCR, *pCall;
317    
318    Dmsg1(100, "Generate event %s\n", event);
319    pName = PyString_FromString(event);
320    if (!pName) {
321       Jmsg(jcr, M_ERROR, 0, "Could not convert \"%s\" to Python string.\n", event);
322       return -1;                      /* Could not convert string */
323    }
324
325    pModule = PyImport_Import(pName);
326    Py_DECREF(pName);                  /* release pName */
327
328    if (pModule != NULL) {
329       pDict = PyModule_GetDict(pModule);
330       /* pDict is a borrowed reference */
331
332       pFunc = PyDict_GetItemString(pDict, (char *)event);
333       /* pFun: Borrowed reference */
334
335       if (pFunc && PyCallable_Check(pFunc)) {
336           /* Create JCR argument to send to function */
337           pArgs = PyTuple_New(1);
338           pJCR = (PyObject *)PyObject_New(JCRObject, &JCRType);
339           ((JCRObject *)pJCR)->jcr = jcr;
340           if (!pJCR) {
341              Py_DECREF(pArgs);
342              Py_DECREF(pModule);
343              Jmsg0(jcr, M_ERROR, 0, "Could not create JCR Python Object.\n");
344              return -1;
345           }
346           Py_INCREF(pJCR);
347           /* pJCR reference stolen here: */
348           PyTuple_SetItem(pArgs, 0, pJCR);
349
350           /* Finally, we call the module here */
351           bstrncpy(jcr->event, event, sizeof(jcr->event));
352           pCall = PyObject_CallObject(pFunc, pArgs);
353           jcr->event[0] = 0;             /* no event in progress */
354           Py_DECREF(pArgs);
355           Py_DECREF(pJCR);
356           if (pCall != NULL) {
357              Py_DECREF(pCall);
358           } else {
359              Py_DECREF(pModule);
360              PyErr_Print();
361              Jmsg1(jcr, M_ERROR, 0, "Error running Python module: %s\n", event);
362              return 0;                /* error running function */
363           }
364           /* pDict and pFunc are borrowed and must not be Py_DECREF-ed */
365       } else {
366          if (PyErr_Occurred()) {
367             PyErr_Print();
368             Dmsg1(000, "Python event %s function not callable.\n", event);
369          }
370          Jmsg1(jcr, M_ERROR, 0, "Python function \"%s\" not found in module.\n", event);
371          return -1;                   /* function not found */
372       }
373       Py_DECREF(pModule);
374    } else {
375       return 0;                       /* Module not present */
376    }
377    Dmsg0(100, "Generate event OK\n");
378    return 1;
379 }
380 #endif
381
382 #else
383
384 /*
385  *  No Python configured -- create external entry points and
386  *    dummy routines so that library code can call this without
387  *    problems even if it is not configured.
388  */
389 int generate_daemon_event(JCR *jcr, const char *event) { return 0; }
390 void init_python_interpreter(const char *progname, const char *scripts,
391          const char *module) { }
392 void term_python_interpreter() { }
393
394 #endif /* HAVE_PYTHON */