-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspreadmodule.c
1290 lines (1159 loc) · 33.9 KB
/
spreadmodule.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2001-2005 Python Software Foundation. All rights reserved.
This code is released under the standard PSF license.
See the file LICENSE.
*/
/* Python wrapper module for the Spread toolkit: http://www.spread.org/ */
#include "Python.h"
#include "structmember.h"
#include "sp.h"
#ifdef WITH_THREAD
/*
Jonathan Stanton (of Spread) verified multithreaded apps can suffer races
when Spread disconnects a mailbox, due to socket recycling (another thread,
which doesn't know about the disconnect, continues using the same socket
desciptor, but it can magically refer to a new connection). They know
about this, and believe they know how to fix it, but haven't fixed it yet
(3.16.2).
We used to worm around it by setting the mbox disconnected flag to true when
Spread returns CONNECTION_CLOSED or ILLEGAL_SESSION. Guido scoured the Spread
source and determined that those were the only Spread errors that closed
the socket descriptor. Alas, it takes another level of locking to do the
{check that flag, call Spread, maybe set that flag} sequence indivisibly.
However that also has the effect of serializing all calls to Spread via a
given mailbox, and so a call to receive() in one thread blocks all threads
from invoking Spread on that mailbox until the receive() returns. But if
the receive is waiting for a multicast from another thread, that's deadlock.
Until Spread disconnection semantics are fixed, we can't win: we either
leave the Spread disconnection race unaddressed, or leave apps open to
deadlock. For now we choose the former.
*/
#include "pythread.h"
/* #define SPREAD_DISCONNECT_RACE_BUG */
#endif
#ifdef SPREAD_DISCONNECT_RACE_BUG
/* Acquiring the lock is ugly, because another thread may be holding on to
it: we need to release the GIL in order to allow the other thread to
make progress.
*/
#define ACQUIRE_MBOX_LOCK(MBOX) \
do { \
Py_BEGIN_ALLOW_THREADS \
PyThread_acquire_lock((MBOX)->spread_lock, 1); \
Py_END_ALLOW_THREADS \
} while(0)
#define RELEASE_MBOX_LOCK(MBOX) PyThread_release_lock((MBOX)->spread_lock)
#else
#define ACQUIRE_MBOX_LOCK(MBOX)
#define RELEASE_MBOX_LOCK(MBOX)
#endif
static PyObject *SpreadError;
#define DEFAULT_GROUPS_SIZE 10
#define DEFAULT_BUFFER_SIZE 10000
#define MAX_VSSETS 10
#define MAX_MEMBERS 100
typedef struct {
PyObject_HEAD
mailbox mbox;
PyObject *private_group;
int disconnected;
#ifdef SPREAD_DISCONNECT_RACE_BUG
PyThread_type_lock spread_lock;
#endif
} MailboxObject;
static PyObject *spread_error(int, MailboxObject *);
typedef struct {
PyObject_HEAD
PyObject *sender;
PyObject *groups;
int msg_type;
int endian;
PyObject *message;
} RegularMsg;
typedef struct {
PyObject_HEAD
int reason;
PyObject *group;
PyObject *group_id;
PyObject *members;
PyObject *orig_members; /* the vs sets that came together in this vs */
} MembershipMsg;
typedef struct {
PyObject_HEAD
group_id gid;
} GroupId;
static PyTypeObject Mailbox_Type;
static PyTypeObject RegularMsg_Type;
static PyTypeObject MembershipMsg_Type;
static PyTypeObject GroupId_Type;
#define MailboxObject_Check(v) ((v)->ob_type == &Mailbox_Type)
#define RegularMsg_Check(v) ((v)->ob_type == &RegularMsg_Type)
#define MembershipMsg_Check(v) ((v)->ob_type == &MembershipMsg_Type)
#define GroupId_Check(v) ((v)->ob_type == &GroupId_Type)
static PyObject *
new_group_id(group_id gid)
{
GroupId *self;
self = PyObject_New(GroupId, &GroupId_Type);
if (!self)
return NULL;
self->gid = gid;
return (PyObject *)self;
}
static void
group_id_dealloc(GroupId *v)
{
PyObject_Del(v);
}
static PyObject *
group_id_repr(GroupId *v)
{
char buf[80];
sprintf(buf, "<group_id %08X:%08X:%08X>",
v->gid.id[0], v->gid.id[1], v->gid.id[2]);
return PyUnicode_FromString(buf);
}
static PyObject *
group_id_richcompare(PyObject *v, PyObject *w, int op)
{
PyObject *res;
if (!GroupId_Check(v) || !GroupId_Check(w) ||
(op != Py_EQ && op != Py_NE)) {
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
if (SP_equal_group_ids(((GroupId *)v)->gid, ((GroupId *)w)->gid) ==
(op == Py_NE))
res = Py_False;
else
res = Py_True;
Py_INCREF(res);
return res;
}
static PyTypeObject GroupId_Type = {
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
PyVarObject_HEAD_INIT(NULL, 0)
"GroupId", /* tp_name */
sizeof(GroupId), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)group_id_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
(reprfunc)group_id_repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
group_id_richcompare, /* tp_richcompare */
};
#define CAUSED_BY_MASK (CAUSED_BY_JOIN | CAUSED_BY_LEAVE | \
CAUSED_BY_DISCONNECT | CAUSED_BY_NETWORK)
static PyObject *
new_membership_msg(int type, PyObject *group, unsigned int num_members,
char (*members)[MAX_GROUP_NAME], char *buffer, int size)
{
MembershipMsg *self;
membership_info memb_info;
unsigned int max_num_vs_sets = MAX_VSSETS;
vs_set_info vssets_buffer[MAX_VSSETS];
vs_set_info *vssets = vssets_buffer;
unsigned int my_vsset_index;
unsigned int num_vs_sets, max_members;
char vs_members_buffer[MAX_MEMBERS][MAX_GROUP_NAME];
char (*vs_members)[MAX_GROUP_NAME] = vs_members_buffer;
unsigned int i, j, ret;
assert(group != NULL);
self = PyObject_New(MembershipMsg, &MembershipMsg_Type);
if (self == NULL)
return NULL;
self->reason = type & CAUSED_BY_MASK; /* from sp.h defines */
Py_INCREF(group);
self->group = group;
self->members = NULL;
self->orig_members = NULL;
self->group_id = NULL;
self->members = PyTuple_New(num_members);
if (self->members == NULL) {
Py_DECREF(self);
return NULL;
}
for (i = 0; i < num_members; ++i) {
PyObject *s = PyBytes_FromString(members[i]);
if (!s) {
Py_DECREF(self);
return NULL;
}
PyTuple_SET_ITEM(self->members, i, s);
}
ret = SP_get_memb_info( buffer, type, &memb_info );
if (ret < 0) {
Py_DECREF(self); /* printf("BUG: membership message does not have valid body\n"); */
return NULL;
}
if ( type & REG_MEMB_MESS ) {
self->group_id = new_group_id(memb_info.gid);
if (self->group_id == NULL) {
Py_DECREF(self);
return NULL;
}
if ( memb_info.num_vs_sets > max_num_vs_sets ) {
max_num_vs_sets = memb_info.num_vs_sets;
vssets = malloc(sizeof(vs_set_info) * max_num_vs_sets);
if (vssets == NULL) {
PyErr_NoMemory();
goto memb_error;
}
}
num_vs_sets = SP_get_vs_sets_info( buffer, &vssets[0], max_num_vs_sets, &my_vsset_index );
if (num_vs_sets < 0) {
goto memb_error; /* shouldn't happen */
}
self->orig_members = PyTuple_New(num_vs_sets);
if (self->orig_members == NULL) {
goto memb_error;
}
max_members = 0;
for ( i = 0; i < num_vs_sets; i++ ) {
if ( vssets[i].num_members > max_members ) { max_members = vssets[i].num_members; }
}
if ( max_members > MAX_MEMBERS ) {
vs_members = malloc( MAX_GROUP_NAME * max_members );
if (vs_members == NULL) {
PyErr_NoMemory();
goto memb_error;
}
}
for ( i = 0; i < num_vs_sets; i++ ) {
PyObject *t;
ret = SP_get_vs_set_members(buffer, &vssets[i], vs_members, max_members);
if (ret < 0) {
goto memb_error; /* shouldn't happen */
}
t = PyTuple_New(vssets[i].num_members);
for ( j = 0; j < vssets[i].num_members; j++ ) {
PyObject *s;
/* Spread promises this: */
assert(strlen(vs_members[j]) < MAX_GROUP_NAME);
s = PyBytes_FromString(vs_members[j]);
if (!s) {
goto memb_error;
}
PyTuple_SET_ITEM(t, j, s);
}
PyTuple_SET_ITEM(self->orig_members, i, t);
}
}
if (vssets != vssets_buffer)
free(vssets);
if (vs_members != vs_members_buffer)
free(vs_members);
return (PyObject *)self;
memb_error:
if (vssets != vssets_buffer)
free(vssets);
if (vs_members != vs_members_buffer)
free(vs_members);
Py_DECREF(self);
return NULL;
}
static void
membership_msg_dealloc(MembershipMsg *self)
{
Py_XDECREF(self->group);
Py_XDECREF(self->members);
Py_XDECREF(self->orig_members);
Py_XDECREF(self->group_id);
PyObject_Del(self);
}
#define OFF(x) offsetof(MembershipMsg, x)
static struct PyMemberDef MembershipMsg_memberlist[] = {
{"reason", T_INT, OFF(reason)},
{"group", T_OBJECT, OFF(group)},
{"group_id", T_OBJECT, OFF(group_id)},
{"members", T_OBJECT, OFF(members)},
{"orig_members", T_OBJECT, OFF(orig_members)},
{NULL}
};
#undef OFF
static PyTypeObject MembershipMsg_Type = {
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
PyVarObject_HEAD_INIT(NULL, 0)
"MembershipMsg", /* tp_name */
sizeof(MembershipMsg), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)membership_msg_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
MembershipMsg_memberlist, /* tp_members */
};
static PyObject *
new_regular_msg(PyObject *sender, int num_groups,
char (*groups)[MAX_GROUP_NAME], int msg_type,
int endian, PyObject *message)
{
RegularMsg *self;
int i;
self = PyObject_New(RegularMsg, &RegularMsg_Type);
if (self == NULL)
return NULL;
self->message = NULL;
self->sender = NULL;
assert(num_groups >= 0);
self->groups = PyTuple_New(num_groups);
if (self->groups == NULL) {
Py_DECREF(self);
return NULL;
}
for (i = 0; i < num_groups; ++i) {
PyObject *s = PyBytes_FromString(groups[i]);
if (!s) {
Py_DECREF(self);
return NULL;
}
PyTuple_SET_ITEM(self->groups, i, s);
}
Py_INCREF(sender);
self->sender = sender;
Py_INCREF(message);
self->message = message;
self->msg_type = msg_type;
self->endian = endian;
return (PyObject *)self;
}
static void
regular_msg_dealloc(RegularMsg *self)
{
Py_XDECREF(self->sender);
Py_XDECREF(self->groups);
Py_XDECREF(self->message);
PyObject_Del(self);
}
#define OFF(x) offsetof(RegularMsg, x)
static struct PyMemberDef RegularMsg_memberlist[] = {
{"msg_type", T_INT, OFF(msg_type)},
{"endian", T_INT, OFF(endian)},
{"sender", T_OBJECT, OFF(sender)},
{"groups", T_OBJECT, OFF(groups)},
{"message", T_OBJECT, OFF(message)},
{NULL}
};
#undef OFF
static PyTypeObject RegularMsg_Type = {
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
PyVarObject_HEAD_INIT(NULL, 0)
"RegularMsg", /* tp_name */
sizeof(RegularMsg), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)regular_msg_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
RegularMsg_memberlist, /* tp_members */
};
static MailboxObject *
new_mailbox(mailbox mbox)
{
MailboxObject *self;
self = PyObject_New(MailboxObject, &Mailbox_Type);
if (self == NULL)
{
printf("Unable to create Mailbox object\n");
return NULL;
}
self->mbox = mbox;
self->private_group = NULL;
self->disconnected = 0;
#ifdef SPREAD_DISCONNECT_RACE_BUG
self->spread_lock = NULL;
#endif
return self;
}
/* mailbox methods */
static void
mailbox_dealloc(MailboxObject *self)
{
if (self->disconnected == 0)
SP_disconnect(self->mbox);
Py_DECREF(self->private_group);
#ifdef SPREAD_DISCONNECT_RACE_BUG
if (self->spread_lock)
PyThread_free_lock(self->spread_lock);
#endif
PyObject_Del(self);
}
static PyObject *
err_disconnected(char *methodname)
{
PyErr_Format(SpreadError, "%s() called on closed mbox", methodname);
return NULL;
}
static PyObject *
mailbox_disconnect(MailboxObject *self, PyObject *args)
{
PyObject *result = Py_None;
if (!PyArg_ParseTuple(args, ":disconnect"))
return NULL;
if (!self->disconnected) {
ACQUIRE_MBOX_LOCK(self);
if (!self->disconnected) {
int err;
self->disconnected = 1;
Py_BEGIN_ALLOW_THREADS
err = SP_disconnect(self->mbox);
Py_END_ALLOW_THREADS
if (err != 0)
result = spread_error(err, self);
}
RELEASE_MBOX_LOCK(self);
}
Py_XINCREF(result);
return result;
}
static PyObject *
mailbox_fileno(MailboxObject *self, PyObject *args)
{
if (!PyArg_ParseTuple(args, ":fileno"))
return NULL;
if (self->disconnected)
return err_disconnected("fileno");
return PyLong_FromLong(self->mbox);
}
static PyObject *
mailbox_join(MailboxObject *self, PyObject *args)
{
char *group;
PyObject *result = Py_None;
if (!PyArg_ParseTuple(args, "y:join", &group))
return NULL;
ACQUIRE_MBOX_LOCK(self);
if (self->disconnected)
result = err_disconnected("join");
else {
int err;
Py_BEGIN_ALLOW_THREADS
err = SP_join(self->mbox, group);
Py_END_ALLOW_THREADS
if (err < 0)
result = spread_error(err, self);
}
RELEASE_MBOX_LOCK(self);
Py_XINCREF(result);
return result;
}
static PyObject *
mailbox_leave(MailboxObject *self, PyObject *args)
{
char *group;
PyObject *result = Py_None;
if (!PyArg_ParseTuple(args, "y:leave", &group))
return NULL;
ACQUIRE_MBOX_LOCK(self);
if (self->disconnected)
result = err_disconnected("leave");
else {
int err;
Py_BEGIN_ALLOW_THREADS
err = SP_leave(self->mbox, group);
Py_END_ALLOW_THREADS
if (err < 0)
result = spread_error(err, self);
}
RELEASE_MBOX_LOCK(self);
Py_XINCREF(result);
return result;
}
static PyObject *
mailbox_receive(MailboxObject *self, PyObject *args)
{
/* CAUTION: initializing svc_type is critical. It's not clear from
* the docs, but this is an input as well as an output parameter.
* We didn't initialize it before, and very rarely the DROP_RECV flag
* would end up getting set in it. That in turn has miserable
* consequences, and consequences only visible if a buffer (data or
* group) is too small for the msg being received (so it goes crazy
* at the worst possible times).
*/
service svc_type;
int num_groups, endian, size;
int16 msg_type;
char senderbuffer[MAX_GROUP_NAME];
char groupbuffer[DEFAULT_GROUPS_SIZE][MAX_GROUP_NAME];
char databuffer[DEFAULT_BUFFER_SIZE];
int max_groups = DEFAULT_GROUPS_SIZE;
char (*groups)[MAX_GROUP_NAME] = groupbuffer;
int bufsize = DEFAULT_BUFFER_SIZE;
char *pbuffer = databuffer;
PyObject *sender = NULL, *data = NULL, *msg = NULL;
if (!PyArg_ParseTuple(args, ":receive"))
return NULL;
ACQUIRE_MBOX_LOCK(self);
if (self->disconnected) {
err_disconnected("receive");
goto error;
}
for (;;) {
char *assertmsg = "internal error";
Py_BEGIN_ALLOW_THREADS
svc_type = 0; /* initializing this is critical */
size = SP_receive(self->mbox, &svc_type,
senderbuffer,
max_groups, &num_groups, groups,
&msg_type, &endian,
bufsize, pbuffer);
Py_END_ALLOW_THREADS
if (size >= 0) {
if (num_groups < 0) {
/* This isn't possible unless DROP_RECV is
* passed to SP_receive in svc_type.
*/
assertmsg = "size >= 0 and num_groups < 0";
goto assert_error;
}
if (endian < 0) {
/* This should never be possible. */
assertmsg = "size >= 0 and endian < 0";
goto assert_error;
}
break; /* This is the only normal loop exit. */
}
if (size == BUFFER_TOO_SHORT) {
if (endian >= 0) {
/* This isn't possible unless DROP_RECV is
* passed to SP_receive in svc_type.
*/
assertmsg = "BUFFER_TOO_SHORT and endian >= 0";
goto assert_error;
}
bufsize = - endian;
Py_XDECREF(data);
data = PyBytes_FromStringAndSize(NULL, bufsize);
if (data == NULL)
goto error;
pbuffer = PyBytes_AS_STRING(data);
continue;
}
if (size == GROUPS_TOO_SHORT) {
/* If the data buffer and the group buffer are both
* too small, and DROP_RECV was not specified, then
* Jonathan Stanton said GROUPS_TOO_SHORT is returned.
* If both are too short and DROP_RECV is specified,
* then BUFFER_TOO_SHORT is returned. "Backward
* compatibility" headaches. For simplicity, we only
* deal with one "too short" condition per loop trip.
* When we loop back, SP_receive should tell us
* about the other (if another thread hasn't already
* grabbed the msg).
*/
if (num_groups >= 0) {
/* This shouldn never be possible. */
assertmsg = "GROUPS_TOO_SHORT and num_groups >= 0";
goto assert_error;
}
max_groups = - num_groups;
if (groups != groupbuffer)
free(groups);
groups = malloc(MAX_GROUP_NAME * max_groups);
if (groups == NULL) {
PyErr_NoMemory();
goto error;
}
continue;
}
/* There's a real error we can't deal with (e.g., Spread
* got disconnected).
*/
spread_error(size, self);
goto error;
assert_error:
PyErr_Format(PyExc_AssertionError,
"SP_receive: %s; "
"size=%d svc_type=%d num_groups=%d "
"msg_type=%d endian=%d",
assertmsg,
size, svc_type, num_groups, msg_type, endian);
goto error;
}
/* It's not clear from the SP_receive() man page what all the
possible categories of services types are possible. */
sender = PyBytes_FromString(senderbuffer);
if (sender == NULL)
goto error;
if (Is_regular_mess(svc_type)) {
if (data == NULL) {
data = PyBytes_FromStringAndSize(databuffer, size);
if (data == NULL)
goto error;
}
else if (PyBytes_GET_SIZE(data) != size) {
if (_PyBytes_Resize(&data, size) < 0)
goto error;
}
msg = new_regular_msg(sender, num_groups, groups,
msg_type, endian, data);
}
else if (Is_membership_mess(svc_type)) {
/* XXX Mark transitional messages */
msg = new_membership_msg(svc_type, sender,
num_groups, groups,
pbuffer, size);
}
else {
PyErr_Format(SpreadError,
"unexpected service type: 0x%x", svc_type);
goto error;
}
error:
RELEASE_MBOX_LOCK(self);
if (groups != groupbuffer)
free(groups);
Py_XDECREF(sender);
Py_XDECREF(data);
return msg;
}
const int valid_svc_type = (UNRELIABLE_MESS | RELIABLE_MESS | FIFO_MESS
| CAUSAL_MESS | AGREED_MESS | SAFE_MESS
| SELF_DISCARD);
static PyObject *
mailbox_multicast(MailboxObject *self, PyObject *args)
{
int svc_type, bytes, msg_len;
int msg_type = 0;
char *group, *msg;
PyObject *result = NULL;
if (!PyArg_ParseTuple(args, "iyy#|i:multicast",
&svc_type, &group, &msg, &msg_len, &msg_type))
return NULL;
ACQUIRE_MBOX_LOCK(self);
if (self->disconnected) {
err_disconnected("multicast");
goto Done;
}
/* XXX This doesn't check that svc_type is set to exactly one of
the service types. */
if ((svc_type & valid_svc_type) != svc_type) {
PyErr_SetString(PyExc_ValueError, "invalid service type");
goto Done;;
}
Py_BEGIN_ALLOW_THREADS
bytes = SP_multicast(self->mbox, svc_type, group, (int16)msg_type,
msg_len, msg);
Py_END_ALLOW_THREADS
if (bytes < 0)
result = spread_error(bytes, self);
else
result = PyLong_FromLong(bytes);
Done:
RELEASE_MBOX_LOCK(self);
return result;
}
static PyObject *
mailbox_multigroup_multicast(MailboxObject *self, PyObject *args)
{
int svc_type, bytes, msg_len, group_len;
int msg_type = 0;
PyObject *group_tuple, *temp;
char *msg;
char (*groups)[MAX_GROUP_NAME];
int index;
PyObject *result = NULL;
if (! PyArg_ParseTuple(args, "iO!y#|i:multicast",
&svc_type,
&PyTuple_Type, &group_tuple,
&msg, &msg_len,
&msg_type))
return NULL;
if(! PyTuple_Check(group_tuple)) {
PyErr_SetString(PyExc_TypeError,
"only tuples are allowed for groups");
return NULL;
}
group_len = PyTuple_Size(group_tuple);
if (group_len == 0) {
PyErr_SetString(PyExc_ValueError,
"there must be at least one group in the tuple");
return NULL;
}
groups = malloc(MAX_GROUP_NAME * group_len);
if (groups == NULL) {
PyErr_NoMemory();
return NULL;
}
for (index = 0; index < group_len; index++) {
temp = PyTuple_GetItem(group_tuple, index);
if(! PyBytes_Check(temp)) {
PyErr_SetString(PyExc_TypeError,
"groups must be bytes only");
goto Done;
}
strncpy(groups[index],
PyBytes_AS_STRING(PyTuple_GetItem(group_tuple, index)),
MAX_GROUP_NAME);
}
ACQUIRE_MBOX_LOCK(self);
if (self->disconnected) {
err_disconnected("multigroup_multicast");
goto Done;
}
/* XXX This doesn't check that svc_type is set to exactly one of
the service types. */
if ((svc_type & valid_svc_type) != svc_type) {
PyErr_SetString(PyExc_ValueError, "invalid service type");
goto Done;
}
Py_BEGIN_ALLOW_THREADS
bytes = SP_multigroup_multicast(self->mbox, svc_type, group_len,
(const char (*)[MAX_GROUP_NAME]) groups,
(int16)msg_type, msg_len, msg);
Py_END_ALLOW_THREADS
if (bytes < 0)
result = spread_error(bytes, self);
else
result = PyLong_FromLong(bytes);
Done:
RELEASE_MBOX_LOCK(self);
free(groups);
return result;
}
static PyObject *
mailbox_poll(MailboxObject *self, PyObject *args)
{
int bytes;
PyObject *result = NULL;
if (!PyArg_ParseTuple(args, ":poll"))
return NULL;
ACQUIRE_MBOX_LOCK(self);
if (self->disconnected) {
err_disconnected("poll");
goto Done;
}
Py_BEGIN_ALLOW_THREADS
bytes = SP_poll(self->mbox);
Py_END_ALLOW_THREADS
if (bytes < 0)
result = spread_error(bytes, self);
else
result = PyLong_FromLong(bytes);
Done:
RELEASE_MBOX_LOCK(self);
return result;
}
static PyMethodDef Mailbox_methods[] = {
{"disconnect", (PyCFunction)mailbox_disconnect,METH_VARARGS},
{"fileno", (PyCFunction)mailbox_fileno, METH_VARARGS},
{"join", (PyCFunction)mailbox_join, METH_VARARGS},
{"leave", (PyCFunction)mailbox_leave, METH_VARARGS},
{"multicast", (PyCFunction)mailbox_multicast, METH_VARARGS},
{"multigroup_multicast", (PyCFunction)mailbox_multigroup_multicast, METH_VARARGS},
{"poll", (PyCFunction)mailbox_poll, METH_VARARGS},
{"receive", (PyCFunction)mailbox_receive, METH_VARARGS},
{NULL, NULL} /* sentinel */
};
#define OFF(x) offsetof(MailboxObject, x)
static struct PyMemberDef Mailbox_memberlist[] = {
{"private_group", T_OBJECT, OFF(private_group)},
{NULL}
};
static PyTypeObject Mailbox_Type = {
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
PyVarObject_HEAD_INIT(NULL, 0)
"Mailbox", /* tp_name */
sizeof(MailboxObject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)mailbox_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
Mailbox_methods, /* tp_methods */
Mailbox_memberlist, /* tp_members */
};
static char spread_connect__doc__[] =
"connect(daemon=\"N@localhost\", name=\"\", priority=0, membership=1) -> mbox\n"
"\n"
"All arguments are optional, and can be specified by keyword or position.\n"
"\n"
"Connect to a Spread daemon, via Spread's SP_connect(). Return a Mailbox\n"
"object representing the connection. Communication with Spread on this\n"
"connection is done via invoking methods of the Mailbox object.\n"
"\n"
"'daemon' is the name of the desired Spread daemon. It defaults to\n"
" \"%d@localhost\" % spread.DEFAULT_SPREAD_PORT\n"
"'name' is the desired private name for the connection. It defaults to an\n"
" empty string, in which case Spread generates a unique random name.\n"
"'priority' is an int, default 0, currently unused (see Spread docs).\n"
"'membership' is a Boolean, default 1 (true), determining whether you want\n"
" to receive membership messages on this connection. If your application\n"
" doesn't make mbox.receive() calls, pass 0 to avoid creating an\n"
" unboundedly large queue of unread membership messages.\n"
"\n"
"Upon successful connect, mbox.private_group is the private group name\n"
"Spread assigned to the connection.";
static PyObject *
spread_connect(PyObject *self, PyObject *args, PyObject* kwds)
{
static char *kwlist[] = {"daemon", "name", "priority", "membership",
0};
char *daemon = NULL;
char *name = "";
int priority = 0;
int membership = 1;
MailboxObject *mbox;
mailbox _mbox;
int ret;
char default_daemon[100];
PyObject *group_name = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|yyii:connect", kwlist,
&daemon, &name, &priority,
&membership))
return NULL;
if (daemon == NULL) {
/* XXX Can't use PyOS_snprintf before 2.2.
PyOS_snprintf(default_daemon, sizeof(default_daemon),
"%d@localhost", DEFAULT_SPREAD_PORT);
*/
sprintf(default_daemon, "%d", DEFAULT_SPREAD_PORT);
daemon = default_daemon;
}
/* initialize output buffer for group name */
group_name = PyBytes_FromStringAndSize(NULL, MAX_GROUP_NAME);
if (group_name == NULL)
return NULL;