]> git.sur5r.net Git - bacula/docs/blob - docs/manual/python.tex
0f1b14a9aaf1dabe0d9db851d7cad0d13ba540b6
[bacula/docs] / docs / manual / python.tex
1 %%
2 %%
3
4 \section*{Python Scripting}
5 \label{_ChapterStart60}
6 \index[general]{Python Scripting}
7 \index[general]{Scripting!Python}
8 \addcontentsline{toc}{section}{Python Scripting}
9
10 You may be asking what Python is and why a scripting language is
11 needed in Bacula. The answer to the first question is that Python
12 is an Object Oriented scripting language with features similar
13 to those found in Perl, but the syntax of the language is much
14 cleaner and simpler.  The answer to why have scripting in Bacula is to
15 give the user more control over the whole backup process. Probably 
16 the simplest example is when Bacula needs a new Volume name, with
17 a scripting language such as Python, you can generate any name 
18 you want, based on the current state of Bacula.
19
20 \subsection*{Python Configuration}
21 \index[general]{Python Configuration}
22 \index[general]{Configuration!Python}
23 \addcontentsline{toc}{subsection}{Python Configuration}
24
25 Python must be enabled during the configuration process by adding
26 a \verb:--:with-python, and possibly specifying an alternate
27 directory if your Python is not installed in a standard system
28 location. If you are using RPMs you will need the python-devel package
29 installed.
30
31 When Python is configured, it becomes an integral part of Bacula and
32 runs in Bacula's address space, so even though it is an interpreted 
33 language, it is very efficient.
34
35 When the Director starts, it looks to see if you have a {\bf
36 Scripts Directory} Directive defined, if so, it looks in that directory for
37 a file named {\bf DirStartUp.py}. If it is found, Bacula will pass this
38 file to Python for execution. The {\bf Scripts Directory} is a new
39 directive that you add to the Director resource of your bacula-dir.conf
40 file.
41
42 \subsection*{Bacula Events}
43 \index[general]{Bacula Events}
44 \index[general]{Events}
45 \addcontentsline{toc}{subsection}{Bacula Events}
46 A Bacula event is a point in the Bacula code where Bacula
47 will call a subroutine (actually a method) that you have 
48 defined in the Python StartUp script. Events correspond 
49 to some significant event such as a Job Start, a Job End,
50 Bacula needs a new Volume Name, ... When your script is
51 called, it will have access to all the Bacula variables
52 specific to the Job (attributes of the Job Object), and
53 it can even call some of the Job methods (subroutines)
54 or set new values in the Job attributes, such as the 
55 Priority. You will see below how the events are used.
56
57 \subsection*{Python Objects}
58 \index[general]{Python Objects}
59 \index[general]{Objects!Python}
60 \addcontentsline{toc}{subsection}{Python Objects}
61
62 There are four Python objects that you will need to work with:
63 \begin{description}
64 \item [The Bacula Object]
65    The Bacula object is created by the Bacula daemon (the Director
66    in the present case) when the daemon starts. It is available to
67    the Python startup script, {\bf DirStartup.py}, by importing the
68    Bacula definitions with {\bf import bacula}. The methods
69    available with this object are described below. 
70
71 \item [The Bacula Events Class]
72    You create this class in the startup script, and you pass
73    it to the Bacula Object's {\bf set\_events} method. The 
74    purpose of the Bacula Events Class is to define what global
75    or daemon events you want to monitor. When one of those events
76    occurs, your Bacula Events Class will be called at the method
77    corresponding to the event. There are currently three events,
78    JobStart, JobEnd, and Exit, which are described in detail below.
79    
80 \item [The Job Object]
81    When a Job starts, and assuming you have defined a JobStart method
82    in your Bacula Events Class, Bacula will create a Job Object. This
83    object will be passed to the JobStart event. The Job Object has a
84    has good number of read-only members or attributes providing many
85    details of the Job, and it also has a number of writable attributes
86    that allow you to pass information into the Job.  These attributes
87    are described below.
88    
89 \item [The Job Events Class]
90    You create this class in the JobStart method of your Bacula Events
91    class, and it allows you to define which of the possible Job Object
92    events you want to see. You must pass an instance of your Job Events
93    class to the Job Object set\_events() method.
94    Normally, you will probably only have one
95    Job Events Class, which will be instantiated for each Job. However,
96    if you wish to see different events in different Jobs, you may have
97    as many Job Events classes as you wish.
98 \end{description}
99
100
101 The first thing the startup script must do is to define what global Bacula
102 events (daemon events), it wants to see. This is done by creating a 
103 Bacula Events class, instantiating it, then passing it to the 
104 {\bf set\_events} method. There are three possible
105 events.
106
107 \begin{description}
108 \item [JobStart]
109    \index[dir]{JobStart}
110    This Python method, if defined, will be called each time a Job is started.
111    The method is passed the class instantiation object as the first argument,
112    and the Bacula Job object as the second argument.  The Bacula Job object
113    has several built-in methods, and you can define which ones you
114    want called. If you do not define this method, you will not be able
115    to interact with Bacula jobs.
116
117 \item [JobEnd]
118    This Python method, if defined, will be called each time a Job terminates.
119    The method is passed the class instantiation object as the first argument,
120    and the Bacula Job object as the second argument.  
121
122 \item [Exit]
123    This Python method, if defined, will be called when the Director terminates.
124    The method is passed the class instantiation object as the first argument.
125 \end{description}
126
127 Access to the Bacula variables and methods is done with:
128
129      import bacula
130
131 The following are the read-only attributes provided by the bacula object.
132 \begin{description}
133 \item [Name]
134 \item [ConfigFile]
135 \item [WorkingDir]
136 \item [Version] string consisting of "Version  Build-date"
137 \end{description}
138
139
140 A simple definition of the Bacula Events Class might be the following:
141
142 \footnotesize
143 \begin{verbatim}
144 import sys, bacula
145 class BaculaEvents:
146   def JobStart(self, job):
147      ...
148 \end{verbatim}
149 \normalsize
150
151 Then to instantiate the class and pass it to Bacula, you
152 would do:
153
154 \footnotesize
155 \begin{verbatim}
156 bacula.set_events(BaculaEvents()) # register Bacula Events wanted
157 \end{verbatim}
158 \normalsize
159
160 And at that point, each time a Job is started, your BaculaEvents JobStart
161 method will be called.
162
163 Now to actually do anything with a Job, you must define which Job events
164 you want to see, and this is done by defining a JobEvents class containing
165 the methods you want called.  Each method name corresponds to one of the
166 Job Events that Bacula will generate.
167
168 A simple Job Events class might look like the following:
169
170 \footnotesize
171 \begin{verbatim}
172 class JobEvents:
173   def NewVolume(self, job):
174      ...
175 \end{verbatim}
176 \normalsize
177
178 Here, your JobEvents class method NewVolume will be called each time
179 the Job needs a new Volume name.  To actually register the events defined
180 in your class with the Job, you must instantiate the JobEvents class and
181 set it in the Job {\bf set\_events} variable. Note, this is a bit different 
182 from how you registered the Bacula events. The registration process must
183 be done in the Bacula JobStart event (your method).  So, you would modify 
184 Bacula Events (not the Job events) as follows:
185
186 \footnotesize
187 \begin{verbatim}
188 import sys, bacula
189 class BaculaEvents:
190   def JobStart(self, job):
191      events = JobEvents()         # create instance of Job class
192      job.set_events(events)       # register Job events desired
193      ...
194 \end{verbatim}
195 \normalsize
196
197 When a job event is triggered, the appropriate event definition is
198 called in the JobEvents class. This is the means by which your Python
199 script or code gets control. Once it has control, it may read job
200 attributes, or set them. See below for a list of read-only attributes,
201 and those that are writable.  
202
203 In addition, the Bacula {\bf job} obbject in the Director has
204 a number of methods (subroutines) that can be called. They
205 are:
206 \begin{description}
207 \item [set\_events] The set\_events takes a single
208    argument, which is the instantation of the Job Events class
209    that contains the methods that you want called. The method
210    names that will be called must correspond to the Bacula
211    defined events. You may define additional methods but Bacula
212    will not use them.
213 \item [run] The run method takes a single string
214    argument, which is the run command (same as in the Console)
215    that you want to submit to start a new Job. The value
216    returned by the run method is the JobId of the job that
217    started, or -1 if there was an error.
218 \item [write] The write method is used to be able to send
219    print output to the Job Report. This will be described later.
220 \item [DoesVolumeExist] The DoesVolumeExist takes a single
221    string argument, which is the Volume name, and returns 
222    1 if the volume exists in the Catalog and 0 if the volume
223    does not exist.
224 \end{description}
225
226 The following attributes are read/write within the Director 
227 for the {\bf job} object.
228
229 \begin{description}
230 \item [Priority] Read or set the Job priority.
231 Note, that setting a Job Priority is effective only before
232 the Job actually starts.  (not functional yet)
233 \end{description}
234
235 The following read-only attributes are available within the Director
236 for the {\bf job} object.
237
238 \begin{description}
239
240 \item [Level] This attribute contains a string representing the Job 
241         level, e.g. Full, Differential, Incremental, ...
242 \item [Type]  This attribute contains a string representing the Job
243         type, e.g. Backup, Restore, Verify, ...
244 \item [JobId] This attribute contains an integer representing the
245         JobId.
246 \item [Client] This attribute contains a string with the name of the
247           Client for this job.
248 \item [NumVols]  This attribute contains an integer with the number of
249           Volumes in the Pool being used by the Job.
250 \item [Pool] This attribute contains a string with the name of the Pool
251           being used by the Job.
252 \item [Storage] This attribute contains a string with the name of the
253           Storage resource being used by the Job.
254 \item [Catalog]  This attribute contains a string with the name of the
255           Catalog resource being used by the Job.
256 \item [MediaType] This attribute contains a string with the name of the
257           Media Type associated with the Storage resource being used by the Job.
258 \item [Job] This attribute contains a string containing the name of the
259            Job resource used by this job (not unique).
260 \item [JobName] This attribute contains a string representing the full
261             unique Job name.
262 \item [JobStatus] This attribute contains a single character string
263             representing the current Job status. The status may change
264             during execution of the job.
265 \item [Priority]  This attribute contains an integer with the priority
266           assigned to the job.
267 \item [CatalogRes] tuple consisting of (DBName, Address, User,
268   Password, Socket, Port, Database Vendor) taken from the Catalog resource 
269    for the Job with the exception of Database Vendor, which is
270    one of the following: MySQL, PostgreSQL, SQLite, Internal,
271    depending on what database you configured.
272 \item [VolumeName]
273    After a Volume has been purged, this attribute will contain the
274    name of that Volume. At other times, this value may have no meaning.
275 \end{description}
276
277 The following write-only attributes are available within the
278 Director:
279
280 \begin{description}
281 \item [JobReport] Send line to the Job Report.
282 \item [VolumeName] Set a new Volume name. Valid only during the
283    NewVolume event.
284 \end{description}
285
286 \subsection*{Python Console Command}
287 \index[general]{Python Console Command}
288 \index[general]{Console Command!Python}
289 \addcontentsline{toc}{subsection}{Python Console Command}
290
291 There is a new Console command named {\bf python}. It takes
292 a single argument {\bf restart}. Example:
293 \begin{verbatim}
294   python restart
295 \end{verbatim}
296
297 This command restarts the Python interpreter in the Director.
298 This can be useful when you are modifying the DirStartUp script,
299 because normally Python will cache it, and thus the
300 script will be read one time.
301
302
303 \subsection*{Python Example}
304 \index[general]{Python Example}
305 \index[general]{Example!Python}
306 \addcontentsline{toc}{subsection}{Python Example}
307
308 An example script for the Director startup file is provided in
309 {\bf examples/python/DirStartup.py} as follows:
310
311 \footnotesize
312 \begin{verbatim}
313 #
314 # Bacula Python interface script for the Director
315 #
316
317 # You must import both sys and bacula
318 import sys, bacula
319
320 # This is the list of Bacula daemon events that you
321 #  can receive.
322 class BaculaEvents:
323   def __init__(self):
324      # Called here when a new Bacula Events class is
325      #  is created. Normally not used 
326      noop = 1
327
328   def JobStart(self, job):
329      """
330        Called here when a new job is started. If you want
331        to do anything with the Job, you must register
332        events you want to receive.
333      """
334      events = JobEvents()         # create instance of Job class
335      events.job = job             # save Bacula's job pointer
336      job.set_events(events)       # register events desired
337      sys.stderr = events          # send error output to Bacula
338      sys.stdout = events          # send stdout to Bacula
339      jobid = job.JobId; client = job.Client
340      numvols = job.NumVols 
341      job.JobReport="Python Dir JobStart: JobId=%d Client=%s NumVols=%d\n" % (jobid,client,numvols) 
342
343   # Bacula Job is going to terminate
344   def JobEnd(self, job):    
345      jobid = job.JobId
346      client = job.Client 
347      job.JobReport="Python Dir JobEnd output: JobId=%d Client=%s.\n" % (jobid, client) 
348
349   # Called here when the Bacula daemon is going to exit
350   def Exit(self, job):
351       print "Daemon exiting."
352      
353 bacula.set_events(BaculaEvents()) # register daemon events desired
354
355 """
356   These are the Job events that you can receive.
357 """
358 class JobEvents:
359   def __init__(self):
360      # Called here when you instantiate the Job. Not
361      # normally used
362      noop = 1
363      
364   def JobInit:
365      # Called when the job is first scheduled
366      noop = 1
367      
368   def JobRun:
369      # Called just before running the job after initializing
370      #  This is the point to change most Job parameters.
371      #  It is equivalent to the JobRunBefore point.
372      noop = 1
373
374   def NewVolume(self, job):
375      # Called when Bacula wants a new Volume name. The Volume
376      #  name returned, if any, must be stored in job.VolumeName
377      jobid = job.JobId
378      client = job.Client 
379      numvol = job.NumVols
380      volname = "TestA-001"
381      job.JobReport = "JobId=%d Client=%s NumVols=%d VolumeName=%s" % (jobid, client, numvol,volname)
382      job.JobReport="Python before New Volume set for Job.\n"
383      job.VolumeName=volname
384
385   def VolumePurged(self, job):
386      # Called when a Volume is purged. The Volume name can be referenced
387      #  with job.VolumeName
388      noop = 1
389
390
391
392 \end{verbatim}
393 \normalsize