]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/pythonlib.c
- Remove a few HAVE_TLS #ifdefs
[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 extern PyObject *job_getattr(PyObject *self, char *attrname);
42 extern int job_setattr(PyObject *self, char *attrname, PyObject *value);
43
44 static PyObject *bacula_module = NULL;    /* We create this */
45 static PyObject *StartUp_module = NULL;   /* We import this */
46
47 /* These are the daemon events or methods that are defined */
48 static PyObject *JobStart_method = NULL;
49 static PyObject *JobEnd_method = NULL;
50 static PyObject *Exit_method = NULL;
51
52 static PyObject *set_bacula_events(PyObject *self, PyObject *args);
53 static PyObject *bacula_write(PyObject *self, PyObject *args);
54
55 PyObject *find_method(PyObject *eventsObject, PyObject *method, const char *name);
56
57 /* Define Bacula daemon method entry points */
58 static PyMethodDef BaculaMethods[] = {
59     {"set_events", set_bacula_events, METH_VARARGS, "Define Bacula events."},
60     {"write", bacula_write, METH_VARARGS, "Write output."},
61     {NULL, NULL, 0, NULL}             /* last item */
62 };
63
64
65 /*
66  * This is a Bacula Job type as defined in Python. We store a pointer
67  *   to the jcr. That is all we need, but the user's script may keep
68  *   local data attached to this. 
69  */
70 typedef struct s_JobObject {
71     PyObject_HEAD
72     JCR *jcr;
73 } JobObject;
74
75 static PyTypeObject JobType = {
76     PyObject_HEAD_INIT(NULL)
77     /* Other items filled in in code below */
78 };
79
80 /* Return the JCR pointer from the JobObject */
81 JCR *get_jcr_from_PyObject(PyObject *self)
82 {
83    if (!self) {
84       return NULL;
85    }
86    return ((JobObject *)self)->jcr;
87 }
88
89
90 /* Start the interpreter */
91 void init_python_interpreter(const char *progname, const char *scripts,
92     const char *module)
93 {
94    char buf[MAXSTRING];
95
96    if (!scripts || scripts[0] == 0) {
97       Dmsg1(100, "No script dir. prog=%s\n", module);
98       return;
99    }
100    Dmsg2(100, "Script dir=%s prog=%s\n", scripts, module);
101
102    Py_SetProgramName((char *)progname);
103    Py_Initialize();
104    PyEval_InitThreads();
105    bacula_module = Py_InitModule("bacula", BaculaMethods);
106    PyModule_AddStringConstant(bacula_module, "name", my_name);
107    if (!bacula_module) {
108       Jmsg0(NULL, M_ERROR_TERM, 0, "Could not initialize Python\n");
109    }
110    bsnprintf(buf, sizeof(buf), "import sys\n"
111             "sys.path.append('%s')\n", scripts);
112    if (PyRun_SimpleString(buf) != 0) {
113       Jmsg1(NULL, M_ERROR_TERM, 0, "Could not Run Python string %s\n", buf);
114    }   
115
116    /* Explicitly set values we want */
117    JobType.tp_name = "Bacula.Job";
118    JobType.tp_basicsize = sizeof(JobObject);
119    JobType.tp_flags = Py_TPFLAGS_DEFAULT;
120    JobType.tp_doc = "Bacula Job object";
121    JobType.tp_getattr = job_getattr;
122    JobType.tp_setattr = job_setattr;
123    
124    if (PyType_Ready(&JobType) != 0) {
125       Jmsg0(NULL, M_ERROR_TERM, 0, "Could not initialize Python Job type.\n");
126       PyErr_Print();
127    }   
128    StartUp_module = PyImport_ImportModule((char *)module);
129    if (!StartUp_module) {
130       Emsg2(M_ERROR, 0, "Could not import Python script %s/%s. Python disabled.\n",
131            scripts, module);
132       if (PyErr_Occurred()) {
133          PyErr_Print();
134          Dmsg0(000, "Python Import error.\n");
135       }
136    }
137    PyEval_ReleaseLock();
138 }
139
140
141 void term_python_interpreter()
142 {
143    if (StartUp_module) {
144       Py_XDECREF(StartUp_module);
145       Py_Finalize();
146    }
147 }
148
149 static PyObject *set_bacula_events(PyObject *self, PyObject *args)
150 {
151    PyObject *eObject;
152
153    Dmsg0(100, "In set_bacula_events.\n");
154    if (!PyArg_ParseTuple(args, "O:set_bacula_events", &eObject)) {
155       return NULL;
156    }
157    JobStart_method = find_method(eObject, JobStart_method, "JobStart");
158    JobEnd_method = find_method(eObject, JobEnd_method, "JobEnd");
159    Exit_method = find_method(eObject, Exit_method, "Exit");
160
161    Py_XINCREF(eObject);
162    Py_INCREF(Py_None);
163    return Py_None;
164 }
165
166 /* Write text to daemon output */
167 static PyObject *bacula_write(PyObject *self, PyObject *args)
168 {
169    char *text;
170    if (!PyArg_ParseTuple(args, "s:write", &text)) {
171       return NULL;
172    }
173    if (text) {
174       Jmsg(NULL, M_INFO, 0, "%s", text);
175    }
176    Py_INCREF(Py_None);
177    return Py_None;
178 }
179
180
181 /*
182  * Check that a method exists and is callable.
183  */
184 PyObject *find_method(PyObject *eventsObject, PyObject *method, const char *name)
185 {
186    Py_XDECREF(method);             /* release old method if any */
187    method = PyObject_GetAttrString(eventsObject, (char *)name);
188    if (method == NULL) {
189        Dmsg1(000, "Python method %s not found\n", name);
190    } else if (PyCallable_Check(method) == 0) {
191        Dmsg1(000, "Python object %s found but not a method.\n", name);
192        Py_XDECREF(method);
193        method = NULL;
194    } else {
195        Dmsg1(100, "Got method %s\n", name);
196    }
197    return method; 
198 }
199
200
201 /*
202  * Generate and process a Bacula event by importing a Python
203  *  module and running it.
204  *
205  *  Returns: 0 if Python not configured or module not found
206  *          -1 on Python error
207  *           1 OK
208  */
209 int generate_daemon_event(JCR *jcr, const char *event)
210 {
211    PyObject *pJob;
212    int stat = -1;
213    PyObject *result = NULL;
214
215    if (!StartUp_module) {
216       Dmsg0(100, "No startup module.\n");
217       return 0;
218    }
219
220    Dmsg1(100, "event=%s\n", event);
221    PyEval_AcquireLock();
222    if (strcmp(event, "JobStart") == 0) {
223       if (!JobStart_method) {
224          stat = 0;
225          goto bail_out;
226       }
227       /* Create JCR argument to send to function */
228       pJob = (PyObject *)PyObject_New(JobObject, &JobType);
229       if (!pJob) {
230          Jmsg(jcr, M_ERROR, 0, "Could not create Python Job Object.\n");
231          goto bail_out;
232       }
233       ((JobObject *)pJob)->jcr = jcr;
234       bstrncpy(jcr->event, event, sizeof(jcr->event));
235       result = PyObject_CallFunction(JobStart_method, "O", pJob);
236       jcr->event[0] = 0;             /* no event in progress */
237       if (result == NULL) {
238          JobStart_method = NULL;
239          if (PyErr_Occurred()) {
240             PyErr_Print();
241             Dmsg0(000, "Python JobStart error.\n");
242          }
243          Jmsg(jcr, M_ERROR, 0, "Python function \"%s\" not found.\n", event);
244          Py_XDECREF(pJob);
245          goto bail_out;
246       }
247       jcr->Python_job = (void *)pJob;
248       stat = 1;                       /* OK */
249       goto jobstart_ok;
250
251    } else if (strcmp(event, "JobEnd") == 0) {
252       if (!JobEnd_method || !jcr->Python_job) {
253          Dmsg2(000, "No JobEnd method=%p Job=%p\n", JobEnd_method, jcr->Python_job);
254          stat = 0;
255          goto bail_out;
256       }
257       bstrncpy(jcr->event, event, sizeof(jcr->event));
258       Dmsg1(100, "Call daemon event=%s\n", event);
259       result = PyObject_CallFunction(JobEnd_method, "O", jcr->Python_job);
260       jcr->event[0] = 0;             /* no event in progress */
261       if (result == NULL) {
262          if (PyErr_Occurred()) {
263             PyErr_Print();
264             Dmsg2(000, "Python JobEnd error. job=%p JobId=%d\n", jcr->Python_job,
265                jcr->JobId);
266             JobEnd_method = NULL;
267          }
268          Jmsg(jcr, M_ERROR, 0, "Python function \"%s\" not found.\n", event);
269          goto bail_out;
270       }
271       stat = 1;                    /* OK */
272    } else if (strcmp(event, "Exit") == 0) {
273       if (!Exit_method) {
274          stat = 0;
275          goto bail_out;
276       }
277       result = PyObject_CallFunction(Exit_method, NULL);
278       if (result == NULL) {
279          goto bail_out;
280       }
281       stat = 1;                    /* OK */
282    } else {
283       Jmsg1(jcr, M_ABORT, 0, "Unknown Python daemon event %s\n", event);
284    }
285
286 bail_out:
287    Py_XDECREF((PyObject *)jcr->Python_job);
288    jcr->Python_job = NULL;
289    Py_XDECREF((PyObject *)jcr->Python_events);
290    jcr->Python_events = NULL;
291    /* Fall through */
292 jobstart_ok:
293    Py_XDECREF(result);
294    PyEval_ReleaseLock();
295    return stat; 
296 }
297
298 #else
299
300 /*
301  *  No Python configured -- create external entry points and
302  *    dummy routines so that library code can call this without
303  *    problems even if it is not configured.
304  */
305 int generate_daemon_event(JCR *jcr, const char *event) { return 0; }
306 void init_python_interpreter(const char *progname, const char *scripts,
307          const char *module) { }
308 void term_python_interpreter() { }
309
310 #endif /* HAVE_PYTHON */