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