]> git.sur5r.net Git - bacula/docs/blob - docs/manuals/en/developers/pluginAPI.tex
386aad18e933ba6083c365c2b0216482cfbb9676
[bacula/docs] / docs / manuals / en / developers / pluginAPI.tex
1 %%
2 %%
3
4 \chapter{Bacula FD Plugin API}
5 To write a Bacula plugin, you create a dynamic shared object program (or dll on
6 Win32) with a particular name and two exported entry points, place it in the
7 {\bf Plugins Directory}, which is defined in the {\bf bacula-fd.conf} file in
8 the {\bf Client} resource, and when the FD starts, it will load all the plugins
9 that end with {\bf -fd.so} (or {\bf -fd.dll} on Win32) found in that directory.
10
11 \section{Normal vs Command Plugins}
12 In general, there are two ways that plugins are called. The first way, is when
13 a particular event is detected in Bacula, it will transfer control to each
14 plugin that is loaded in turn informing the plugin of the event.  This is very
15 similar to how a {\bf RunScript} works, and the events are very similar.  Once
16 the plugin gets control, it can interact with Bacula by getting and setting
17 Bacula variables.  In this way, it behaves much like a RunScript.  Currently
18 very few Bacula variables are defined, but they will be implemented as the need
19 arises, and it is very extensible.
20
21 We plan to have plugins register to receive events that they normally would
22 not receive, such as an event for each file examined for backup or restore.
23 This feature is not yet implemented.
24
25 The second type of plugin, which is more useful and fully implemented in the
26 current version is what we call a command plugin.  As with all plugins, it gets
27 notified of important events as noted above (details described below), but in
28 addition, this kind of plugin can accept a command line, which is a:
29
30 \begin{verbatim}
31    Plugin = <command-string>
32 \end{verbatim}
33
34 directive that is placed in the Include section of a FileSet and is very
35 similar to the "File = " directive.  When this Plugin directive is encountered
36 by Bacula during backup, it passes the "command" part of the Plugin directive
37 only to the plugin that is explicitly named in the first field of that command
38 string.  This allows that plugin to backup any file or files on the system that
39 it wants. It can even create "virtual files" in the catalog that contain data
40 to be restored but do not necessarily correspond to actual files on the
41 filesystem.
42
43 The important features of the command plugin entry points are:
44 \begin{itemize}
45  \item It is triggered by a "Plugin =" directive in the FileSet
46  \item Only a single plugin is called that is named on the "Plugin =" directive.
47  \item The full command string after the "Plugin =" is passed to the plugin
48     so that it can be told what to backup/restore.
49 \end{itemize}
50
51
52 \section{Loading Plugins}
53 Once the File daemon loads the plugins, it asks the OS for the
54 two entry points (loadPlugin and unloadPlugin) then calls the
55 {\bf loadPlugin} entry point (see below).
56
57 Bacula passes information to the plugin through this call and it gets
58 back information that it needs to use the plugin.  Later, Bacula
59  will call particular functions that are defined by the
60 {\bf loadPlugin} interface.  
61
62 When Bacula is finished with the plugin 
63 (when Bacula is going to exit), it will call the {\bf unloadPlugin}
64 entry point.
65
66 The two entry points are:
67
68 \begin{verbatim}
69 bRC loadPlugin(bInfo *lbinfo, bFuncs *lbfuncs, pInfo **pinfo, pFuncs **pfuncs)
70
71 and
72
73 bRC unloadPlugin()
74 \end{verbatim}
75
76 both these external entry points to the shared object are defined as C entry
77 points to avoid name mangling complications with C++.  However, the shared
78 object can actually be written in any language (preferably C or C++) providing
79 that it follows C language calling conventions.
80
81 The definitions for {\bf bRC} and the arguments are {\bf
82 src/filed/fd-plugins.h} and so this header file needs to be included in
83 your plugin.  It along with {\bf src/lib/plugins.h} define basically the whole
84 plugin interface.  Within this header file, it includes the following
85 files:
86
87 \begin{verbatim}
88 #include <sys/types.h>
89 #include "config.h"
90 #include "bc_types.h"
91 #include "lib/plugins.h"
92 #include <sys/stat.h>
93 \end{verbatim}
94
95 Aside from the {\bf bc\_types.h} and {\bf confit.h} headers, the plugin
96 definition uses the minimum code from Bacula.  The bc\_types.h file is required
97 to ensure that the data type definitions in arguments correspond to the Bacula
98 core code.
99
100 The return codes are defined as:
101 \begin{verbatim}
102 typedef enum {
103   bRC_OK    = 0,                         /* OK */
104   bRC_Stop  = 1,                         /* Stop calling other plugins */
105   bRC_Error = 2,                         /* Some kind of error */
106   bRC_More  = 3,                         /* More files to backup */
107 } bRC;
108 \end{verbatim}
109
110
111 At a future point in time, we hope to make the Bacula libbac.a into a
112 shared object so that the plugin can use much more of Bacula's
113 infrastructure, but for this first cut, we have tried to minimize the
114 dependence on Bacula.
115
116 \section{loadPlugin}
117 As previously mentioned, the {\bf loadPlugin} entry point in the plugin
118 is called immediately after Bacula loads the plugin when the File daemon
119 itself is first starting.  This entry point is only called once during the
120 execution of the File daemon.  In calling the
121 plugin, the first two arguments are information from Bacula that
122 is passed to the plugin, and the last two arguments are information
123 about the plugin that the plugin must return to Bacula.  The call is:
124
125 \begin{verbatim}
126 bRC loadPlugin(bInfo *lbinfo, bFuncs *lbfuncs, pInfo **pinfo, pFuncs **pfuncs)
127 \end{verbatim}
128
129 and the arguments are:
130
131 \begin{description}
132 \item [lbinfo]
133 This is information about Bacula in general. Currently, the only value
134 defined in the bInfo structure is the version, which is the Bacula plugin 
135 interface version, currently defined as 1.  The {\bf size} is set to the
136 byte size of the structure. The exact definition of the bInfo structure
137 as of this writing is: 
138
139 \begin{verbatim}
140 typedef struct s_baculaInfo {
141    uint32_t size;
142    uint32_t version;
143 } bInfo;
144 \end{verbatim}
145
146 \item [lbfuncs]
147 The bFuncs structure defines the callback entry points within Bacula
148 that the plugin can use register events, get Bacula values, set
149 Bacula values, and send messages to the Job output or debug output.
150
151 The exact definition as of this writing is:
152 \begin{verbatim}
153 typedef struct s_baculaFuncs {
154    uint32_t size;
155    uint32_t version;
156    bRC (*registerBaculaEvents)(bpContext *ctx, ...);
157    bRC (*getBaculaValue)(bpContext *ctx, bVariable var, void *value);
158    bRC (*setBaculaValue)(bpContext *ctx, bVariable var, void *value);
159    bRC (*JobMessage)(bpContext *ctx, const char *file, int line,
160        int type, utime_t mtime, const char *fmt, ...);
161    bRC (*DebugMessage)(bpContext *ctx, const char *file, int line,
162        int level, const char *fmt, ...);
163    void *(*baculaMalloc)(bpContext *ctx, const char *file, int line,
164        size_t size);
165    void (*baculaFree)(bpContext *ctx, const char *file, int line, void *mem);
166 } bFuncs;
167 \end{verbatim}
168
169 We will discuss these entry points and how to use them a bit later when
170 describing the plugin code.
171
172
173 \item [pInfo]
174 When the loadPlugin entry point is called, the plugin must initialize
175 an information structure about the plugin and return a pointer to
176 this structure to Bacula.
177
178 The exact definition as of this writing is:
179
180 \begin{verbatim}
181 typedef struct s_pluginInfo {
182    uint32_t size;
183    uint32_t version;
184    const char *plugin_magic;
185    const char *plugin_license;
186    const char *plugin_author;
187    const char *plugin_date;
188    const char *plugin_version;
189    const char *plugin_description;
190 } pInfo;
191 \end{verbatim}
192
193 Where:
194  \begin{description}
195  \item [version] is the current Bacula defined plugin interface version, currently
196    set to 1. If the interface version differs from the current version of 
197    Bacula, the plugin will not be run (not yet implemented).
198  \item [plugin\_magic] is a pointer to the text string "*FDPluginData*", a
199    sort of sanity check.  If this value is not specified, the plugin
200    will not be run (not yet implemented).
201  \item [plugin\_license] is a pointer to a text string that describes the
202    plugin license. Bacula will only accept compatible licenses (not yet
203    implemented).
204  \item [plugin\_author] is a pointer to the text name of the author of the program.
205    This string can be anything but is generally the author's name.
206  \item [plugin\_date] is the pointer text string containing the date of the plugin.
207    This string can be anything but is generally some human readable form of 
208    the date.
209  \item [plugin\_version] is a pointer to a text string containing the version of
210    the plugin.  The contents are determined by the plugin writer.
211  \item [plugin\_description] is a pointer to a string describing what the
212    plugin does. The contents are determined by the plugin writer.
213  \end{description}
214
215 The pInfo structure must be defined in static memory because Bacula does not
216 copy it and may refer to the values at any time while the plugin is
217 loaded. All values must be supplied or the plugin will not run (not yet
218 implemented).  All text strings must be either ASCII or UTF-8 strings that
219 are terminated with a zero byte.
220
221 \item [pFuncs]
222 When the loadPlugin entry point is called, the plugin must initialize
223 an entry point structure about the plugin and return a pointer to
224 this structure to Bacula. This structure contains pointer to each
225 of the entry points that the plugin must provide for Bacula. When
226 Bacula is actually running the plugin, it will call the defined
227 entry points at particular times.  All entry points must be defined.
228
229 The pFuncs structure must be defined in static memory because Bacula does not
230 copy it and may refer to the values at any time while the plugin is
231 loaded.
232
233 The exact definition as of this writing is:
234
235 \begin{verbatim}
236 typedef struct s_pluginFuncs {
237    uint32_t size;
238    uint32_t version;
239    bRC (*newPlugin)(bpContext *ctx);
240    bRC (*freePlugin)(bpContext *ctx);
241    bRC (*getPluginValue)(bpContext *ctx, pVariable var, void *value);
242    bRC (*setPluginValue)(bpContext *ctx, pVariable var, void *value);
243    bRC (*handlePluginEvent)(bpContext *ctx, bEvent *event, void *value);
244    bRC (*startBackupFile)(bpContext *ctx, struct save_pkt *sp);
245    bRC (*endBackupFile)(bpContext *ctx);
246    bRC (*startRestoreFile)(bpContext *ctx, const char *cmd);
247    bRC (*endRestoreFile)(bpContext *ctx);
248    bRC (*pluginIO)(bpContext *ctx, struct io_pkt *io);
249    bRC (*createFile)(bpContext *ctx, struct restore_pkt *rp);
250    bRC (*setFileAttributes)(bpContext *ctx, struct restore_pkt *rp);
251    bRC (*checkFile)(bpContext *ctx, char *fname);
252 } pFuncs;
253 \end{verbatim}
254
255 The details of the entry points will be presented in
256 separate sections below. 
257
258 Where:
259  \begin{description}
260  \item [size] is the byte size of the structure.
261  \item [version] is the plugin interface version currently set to 3.
262  \end{description}
263
264 Sample code for loadPlugin:
265 \begin{verbatim}
266   bfuncs = lbfuncs;                  /* set Bacula funct pointers */
267   binfo  = lbinfo;
268   *pinfo  = &pluginInfo;             /* return pointer to our info */
269   *pfuncs = &pluginFuncs;            /* return pointer to our functions */
270
271    return bRC_OK;
272 \end{verbatim}
273
274 where pluginInfo and pluginFuncs are statically defined structures. 
275 See bpipe-fd.c for details.
276
277
278
279 \end{description}
280
281 \section{Plugin Entry Points}
282 This section will describe each of the entry points (subroutines) within
283 the plugin that the plugin must provide for Bacula, when they are called
284 and their arguments. As noted above, pointers to these subroutines are
285 passed back to Bacula in the pFuncs structure when Bacula calls the 
286 loadPlugin() externally defined entry point.
287
288 \subsection{newPlugin(bpContext *ctx)}
289   This is the entry point that Bacula will call
290   when a new "instance" of the plugin is created. This typically
291   happens at the beginning of a Job.  If 10 Jobs are running
292   simultaneously, there will be at least 10 instances of the
293   plugin.
294
295   The bpContext structure will be passed to the plugin, and
296   during this call, if the plugin needs to have its private
297   working storage that is associated with the particular
298   instance of the plugin, it should create it from the heap
299   (malloc the memory) and store a pointer to
300   its private working storage in the {\bf pContext} variable.
301   Note: since Bacula is a multi-threaded program, you must not
302   keep any variable data in your plugin unless it is truly meant
303   to apply globally to the whole plugin.  In addition, you must
304   be aware that except the first and last call to the plugin
305   (loadPlugin and unloadPlugin) all the other calls will be 
306   made by threads that correspond to a Bacula job.  The 
307   bpContext that will be passed for each thread will remain the
308   same throughout the Job thus you can keep your private Job specific
309   data in it ({\bf bContext}).
310
311 \begin{verbatim}
312 typedef struct s_bpContext {
313   void *pContext;   /* Plugin private context */
314   void *bContext;   /* Bacula private context */
315 } bpContext;
316
317 \end{verbatim}
318    
319   This context pointer will be passed as the first argument to all
320   the entry points that Bacula calls within the plugin.  Needless
321   to say, the plugin should not change the bContext variable, which
322   is Bacula's private context pointer for this instance (Job) of this
323   plugin.
324
325 \subsection{freePlugin(bpContext *ctx)}
326 This entry point is called when the
327 this instance of the plugin is no longer needed (the Job is
328 ending), and the plugin should release all memory it may
329 have allocated for this particular instance (Job) i.e. the pContext.  
330 This is not the final termination
331 of the plugin signaled by a call to {\bf unloadPlugin}. 
332 Any other instances (Job) will
333 continue to run, and the entry point {\bf newPlugin} may be called
334 again if other jobs start.
335
336 \subsection{getPluginValue(bpContext *ctx, pVariable var, void *value)} 
337 Bacula will call this entry point to get
338 a value from the plugin.  This entry point is currently not called.
339
340 \subsection{setPluginValue(bpContext *ctx, pVariable var, void *value)}
341 Bacula will call this entry point to set
342 a value in the plugin.  This entry point is currently not called.
343  
344 \subsection{handlePluginEvent(bpContext *ctx, bEvent *event, void *value)}
345 This entry point is called when Bacula
346 encounters certain events (discussed below). This is, in fact, the 
347 main way that most plugins get control when a Job runs and how
348 they know what is happening in the job. It can be likened to the
349 {\bf RunScript} feature that calls external programs and scripts,
350 and is very similar to the Bacula Python interface.
351 When the plugin is called, Bacula passes it the pointer to an event
352 structure (bEvent), which currently has one item, the eventType:
353
354 \begin{verbatim}
355 typedef struct s_bEvent {
356    uint32_t eventType;
357 } bEvent;
358 \end{verbatim}
359
360   which defines what event has been triggered, and for each event,
361   Bacula will pass a pointer to a value associated with that event.
362   If no value is associated with a particular event, Bacula will 
363   pass a NULL pointer, so the plugin must be careful to always check
364   value pointer prior to dereferencing it.
365   
366   The current list of events are:
367
368 \begin{verbatim}
369 typedef enum {
370   bEventJobStart                        = 1,
371   bEventJobEnd                          = 2,
372   bEventStartBackupJob                  = 3,
373   bEventEndBackupJob                    = 4,
374   bEventStartRestoreJob                 = 5,
375   bEventEndRestoreJob                   = 6,
376   bEventStartVerifyJob                  = 7,
377   bEventEndVerifyJob                    = 8,
378   bEventBackupCommand                   = 9,
379   bEventRestoreCommand                  = 10,
380   bEventLevel                           = 11,
381   bEventSince                           = 12,
382   bEventCancelCommand                   = 13,
383   bEventVssBackupAddComponents          = 14,
384   bEventVssRestoreLoadComponentMetadata = 15,
385   bEventVssRestoreSetComponentsSelected = 16,
386   bEventRestoreObject                   = 17,
387   bEventEndFileSet                      = 18,
388   bEventPluginCommand                   = 19
389 } bEventType;
390
391 \end{verbatim}
392  
393 Most of the above are self-explanatory.
394
395 \begin{description}
396  \item [bEventJobStart] is called whenever a Job starts. The value
397    passed is a pointer to a string that contains: "Jobid=nnn 
398    Job=job-name". Where nnn will be replaced by the JobId and job-name
399    will be replaced by the Job name. The variable is temporary so if you
400    need the values, you must copy them.
401
402  \item [bEventJobEnd] is called whenever a Job ends. No value is passed.
403
404  \item [bEventStartBackupJob] is called when a Backup Job begins. No value
405    is passed.
406
407  \item [bEventEndBackupJob] is called when a Backup Job ends. No value is 
408    passed.
409
410  \item [bEventStartRestoreJob] is called when a Restore Job starts. No value
411    is passed.
412
413  \item [bEventEndRestoreJob] is called when a Restore Job ends. No value is
414    passed.
415
416  \item [bEventStartVerifyJob] is called when a Verify Job starts. No value
417    is passed.
418
419  \item [bEventEndVerifyJob] is called when a Verify Job ends. No value
420    is passed.
421
422  \item [bEventBackupCommand] is called prior to the bEventStartBackupJob and
423    the plugin is passed the command string (everything after the equal sign
424    in "Plugin =" as the value.
425
426    Note, if you intend to backup a file, this is an important first point to
427    write code that copies the command string passed into your pContext area
428    so that you will know that a backup is being performed and you will know
429    the full contents of the "Plugin =" command (i.e. what to backup and
430    what virtual filename the user wants to call it.
431
432  \item [bEventRestoreCommand] is called prior to the bEventStartRestoreJob and
433    the plugin is passed the command string (everything after the equal sign
434    in "Plugin =" as the value.
435
436    See the notes above concerning backup and the command string. This is the
437    point at which Bacula passes you the original command string that was
438    specified during the backup, so you will want to save it in your pContext
439    area for later use when Bacula calls the plugin again.
440
441  \item [bEventLevel] is called when the level is set for a new Job. The value
442    is a 32 bit integer stored in the void*, which represents the Job Level code.
443
444  \item [bEventSince] is called when the since time is set for a new Job. The 
445    value is a time\_t time at which the last job was run.
446
447 \item [bEventCancelCommand] is called whenever the currently
448   running Job is cancelled
449
450 \item [bEventVssBackupAddComponents] 
451
452 \item [bEventPluginCommand] is called for each PluginCommand present in the
453   current FileSet. The event will be sent only on plugin specifed in the
454   command. The argument is the PluginCommand (not valid after the call). 
455
456 \end{description}
457
458 During each of the above calls, the plugin receives either no specific value or
459 only one value, which in some cases may not be sufficient.  However, knowing
460 the context of the event, the plugin can call back to the Bacula entry points
461 it was passed during the {\bf loadPlugin} call and get to a number of Bacula
462 variables.  (at the current time few Bacula variables are implemented, but it
463 easily extended at a future time and as needs require).
464
465 \subsection{startBackupFile(bpContext *ctx, struct save\_pkt *sp)}
466 This entry point is called only if your plugin is a command plugin, and 
467 it is called when Bacula encounters the "Plugin = " directive in
468 the Include section of the FileSet.
469 Called when beginning the backup of a file. Here Bacula provides you
470 with a pointer to the {\bf save\_pkt} structure and you must fill in 
471 this packet with the "attribute" data of the file.
472
473 \begin{verbatim}
474 struct save_pkt {
475    int32_t pkt_size;                  /* size of this packet */
476    char *fname;                       /* Full path and filename */
477    char *link;                        /* Link name if any */
478    struct stat statp;                 /* System stat() packet for file */
479    int32_t type;                      /* FT_xx for this file */
480    uint32_t flags;                    /* Bacula internal flags */
481    bool portable;                     /* set if data format is portable */
482    char *cmd;                         /* command */
483    int32_t pkt_end;                   /* end packet sentinel */
484 };
485 \end{verbatim}
486
487 The second argument is a pointer to the {\bf save\_pkt} structure for the file
488 to be backed up.  The plugin is responsible for filling in all the fields 
489 of the {\bf save\_pkt}. If you are backing up
490 a real file, then generally, the statp structure can be filled in by doing
491 a {\bf stat} system call on the file.  
492
493 If you are backing up a database or
494 something that is more complex, you might want to create a virtual file.
495 That is a file that does not actually exist on the filesystem, but represents 
496 say an object that you are backing up.  In that case, you need to ensure
497 that the {\bf fname} string that you pass back is unique so that it
498 does not conflict with a real file on the system, and you need to 
499 artifically create values in the statp packet.
500
501 Example programs such as {\bf bpipe-fd.c} show how to set these fields.  You
502 must take care not to store pointers the stack in the pointer fields such as
503 fname and link, because when you return from your function, your stack entries
504 will be destroyed. The solution in that case is to malloc() and return the
505 pointer to it. In order to not have memory leaks, you should store a pointer to
506 all memory allocated in your pContext structure so that in subsequent calls or
507 at termination, you can release it back to the system.
508
509 Once the backup has begun, Bacula will call your plugin at the {\bf pluginIO}
510 entry point to "read" the data to be backed up.  Please see the {\bf bpipe-fd.c}
511 plugin for how to do I/O.
512
513 Example of filling in the save\_pkt as used in bpipe-fd.c:
514
515 \begin{verbatim}
516    struct plugin_ctx *p_ctx = (struct plugin_ctx *)ctx->pContext;
517    time_t now = time(NULL);
518    sp->fname = p_ctx->fname;
519    sp->statp.st_mode = 0700 | S_IFREG;
520    sp->statp.st_ctime = now;
521    sp->statp.st_mtime = now;
522    sp->statp.st_atime = now;
523    sp->statp.st_size = -1;
524    sp->statp.st_blksize = 4096;
525    sp->statp.st_blocks = 1;
526    p_ctx->backup = true;
527    return bRC_OK; 
528 \end{verbatim}
529
530 Note: the filename to be created has already been created from the 
531 command string previously sent to the plugin and is in the plugin 
532 context (p\_ctx->fname) and is a malloc()ed string.  This example
533 creates a regular file (S\_IFREG), with various fields being created.
534
535 In general, the sequence of commands issued from Bacula to the plugin
536 to do a backup while processing the "Plugin = " directive are:
537
538 \begin{enumerate}
539  \item generate a bEventBackupCommand event to the specified plugin
540        and pass it the command string.
541  \item make a startPluginBackup call to the plugin, which
542        fills in the data needed in save\_pkt to save as the file
543        attributes and to put on the Volume and in the catalog.
544  \item call Bacula's internal save\_file() subroutine to save the specified
545        file.  The plugin will then be called at pluginIO() to "open"
546        the file, and then to read the file data.
547        Note, if you are dealing with a virtual file, the "open" operation
548        is something the plugin does internally and it doesn't necessarily
549        mean opening a file on the filesystem.  For example in the case of
550        the bpipe-fd.c program, it initiates a pipe to the requested program.
551        Finally when the plugin signals to Bacula that all the data was read,
552        Bacula will call the plugin with the "close" pluginIO() function.
553 \end{enumerate}
554
555
556 \subsection{endBackupFile(bpContext *ctx)}
557 Called at the end of backing up a file for a command plugin.  If the plugin's
558 work is done, it should return bRC\_OK.  If the plugin wishes to create another
559 file and back it up, then it must return bRC\_More (not yet implemented).  This
560 is probably a good time to release any malloc()ed memory you used to pass back
561 filenames.
562
563 \subsection{startRestoreFile(bpContext *ctx, const char *cmd)}
564 Called when the first record is read from the Volume that was 
565 previously written by the command plugin.
566
567 \subsection{createFile(bpContext *ctx, struct restore\_pkt *rp)}
568 Called for a command plugin to create a file during a Restore job before 
569 restoring the data. 
570 This entry point is called before any I/O is done on the file.  After
571 this call, Bacula will call pluginIO() to open the file for write.
572
573 The data in the 
574 restore\_pkt is passed to the plugin and is based on the data that was
575 originally given by the plugin during the backup and the current user
576 restore settings (e.g. where, RegexWhere, replace).  This allows the
577 plugin to first create a file (if necessary) so that the data can
578 be transmitted to it.  The next call to the plugin will be a
579 pluginIO command with a request to open the file write-only.
580
581 This call must return one of the following values:
582
583 \begin{verbatim}
584  enum {
585    CF_SKIP = 1,       /* skip file (not newer or something) */
586    CF_ERROR,          /* error creating file */
587    CF_EXTRACT,        /* file created, data to extract */
588    CF_CREATED         /* file created, no data to extract */
589 };
590 \end{verbatim}
591
592 in the restore\_pkt value {\bf create\_status}.  For a normal file,
593 unless there is an error, you must return {\bf CF\_EXTRACT}.
594
595 \begin{verbatim}
596  
597 struct restore_pkt {
598    int32_t pkt_size;                  /* size of this packet */
599    int32_t stream;                    /* attribute stream id */
600    int32_t data_stream;               /* id of data stream to follow */
601    int32_t type;                      /* file type FT */
602    int32_t file_index;                /* file index */
603    int32_t LinkFI;                    /* file index to data if hard link */
604    uid_t uid;                         /* userid */
605    struct stat statp;                 /* decoded stat packet */
606    const char *attrEx;                /* extended attributes if any */
607    const char *ofname;                /* output filename */
608    const char *olname;                /* output link name */
609    const char *where;                 /* where */
610    const char *RegexWhere;            /* regex where */
611    int replace;                       /* replace flag */
612    int create_status;                 /* status from createFile() */
613    int32_t pkt_end;                   /* end packet sentinel */
614
615 };
616 \end{verbatim}
617
618 Typical code to create a regular file would be the following:
619
620 \begin{verbatim}
621    struct plugin_ctx *p_ctx = (struct plugin_ctx *)ctx->pContext;
622    time_t now = time(NULL);
623    sp->fname = p_ctx->fname;   /* set the full path/filename I want to create */
624    sp->type = FT_REG;
625    sp->statp.st_mode = 0700 | S_IFREG;
626    sp->statp.st_ctime = now;
627    sp->statp.st_mtime = now;
628    sp->statp.st_atime = now;
629    sp->statp.st_size = -1;
630    sp->statp.st_blksize = 4096;
631    sp->statp.st_blocks = 1;
632    return bRC_OK;
633 \end{verbatim}
634
635 This will create a virtual file.  If you are creating a file that actually 
636 exists, you will most likely want to fill the statp packet using the
637 stat() system call.
638
639 Creating a directory is similar, but requires a few extra steps:
640
641 \begin{verbatim}
642    struct plugin_ctx *p_ctx = (struct plugin_ctx *)ctx->pContext;
643    time_t now = time(NULL);
644    sp->fname = p_ctx->fname;   /* set the full path I want to create */
645    sp->link = xxx; where xxx is p_ctx->fname with a trailing forward slash
646    sp->type = FT_DIREND
647    sp->statp.st_mode = 0700 | S_IFDIR;
648    sp->statp.st_ctime = now;
649    sp->statp.st_mtime = now;
650    sp->statp.st_atime = now;
651    sp->statp.st_size = -1;
652    sp->statp.st_blksize = 4096;
653    sp->statp.st_blocks = 1;
654    return bRC_OK;
655 \end{verbatim}
656
657 The link field must be set with the full cononical path name, which always 
658 ends with a forward slash.  If you do not terminate it with a forward slash,
659 you will surely have problems later.
660
661 As with the example that creates a file, if you are backing up a real
662 directory, you will want to do an stat() on the directory.  
663
664 Note, if you want the directory permissions and times to be correctly
665 restored, you must create the directory {\bf after} all the file directories
666 have been sent to Bacula. That allows the restore process to restore all the
667 files in a directory using default directory options, then at the end, restore
668 the directory permissions.  If you do it the other way around, each time you
669 restore a file, the OS will modify the time values for the directory entry.
670
671 \subsection{setFileAttributes(bpContext *ctx, struct restore\_pkt *rp)}
672 This is call not yet implemented.  Called for a command plugin.
673
674 See the definition of {\bf restre\_pkt} in the above section.
675
676 \subsection{endRestoreFile(bpContext *ctx)}
677 Called when a command plugin is done restoring a file.
678
679 \subsection{pluginIO(bpContext *ctx, struct io\_pkt *io)}
680 Called to do the input (backup) or output (restore) of data from or to a file
681 for a command plugin. These routines simulate the Unix read(), write(), open(),
682 close(), and lseek() I/O calls, and the arguments are passed in the packet and
683 the return values are also placed in the packet.  In addition for Win32 systems
684 the plugin must return two additional values (described below).
685
686 \begin{verbatim}
687  enum {
688    IO_OPEN = 1,
689    IO_READ = 2,
690    IO_WRITE = 3,
691    IO_CLOSE = 4,
692    IO_SEEK = 5
693 };
694
695 struct io_pkt {
696    int32_t pkt_size;                  /* Size of this packet */
697    int32_t func;                      /* Function code */
698    int32_t count;                     /* read/write count */
699    mode_t mode;                       /* permissions for created files */
700    int32_t flags;                     /* Open flags */
701    char *buf;                         /* read/write buffer */
702    const char *fname;                 /* open filename */
703    int32_t status;                    /* return status */
704    int32_t io_errno;                  /* errno code */
705    int32_t lerror;                    /* Win32 error code */
706    int32_t whence;                    /* lseek argument */
707    boffset_t offset;                  /* lseek argument */
708    bool win32;                        /* Win32 GetLastError returned */
709    int32_t pkt_end;                   /* end packet sentinel */
710 };
711 \end{verbatim}
712
713 The particular Unix function being simulated is indicated by the {\bf func},
714 which will have one of the IO\_OPEN, IO\_READ, ... codes listed above.  The
715 status code that would be returned from a Unix call is returned in {\bf status}
716 for IO\_OPEN, IO\_CLOSE, IO\_READ, and IO\_WRITE. The return value for IO\_SEEK
717 is returned in {\bf offset} which in general is a 64 bit value.
718
719 When there is an error on Unix systems, you must always set io\_error, and
720 on a Win32 system, you must always set win32, and the returned value from
721 the OS call GetLastError() in lerror.
722
723 For all except IO\_SEEK, {\bf status} is the return result.  In general it is
724 a positive integer unless there is an error in which case it is -1.
725
726 The following describes each call and what you get and what you
727 should return:
728
729 \begin{description}
730  \item [IO\_OPEN]
731    You will be passed fname, mode, and flags.
732    You must set on return: status, and if there is a Unix error
733    io\_errno must be set to the errno value, and if there is a 
734    Win32 error win32 and lerror. 
735
736  \item [IO\_READ]
737   You will be passed: count, and buf (buffer of size count).
738   You must set on return: status to the number of bytes 
739   read into the buffer (buf) or -1 on an error, 
740   and if there is a Unix error
741   io\_errno must be set to the errno value, and if there is a
742   Win32 error, win32 and lerror must be set.
743
744  \item [IO\_WRITE]
745   You will be passed: count, and buf (buffer of size count).
746   You must set on return: status to the number of bytes 
747   written from the buffer (buf) or -1 on an error, 
748   and if there is a Unix error
749   io\_errno must be set to the errno value, and if there is a
750   Win32 error, win32 and lerror must be set.
751
752  \item [IO\_CLOSE]
753   Nothing will be passed to you.  On return you must set 
754   status to 0 on success and -1 on failure.  If there is a Unix error
755   io\_errno must be set to the errno value, and if there is a
756   Win32 error, win32 and lerror must be set.
757
758  \item [IO\_LSEEK]
759   You will be passed: offset, and whence. offset is a 64 bit value
760   and is the position to seek to relative to whence.  whence is one
761   of the following SEEK\_SET, SEEK\_CUR, or SEEK\_END indicating to
762   either to seek to an absolute possition, relative to the current 
763   position or relative to the end of the file.
764   You must pass back in offset the absolute location to which you 
765   seeked. If there is an error, offset should be set to -1.
766   If there is a Unix error
767   io\_errno must be set to the errno value, and if there is a
768   Win32 error, win32 and lerror must be set.
769
770   Note: Bacula will call IO\_SEEK only when writing a sparse file.
771   
772 \end{description}
773
774 \subsection{bool checkFile(bpContext *ctx, char *fname)}
775 If this entry point is set, Bacula will call it after backing up all file
776 data during an Accurate backup.  It will be passed the full filename for
777 each file that Bacula is proposing to mark as deleted.  Only files
778 previously backed up but not backed up in the current session will be
779 marked to be deleted.  If you return {\bf false}, the file will be be
780 marked deleted.  If you return {\bf true} the file will not be marked
781 deleted.  This permits a plugin to ensure that previously saved virtual
782 files or files controlled by your plugin that have not change (not backed
783 up in the current job) are not marked to be deleted.  This entry point will
784 only be called during Accurate Incrmental and Differential backup jobs.
785
786
787 \section{Bacula Plugin Entrypoints}
788 When Bacula calls one of your plugin entrypoints, you can call back to
789 the entrypoints in Bacula that were supplied during the xxx plugin call
790 to get or set information within Bacula.
791
792 \subsection{bRC registerBaculaEvents(bpContext *ctx, ...)}
793 This Bacula entrypoint will allow you to register to receive events
794 that are not autmatically passed to your plugin by default. This 
795 entrypoint currently is unimplemented.
796
797 \subsection{bRC getBaculaValue(bpContext *ctx, bVariable var, void *value)}
798 Calling this entrypoint, you can obtain specific values that are available
799 in Bacula. The following Variables can be referenced:
800 \begin{itemize}
801 \item bVarJobId returns an int
802 \item bVarFDName returns a char *
803 \item bVarLevel returns an int
804 \item bVarClient returns a char *
805 \item bVarJobName returns a char *
806 \item bVarJobStatus returns an int
807 \item bVarSinceTime returns an int (time\_t)
808 \item bVarAccurate returns an int
809 \end{itemize}
810
811 \subsection{bRC setBaculaValue(bpContext *ctx, bVariable var, void *value)}
812 Calling this entrypoint allows you to set particular values in
813 Bacula. The only variable that can currently be set is 
814 {\bf bVarFileSeen} and the value passed is a char * that points
815 to the full filename for a file that you are indicating has been
816 seen and hence is not deleted.
817
818 \subsection{bRC JobMessage(bpContext *ctx, const char *file, int line,
819        int type, utime\_t mtime, const char *fmt, ...)}
820 This call permits you to put a message in the Job Report.
821
822
823 \subsection{bRC DebugMessage(bpContext *ctx, const char *file, int line,
824        int level, const char *fmt, ...)}
825 This call permits you to print a debug message.
826
827
828 \subsection{void baculaMalloc(bpContext *ctx, const char *file, int line,
829        size\_t size)}
830 This call permits you to obtain memory from Bacula's memory allocator.
831
832
833 \subsection{void baculaFree(bpContext *ctx, const char *file, int line, void *mem)}
834 This call permits you to free memory obtained from Bacula's memory allocator.
835
836 \section{Building Bacula Plugins}
837 There is currently one sample program {\bf example-plugin-fd.c} and
838 one working plugin {\bf bpipe-fd.c} that can be found in the Bacula
839 {\bf src/plugins/fd} directory.  Both are built with the following:
840
841 \begin{verbatim}
842  cd <bacula-source>
843  ./configure <your-options>
844  make
845  ...
846  cd src/plugins/fd
847  make
848  make test
849 \end{verbatim}
850
851 After building Bacula and changing into the src/plugins/fd directory,
852 the {\bf make} command will build the {\bf bpipe-fd.so} plugin, which 
853 is a very useful and working program.
854
855 The {\bf make test} command will build the {\bf example-plugin-fd.so}
856 plugin and a binary named {\bf main}, which is build from the source
857 code located in {\bf src/filed/fd\_plugins.c}. 
858
859 If you execute {\bf ./main}, it will load and run the example-plugin-fd
860 plugin simulating a small number of the calling sequences that Bacula uses
861 in calling a real plugin.  This allows you to do initial testing of 
862 your plugin prior to trying it with Bacula.
863
864 You can get a good idea of how to write your own plugin by first 
865 studying the example-plugin-fd, and actually running it.  Then
866 it can also be instructive to read the bpipe-fd.c code as it is 
867 a real plugin, which is still rather simple and small.
868
869 When actually writing your own plugin, you may use the example-plugin-fd.c
870 code as a template for your code.