]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/pythonlib.c
Get FD Python running -- design Python backup interface.
[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       Dmsg1(100, "No script dir. prog=%s\n", module);
130       return;
131    }
132    Dmsg2(100, "Script dir=%s prog=%s\n", scripts, module);
133
134    Py_SetProgramName((char *)progname);
135    Py_Initialize();
136    PyEval_InitThreads();
137    bacula_module = Py_InitModule("bacula", BaculaMethods);
138    if (!bacula_module) {
139       Jmsg0(NULL, M_ERROR_TERM, 0, "Could not initialize Python\n");
140    }
141    bsnprintf(buf, sizeof(buf), "import sys\n"
142             "sys.path.append('%s')\n", scripts);
143    if (PyRun_SimpleString(buf) != 0) {
144       Jmsg1(NULL, M_ERROR_TERM, 0, "Could not Run Python string %s\n", buf);
145    }   
146    JobType.tp_methods = JobMethods;
147    if (PyType_Ready(&JobType) != 0) {
148       Jmsg0(NULL, M_ERROR_TERM, 0, "Could not initialize Python Job type.\n");
149       PyErr_Print();
150    }   
151    StartUp_module = PyImport_ImportModule((char *)module);
152    if (!StartUp_module) {
153       Emsg2(M_ERROR, 0, "Could not import Python script %s/%s. Python disabled.\n",
154            scripts, module);
155       if (PyErr_Occurred()) {
156          PyErr_Print();
157          Dmsg0(000, "Python Import error.\n");
158       }
159    }
160    PyEval_ReleaseLock();
161 }
162
163
164 void term_python_interpreter()
165 {
166    if (StartUp_module) {
167       Py_XDECREF(StartUp_module);
168       Py_Finalize();
169    }
170 }
171
172 static PyObject *set_bacula_events(PyObject *self, PyObject *args)
173 {
174    PyObject *eObject;
175
176    Dmsg0(100, "In set_bacula_events.\n");
177    if (!PyArg_ParseTuple(args, "O:set_bacula_events", &eObject)) {
178       return NULL;
179    }
180    JobStart_method = find_method(eObject, JobStart_method, "JobStart");
181    JobEnd_method = find_method(eObject, JobEnd_method, "JobEnd");
182    Exit_method = find_method(eObject, Exit_method, "Exit");
183
184    Py_XINCREF(eObject);
185    Py_INCREF(Py_None);
186    return Py_None;
187 }
188
189 /* Write text to daemon output */
190 static PyObject *bacula_write(PyObject *self, PyObject *args)
191 {
192    char *text;
193    if (!PyArg_ParseTuple(args, "s:write", &text)) {
194       return NULL;
195    }
196    if (text) {
197       Jmsg(NULL, M_INFO, 0, "%s", text);
198    }
199    Py_INCREF(Py_None);
200    return Py_None;
201 }
202
203
204 /*
205  * Check that a method exists and is callable.
206  */
207 PyObject *find_method(PyObject *eventsObject, PyObject *method, const char *name)
208 {
209    Py_XDECREF(method);             /* release old method if any */
210    method = PyObject_GetAttrString(eventsObject, (char *)name);
211    if (method == NULL) {
212        Dmsg1(000, "Python method %s not found\n", name);
213    } else if (PyCallable_Check(method) == 0) {
214        Dmsg1(000, "Python object %s found but not a method.\n", name);
215        Py_XDECREF(method);
216        method = NULL;
217    } else {
218        Dmsg1(100, "Got method %s\n", name);
219    }
220    return method; 
221 }
222
223
224 /*
225  * Generate and process a Bacula event by importing a Python
226  *  module and running it.
227  *
228  *  Returns: 0 if Python not configured or module not found
229  *          -1 on Python error
230  *           1 OK
231  */
232 int generate_daemon_event(JCR *jcr, const char *event)
233 {
234    PyObject *pJob;
235    int stat = -1;
236    PyObject *result = NULL;
237
238    if (!StartUp_module) {
239       Dmsg0(100, "No startup module.\n");
240       return 0;
241    }
242
243    Dmsg1(100, "event=%s\n", event);
244    PyEval_AcquireLock();
245    if (strcmp(event, "JobStart") == 0) {
246       if (!JobStart_method) {
247          stat = 0;
248          goto bail_out;
249       }
250       /* Create JCR argument to send to function */
251       pJob = (PyObject *)PyObject_New(JobObject, &JobType);
252       if (!pJob) {
253          Jmsg(jcr, M_ERROR, 0, "Could not create Python Job Object.\n");
254          goto bail_out;
255       }
256       ((JobObject *)pJob)->jcr = jcr;
257       bstrncpy(jcr->event, event, sizeof(jcr->event));
258       result = PyObject_CallFunction(JobStart_method, "O", pJob);
259       jcr->event[0] = 0;             /* no event in progress */
260       if (result == NULL) {
261          JobStart_method = NULL;
262          if (PyErr_Occurred()) {
263             PyErr_Print();
264             Dmsg0(000, "Python JobStart error.\n");
265          }
266          Jmsg(jcr, M_ERROR, 0, "Python function \"%s\" not found.\n", event);
267          Py_XDECREF(pJob);
268          goto bail_out;
269       }
270       jcr->Python_job = (void *)pJob;
271       stat = 1;                       /* OK */
272       goto jobstart_ok;
273
274    } else if (strcmp(event, "JobEnd") == 0) {
275       if (!JobEnd_method || !jcr->Python_job) {
276          Dmsg0(100, "No JobEnd method\n");
277          stat = 0;
278          goto bail_out;
279       }
280       bstrncpy(jcr->event, event, sizeof(jcr->event));
281       Dmsg1(100, "Call event=%s\n", event);
282       result = PyObject_CallFunction(JobEnd_method, "O", jcr->Python_job);
283       jcr->event[0] = 0;             /* no event in progress */
284       if (result == NULL) {
285          JobEnd_method = NULL;
286          if (PyErr_Occurred()) {
287             PyErr_Print();
288             Dmsg1(000, "Python JobEnd error. JobId=%d\n", jcr->JobId);
289          }
290          Jmsg(jcr, M_ERROR, 0, "Python function \"%s\" not found.\n", event);
291          goto bail_out;
292       }
293       stat = 1;                    /* OK */
294    } else if (strcmp(event, "Exit") == 0) {
295       if (!Exit_method) {
296          stat = 0;
297          goto bail_out;
298       }
299       result = PyObject_CallFunction(JobEnd_method, NULL);
300       if (result == NULL) {
301          goto bail_out;
302       }
303       stat = 1;                    /* OK */
304    } else {
305       Emsg1(M_ABORT, 0, "Unknown Python daemon event %s\n", event);
306    }
307
308 bail_out:
309    Py_XDECREF((PyObject *)jcr->Python_job);
310    jcr->Python_job = NULL;
311    Py_XDECREF((PyObject *)jcr->Python_events);
312    jcr->Python_events = NULL;
313    /* Fall through */
314 jobstart_ok:
315    Py_XDECREF(result);
316    PyEval_ReleaseLock();
317    return stat; 
318 }
319
320 #ifdef xxx
321    PyObject *pName, *pModule, *pDict, *pFunc;
322    PyObject *pArgs, *pJCR, *pCall;
323    
324    Dmsg1(100, "Generate event %s\n", event);
325    pName = PyString_FromString(event);
326    if (!pName) {
327       Jmsg(jcr, M_ERROR, 0, "Could not convert \"%s\" to Python string.\n", event);
328       return -1;                      /* Could not convert string */
329    }
330
331    pModule = PyImport_Import(pName);
332    Py_DECREF(pName);                  /* release pName */
333
334    if (pModule != NULL) {
335       pDict = PyModule_GetDict(pModule);
336       /* pDict is a borrowed reference */
337
338       pFunc = PyDict_GetItemString(pDict, (char *)event);
339       /* pFun: Borrowed reference */
340
341       if (pFunc && PyCallable_Check(pFunc)) {
342           /* Create JCR argument to send to function */
343           pArgs = PyTuple_New(1);
344           pJCR = (PyObject *)PyObject_New(JCRObject, &JCRType);
345           ((JCRObject *)pJCR)->jcr = jcr;
346           if (!pJCR) {
347              Py_DECREF(pArgs);
348              Py_DECREF(pModule);
349              Jmsg0(jcr, M_ERROR, 0, "Could not create JCR Python Object.\n");
350              return -1;
351           }
352           Py_INCREF(pJCR);
353           /* pJCR reference stolen here: */
354           PyTuple_SetItem(pArgs, 0, pJCR);
355
356           /* Finally, we call the module here */
357           bstrncpy(jcr->event, event, sizeof(jcr->event));
358           pCall = PyObject_CallObject(pFunc, pArgs);
359           jcr->event[0] = 0;             /* no event in progress */
360           Py_DECREF(pArgs);
361           Py_DECREF(pJCR);
362           if (pCall != NULL) {
363              Py_DECREF(pCall);
364           } else {
365              Py_DECREF(pModule);
366              PyErr_Print();
367              Jmsg1(jcr, M_ERROR, 0, "Error running Python module: %s\n", event);
368              return 0;                /* error running function */
369           }
370           /* pDict and pFunc are borrowed and must not be Py_DECREF-ed */
371       } else {
372          if (PyErr_Occurred()) {
373             PyErr_Print();
374             Dmsg1(000, "Python event %s function not callable.\n", event);
375          }
376          Jmsg1(jcr, M_ERROR, 0, "Python function \"%s\" not found in module.\n", event);
377          return -1;                   /* function not found */
378       }
379       Py_DECREF(pModule);
380    } else {
381       return 0;                       /* Module not present */
382    }
383    Dmsg0(100, "Generate event OK\n");
384    return 1;
385 }
386 #endif
387
388 #else
389
390 /*
391  *  No Python configured -- create external entry points and
392  *    dummy routines so that library code can call this without
393  *    problems even if it is not configured.
394  */
395 int generate_daemon_event(JCR *jcr, const char *event) { return 0; }
396 void init_python_interpreter(const char *progname, const char *scripts,
397          const char *module) { }
398 void term_python_interpreter() { }
399
400 #endif /* HAVE_PYTHON */