6b980b1635d731d14c61858401cd51d7790ee7d9
[debian/amanda] / perl / Amanda / Xfer.swg
1 /*
2  * Copyright (c) 2008, 2009, 2010 Zmanda, Inc.  All Rights Reserved.
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License version 2 as published
6  * by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
10  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
11  * for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16  *
17  * Contact information: Zmanda Inc., 465 S. Mathilda Ave., Suite 300
18  * Sunnyvale, CA 94085, USA, or: http://www.zmanda.com
19  */
20
21 %module "Amanda::Xfer"
22 %include "amglue/amglue.swg"
23 %include "exception.i"
24 %include "cstring.i"
25 %import "Amanda/MainLoop.swg"
26
27 %include "Xfer.pod"
28
29 %{
30 #include "glib-util.h"
31 #include "amxfer.h"
32 %}
33
34 /* The SWIGging of the transfer architecture.
35  *
36  * The C layer of the transfer architecture exposes some structs, which are
37  * arranged through GObject magic into a class hierarchy.  It also exposes
38  * regular C functions which are intended to act as methods on these structs.
39  * Furthermore, it exposes Perl callbacks (via Amanda::MainLoop) with
40  * parameters involving objects of these classes.
41  *
42  * SWIG doesn't support callbacks very well, and makes it particularly
43  * difficult to represent a GObject class hierarchy.  Rather than try to "make
44  * it fit" into SWIG, this module uses custom typemaps and perl/C conversions
45  * to get all of this stuff right in the first place.
46  *
47  * For Xfer objects, we define two functions, new_sv_for_xfer and xfer_from_sv,
48  * which create a new SV for an Xfer object, and subsequently extract a pointer
49  * to the object from the SV.  The SV is both blessed and tied to the
50  * Amanda::Xfer::Xfer class, in which all of the method calls are defined, and
51  * which defines a DESTROY method that calls xfer_unref.
52  *
53  * XferElements are similar, but we have the added challenge of representing
54  * subclasses with appropriate perl subclasses.  The solution is to tag each C
55  * class with a perl class name, and use that name when blessing a new SV.
56  *
57  * Finally, XMsgs are reflected entirely into perl hashrefs, in the interest of
58  * efficiency.
59  */
60
61 /*
62  * Initialization
63  */
64
65 %init %{
66     /* We need GType and GThread initialized to use xfers */
67     glib_init();
68 %}
69
70 /*
71  * Constants
72  */
73
74 amglue_add_enum_tag_fns(xfer_status);
75 amglue_add_constant(XFER_INIT, xfer_status);
76 amglue_add_constant(XFER_START, xfer_status);
77 amglue_add_constant(XFER_RUNNING, xfer_status);
78 amglue_add_constant(XFER_DONE, xfer_status);
79 amglue_copy_to_tag(xfer_status, constants);
80
81 amglue_add_enum_tag_fns(xmsg_type);
82 amglue_add_constant(XMSG_INFO, xmsg_type);
83 amglue_add_constant(XMSG_ERROR, xmsg_type);
84 amglue_add_constant(XMSG_DONE, xmsg_type);
85 amglue_add_constant(XMSG_CANCEL, xmsg_type);
86 amglue_add_constant(XMSG_PART_DONE, xmsg_type);
87 amglue_add_constant(XMSG_READY, xmsg_type);
88 amglue_copy_to_tag(xmsg_type, constants);
89
90 /*
91  * Wrapping machinery
92  */
93
94 %{
95 /* Given an XMsg, return a hashref representing the message as a pure-perl
96  * object.  The object is new, has refcount 1, and is totally independent of
97  * the underlying XMsg.
98  *
99  * Reflecting the XMsg directly into Perl avoids the need to reference-count
100  * the XMsg objects themselves, which can simply be freed after a callback
101  * completes.  The overhead of creating a hash is likely equivalent to or
102  * less than the overhead that would be consumed with SWIG's swig_$field_get
103  * accessors, assuming that perl code examines most of the fields in a message.
104  *
105  * @param msg: the message to represent
106  * @returns: a perl SV
107  */
108 static SV *
109 new_sv_for_xmsg(
110     XMsg *msg)
111 {
112     static HV *amanda_xfer_msg_stash = NULL;
113     HV *hash = newHV();
114     SV *rv = newRV_noinc((SV *)hash);
115
116     /* bless the rv as an Amanda::Xfer::Msg object */
117     if (!amanda_xfer_msg_stash) {
118         amanda_xfer_msg_stash = gv_stashpv("Amanda::Xfer::Msg", GV_ADD);
119     }
120     sv_bless(rv, amanda_xfer_msg_stash);
121
122     /* TODO: consider optimizing by precomputing the hash values of
123      * the keys? */
124
125     /* elt */
126     hv_store(hash, "elt", 3, new_sv_for_xfer_element(msg->elt), 0);
127
128     /* type */
129     hv_store(hash, "type", 4, newSViv(msg->type), 0);
130
131     /* type */
132     hv_store(hash, "version", 7, newSViv(msg->version), 0);
133
134     /* message */
135     if (msg->message)
136         hv_store(hash, "message", 7, newSVpv(msg->message, 0), 0);
137
138     /* successful */
139     hv_store(hash, "successful", 10, newSViv(msg->successful), 0);
140
141     /* eom */
142     hv_store(hash, "eom", 3, newSViv(msg->eom), 0);
143
144     /* eof */
145     hv_store(hash, "eof", 3, newSViv(msg->eof), 0);
146
147     /* size */
148     hv_store(hash, "size", 4, amglue_newSVu64(msg->size), 0);
149
150     /* duration */
151     hv_store(hash, "duration", 8, newSVnv(msg->duration), 0);
152
153     /* partnum */
154     hv_store(hash, "partnum", 7, amglue_newSVu64(msg->partnum), 0);
155
156     /* fileno */
157     hv_store(hash, "fileno", 6, amglue_newSVu64(msg->fileno), 0);
158
159     return rv;
160 }
161 %}
162
163 %typemap(in) Xfer * {
164     $1 = xfer_from_sv($input);
165 }
166
167 %typemap(in) XferElement * {
168     $1 = xfer_element_from_sv($input);
169 }
170
171 %typemap(out) Xfer * {
172     $result = sv_2mortal(new_sv_for_xfer($1));
173     argvi++;
174 }
175
176 %typemap(out) XferElement * {
177     $result = sv_2mortal(new_sv_for_xfer_element($1));
178     argvi++;
179 }
180
181 %typemap(newfree) Xfer * {
182     xfer_unref($1);
183 }
184
185 %typemap(newfree) XferElement * {
186     xfer_element_unref($1);
187 }
188
189 /*
190  * Xfer functions
191  */
192
193 /* A typemap for the input to the Xfer constructor, a.k.a. xfer_new */
194 %typemap(in,numinputs=1) (XferElement **elementlist, unsigned int nelements) {
195     AV *av;
196     unsigned int i;
197
198     /* check that it's an arrayref */
199     if (!SvROK($input) || SvTYPE(SvRV($input)) != SVt_PVAV) {
200         SWIG_exception(SWIG_TypeError, "Expected an arrayref");
201     }
202     av = (AV *)SvRV($input);
203
204     /* allocate memory for $1 */
205     $2 = av_len(av)+1; /* av_len(av) is like $#av */
206     $1 = g_new(XferElement *, $2);
207
208     /* extract the underlying XferElement objects and add pointers to
209      * them, "borrowing" the caller's references for the moment. */
210     for (i = 0; i < $2; i++) {
211         SV **sv = av_fetch(av, i, 0);
212         XferElement *elt = sv? xfer_element_from_sv(*sv):NULL;
213
214         if (!elt) {
215             SWIG_exception(SWIG_TypeError, "Expected an arrayref of Amanda::Xfer::Element objects");
216         }
217         $1[i] = elt;
218     }
219 }
220
221 %typemap(freearg) (XferElement **elementlist, unsigned int nelements) {
222     /* free the element vector allocated in the (in) typemap */
223     g_free($1);
224 }
225
226 %newobject xfer_new;
227 Xfer *xfer_new(XferElement **elementlist, unsigned int nelements);
228 void xfer_unref(Xfer *);
229 xfer_status xfer_get_status(Xfer *xfer);
230 char *xfer_repr(Xfer *xfer);
231 void xfer_start(Xfer *xfer);
232 void xfer_cancel(Xfer *xfer);
233 /* xfer_get_source is implemented below */
234
235 %inline %{
236 /* SWIG wants to treat this as a function */
237 #define xfer_get_status(xfer) ((xfer)->status)
238 %}
239
240 /* upgrade the start method to optionally take a callback, which is
241  * passed to the GSource's set_callback */
242 %perlcode %{
243 sub xfer_start_with_callback {
244     my ($xfer, $cb) = @_;
245     if (defined $cb) {
246         my $releasing_cb = sub {
247             my ($src, $msg, $xfer) = @_;
248             my $done = $msg->{'type'} == $XMSG_DONE;
249             $src->remove() if $done;
250             $cb->(@_);
251             $cb = undef if $done; # break potential reference loop
252         };
253         $xfer->get_source()->set_callback($releasing_cb);
254     }
255     xfer_start($xfer);
256 }
257 %}
258
259 /*
260  * XferElement functions
261  *
262  * Some of these methods are not intended to be used from Perl; they are annotated
263  * as "private".
264  */
265
266 void xfer_element_unref(XferElement *elt); /* (wrap the macro, above) */
267 /* xfer_element_link_to -- private */
268 char *xfer_element_repr(XferElement *elt);
269 /* xfer_element_start -- private */
270 /* xfer_element_cancel -- private */
271
272 %inline %{
273 static gboolean same_elements(
274         XferElement *a,
275         XferElement *b)
276 {
277     return a == b;
278 }
279 %}
280
281 /* subclass constructors */
282
283 /* N.B. When adding new classes, ensure that the class_init function
284  * sets perl_class to the appropriate value. */
285
286 %newobject xfer_source_random;
287 XferElement *xfer_source_random(
288     guint64 length,
289     guint32 seed);
290
291 guint32 xfer_source_random_get_seed(
292     XferElement *self);
293
294 %typemap(in) (void * pattern, size_t pattern_length) {
295  size_t len;
296  char * pat;
297
298  pat = SvPV($input, len);
299  $1 = g_memdup(pat, len);
300  $2 = len;
301 }
302
303 %typemap(in) (gchar **argv) {
304     AV *av;
305     unsigned int len;
306     unsigned int i;
307
308     /* check that it's an arrayref */
309     if (!SvROK($input) || SvTYPE(SvRV($input)) != SVt_PVAV) {
310         SWIG_exception(SWIG_TypeError, "Expected a non-empty arrayref");
311     }
312     av = (AV *)SvRV($input);
313
314     /* allocate memory for $1 */
315     len = av_len(av)+1; /* av_len(av) is like $#av */
316     if (!len) {
317         SWIG_exception(SWIG_TypeError, "Expected a non-empty arrayref");
318     }
319     $1 = g_new0(gchar *, len+1);
320
321     for (i = 0; i < len; i++) {
322         SV **sv = av_fetch(av, i, 0);
323         g_assert(sv != NULL);
324         $1[i] = g_strdup(SvPV_nolen(*sv));
325     }
326
327     /* final element is already NULL due to g_new0; xfer_filter_process takes
328      * care of freeing this array, so we don't have to */
329 }
330
331 %newobject xfer_source_pattern;
332 XferElement *xfer_source_pattern(
333     guint64 length,
334     void * pattern,
335     size_t pattern_length);
336
337 %newobject xfer_source_fd;
338 XferElement *xfer_source_fd(
339     int fd);
340
341 %newobject xfer_source_directtcp_listen;
342 XferElement *xfer_source_directtcp_listen(void);
343
344 %inline %{
345 static DirectTCPAddr *
346 xfer_source_directtcp_listen_get_addrs(XferElement *elt) {
347     return elt->input_listen_addrs;
348 }
349 %}
350
351 %newobject xfer_source_directtcp_connect;
352 XferElement *xfer_source_directtcp_connect(DirectTCPAddr *addrs);
353
354 %newobject xfer_filter_xor;
355 XferElement *xfer_filter_xor(
356     unsigned char xor_key);
357
358 %newobject xfer_filter_process;
359 XferElement *xfer_filter_process(
360     gchar **argv,
361     gboolean need_root);
362
363 %newobject xfer_dest_null;
364 XferElement *xfer_dest_null(
365     guint32 prng_seed);
366
367 %newobject xfer_dest_buffer;
368 XferElement *xfer_dest_buffer(
369     gsize max_size);
370
371 %cstring_output_allocate_size(gpointer *buf, gsize *size, );
372 void xfer_dest_buffer_get(
373     XferElement *elt,
374     gpointer *buf,
375     gsize *size);
376
377 %newobject xfer_dest_fd;
378 XferElement *xfer_dest_fd(
379     int fd);
380
381 %newobject xfer_dest_directtcp_listen;
382 XferElement *xfer_dest_directtcp_listen(void);
383
384 %inline %{
385 static DirectTCPAddr *
386 xfer_dest_directtcp_listen_get_addrs(XferElement *elt) {
387     return elt->output_listen_addrs;
388 }
389 %}
390
391 %newobject xfer_dest_directtcp_connect;
392 XferElement *xfer_dest_directtcp_connect(DirectTCPAddr *addrs);
393
394 /*
395  * Callback handling
396  */
397
398 %types(amglue_Source *);
399 %{
400 static gboolean
401 xmsgsource_perl_callback(
402     gpointer data,
403     struct XMsg *msg,
404     Xfer *xfer)
405 {
406     dSP;
407     amglue_Source *src = (amglue_Source *)data;
408     SV *src_sv = NULL;
409     SV *msg_sv = NULL;
410     SV *xfer_sv = NULL;
411
412     /* keep the source around long enough for the call to finish */
413     amglue_source_ref(src);
414     g_assert(src->callback_sv != NULL);
415
416     ENTER;
417     SAVETMPS;
418
419     /* create a new SV pointing to 'src', and increase its refcount
420      * accordingly. */
421     amglue_source_ref(src);
422     src_sv = SWIG_NewPointerObj(src, SWIGTYPE_p_amglue_Source,
423                                  SWIG_OWNER | SWIG_SHADOW);
424     SvREFCNT_inc(src_sv);
425
426     msg_sv = new_sv_for_xmsg(msg);
427     xfer_sv = new_sv_for_xfer(xfer);
428
429     PUSHMARK(SP);
430     XPUSHs(sv_2mortal(src_sv));
431     XPUSHs(sv_2mortal(msg_sv));
432     XPUSHs(sv_2mortal(xfer_sv));
433     PUTBACK;
434
435     call_sv(src->callback_sv, G_EVAL|G_DISCARD);
436
437     FREETMPS;
438     LEAVE;
439
440     /* we no longer need the src */
441     amglue_source_unref(src);
442     src = NULL;
443
444     /* these may be gone, so NULL them out */
445     src_sv = NULL;
446     msg_sv = NULL;
447     xfer_sv = NULL;
448
449     /* check for an uncaught 'die'.  If we don't do this, then Perl will longjmp()
450      * over the GMainLoop mechanics, leaving GMainLoop in an inconsistent (locked)
451      * state. */
452     if (SvTRUE(ERRSV)) {
453         /* We handle this just the way the default 'die' handler in Amanda::Debug 
454          * does, but since Amanda's debug support may not yet be running, we back
455          * it up with an exit() */
456         g_critical("%s", SvPV_nolen(ERRSV));
457         exit(1);
458     }
459
460     return TRUE;
461 }
462 %}
463
464 %newobject xfer_get_amglue_source;
465 %inline %{
466 amglue_Source *
467 xfer_get_amglue_source(
468     Xfer *xfer)
469 {
470     return amglue_source_get(xfer_get_source(xfer),
471         (GSourceFunc)xmsgsource_perl_callback);
472 }
473 %}
474
475 /*
476  * XMsg and XMsgSource handling
477  */
478
479 /*
480  * The perl side
481  */
482
483 /* First, a few macros to generate decent Perl */
484
485 %define PACKAGE(PKG)
486 %perlcode {
487 package PKG;
488 }
489 %enddef
490
491 %define XFER_ELEMENT_SUBCLASS_OF(PARENT)
492 %perlcode {
493 use vars qw(@ISA);
494 @ISA = qw( PARENT );
495 }
496 %enddef
497
498 %define XFER_ELEMENT_SUBCLASS()
499 XFER_ELEMENT_SUBCLASS_OF(Amanda::Xfer::Element)
500 %enddef
501
502 %define DECLARE_CONSTRUCTOR(C_CONSTRUCTOR)
503 %perlcode {
504 sub new { 
505     my $pkg = shift;
506     # The C function adds the proper blessing -- this function
507     # just gets $pkg out of the way.
508     C_CONSTRUCTOR(@_);
509 }
510 }
511 %enddef
512
513 %define OVERLOAD_REPR()
514 %perlcode {
515 use overload '""' => sub { $_[0]->repr(); };
516 # overload comparison, so users can ask if one obj == another
517 use overload '==' => sub {     Amanda::Xfer::same_elements($_[0], $_[1]); };
518 use overload '!=' => sub { not Amanda::Xfer::same_elements($_[0], $_[1]); };
519 }
520 %enddef
521
522 %define DECLARE_METHOD(METHOD_NAME, C_FUNCTION)
523 %perlcode {*METHOD_NAME = *C_FUNCTION;
524 }
525 %enddef
526
527 /* And now define the required perl classes */
528
529 PACKAGE(Amanda::Xfer::Xfer)
530 DECLARE_CONSTRUCTOR(Amanda::Xfer::xfer_new);
531 DECLARE_METHOD(DESTROY, Amanda::Xfer::xfer_unref);
532 OVERLOAD_REPR()
533 DECLARE_METHOD(repr, Amanda::Xfer::xfer_repr);
534 DECLARE_METHOD(get_status, Amanda::Xfer::xfer_get_status);
535 DECLARE_METHOD(get_source, Amanda::Xfer::xfer_get_amglue_source);
536 DECLARE_METHOD(start, Amanda::Xfer::xfer_start_with_callback);
537 DECLARE_METHOD(cancel, Amanda::Xfer::xfer_cancel);
538
539 /* ---- */
540
541 PACKAGE(Amanda::Xfer::Element)
542 DECLARE_METHOD(DESTROY, Amanda::Xfer::xfer_element_unref);
543 OVERLOAD_REPR()
544 DECLARE_METHOD(repr, Amanda::Xfer::xfer_element_repr);
545
546 /* ---- */
547
548 PACKAGE(Amanda::Xfer::Element::Glue)
549 XFER_ELEMENT_SUBCLASS()
550 /* no constructor -- internal use only */
551
552 /* ---- */
553
554 PACKAGE(Amanda::Xfer::Source::Fd)
555 XFER_ELEMENT_SUBCLASS()
556 DECLARE_CONSTRUCTOR(Amanda::Xfer::xfer_source_fd)
557
558 /* ---- */
559
560 PACKAGE(Amanda::Xfer::Source::Random)
561 XFER_ELEMENT_SUBCLASS()
562 DECLARE_CONSTRUCTOR(Amanda::Xfer::xfer_source_random)
563 DECLARE_METHOD(get_seed, Amanda::Xfer::xfer_source_random_get_seed)
564
565 /* ---- */
566
567 PACKAGE(Amanda::Xfer::Source::DirectTCPListen)
568 XFER_ELEMENT_SUBCLASS()
569 DECLARE_CONSTRUCTOR(Amanda::Xfer::xfer_source_directtcp_listen)
570 DECLARE_METHOD(get_addrs, Amanda::Xfer::xfer_source_directtcp_listen_get_addrs)
571
572 /* ---- */
573
574 PACKAGE(Amanda::Xfer::Source::DirectTCPConnect)
575 XFER_ELEMENT_SUBCLASS()
576 DECLARE_CONSTRUCTOR(Amanda::Xfer::xfer_source_directtcp_connect)
577
578 /* ---- */
579
580 PACKAGE(Amanda::Xfer::Source::Pattern)
581 XFER_ELEMENT_SUBCLASS()
582 DECLARE_CONSTRUCTOR(Amanda::Xfer::xfer_source_pattern)
583
584 /* ---- */
585
586 PACKAGE(Amanda::Xfer::Filter::Xor)
587 XFER_ELEMENT_SUBCLASS()
588 DECLARE_CONSTRUCTOR(Amanda::Xfer::xfer_filter_xor)
589
590 /* ---- */
591
592 PACKAGE(Amanda::Xfer::Filter::Process)
593 XFER_ELEMENT_SUBCLASS()
594 DECLARE_CONSTRUCTOR(Amanda::Xfer::xfer_filter_process)
595
596 /* ---- */
597
598 PACKAGE(Amanda::Xfer::Dest::Fd)
599 XFER_ELEMENT_SUBCLASS()
600 DECLARE_CONSTRUCTOR(Amanda::Xfer::xfer_dest_fd)
601
602 /* ---- */
603
604 PACKAGE(Amanda::Xfer::Dest::Null)
605 XFER_ELEMENT_SUBCLASS()
606 DECLARE_CONSTRUCTOR(Amanda::Xfer::xfer_dest_null)
607
608 /* ---- */
609
610 PACKAGE(Amanda::Xfer::Dest::Buffer)
611 XFER_ELEMENT_SUBCLASS()
612 DECLARE_CONSTRUCTOR(Amanda::Xfer::xfer_dest_buffer)
613 DECLARE_METHOD(get, Amanda::Xfer::xfer_dest_buffer_get)
614
615 /* ---- */
616
617 PACKAGE(Amanda::Xfer::Dest::DirectTCPListen)
618 XFER_ELEMENT_SUBCLASS()
619 DECLARE_CONSTRUCTOR(Amanda::Xfer::xfer_dest_directtcp_listen)
620 DECLARE_METHOD(get_addrs, Amanda::Xfer::xfer_dest_directtcp_listen_get_addrs)
621
622 /* ---- */
623
624 PACKAGE(Amanda::Xfer::Dest::DirectTCPConnect)
625 XFER_ELEMENT_SUBCLASS()
626 DECLARE_CONSTRUCTOR(Amanda::Xfer::xfer_dest_directtcp_connect)
627
628 /* ---- */
629
630 PACKAGE(Amanda::Xfer::Msg)
631 %perlcode %{
632 use Data::Dumper;
633 use overload '""' => sub { $_[0]->repr(); };
634
635 sub repr {
636     my ($self) = @_;
637     local $Data::Dumper::Indent = 0;
638     local $Data::Dumper::Terse = 1;
639     local $Data::Dumper::Useqq = 1;
640
641     my $typestr = Amanda::Xfer::xmsg_type_to_string($self->{'type'});
642     my $str = "{ type => \$$typestr, elt => $self->{'elt'}, version => $self->{'version'},";
643
644     my %skip = ( "type" => 1, "elt" => 1, "version" => 1 );
645     for my $k (keys %$self) {
646         next if $skip{$k};
647         $str .= " $k => " . Dumper($self->{$k}) . ",";
648     }
649
650     # strip the trailing comma and add a closing brace
651     $str =~ s/,$/ }/g;
652
653     return $str;
654 }
655 %}
656
657 /* ---- */
658
659 PACKAGE(Amanda::Xfer)
660 %perlcode %{
661 # make Amanda::Xfer->new equivalent to Amanda::Xfer::Xfer->new (don't
662 # worry, the blessings work out just fine)
663 *new = *Amanda::Xfer::Xfer::new;
664
665 # try to load Amanda::XferServer, which is server-only.  If it's not found, then
666 # its classes just remain undefined.
667 BEGIN {
668     eval "use Amanda::XferServer;";
669 }
670 %}