socket-bridge 33.7 KB
Newer Older
tlavocat's avatar
tlavocat committed
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
#!/usr/bin/env python3
import time
import traceback
import os
import fcntl
import getopt
import json
import queue
import struct
import sys
import socket
import select
from isengard  import consts
from threading import Thread
from threading import Timer
from threading import Lock

HEADER_BUFFER   = 64
SMALL_BUFFER    = 20
MSG_LENGTH      = 1

READ_ACCESS     = 0
WRITE_ACCESS    = 1
GET_INFO_ACCESS = 2
RECV_ACCESS     = 3

TAKTUK_EMAXCD   = 21

TAKTUK_TARGET_ANY    = 0xFFFFFFFF
TAKTUK_TARGET_ALL    = 0xFFFFFFFE
TAKTUK_TARGET_OUTPUT = 0xFFFFFFFD

TAKTUK_READ_SIZE  = 8192
TAKTUK_WRITE_SIZE = 8192

TAKTUK_ACTION="A";
TAKTUK_WAIT="B";
TAKTUK_ID="C";
TAKTUK_EOF="D";
TAKTUK_TAKTUK_PERL="E";
TAKTUK_GATEWAY="F";
TAKTUK_GET="G";
TAKTUK_INVALID="H";
TAKTUK_INFO="I";
TAKTUK_COMMAND_SEND_TO="J";
TAKTUK_COMMAND_MESSAGE="K";
TAKTUK_OPTION="N";
TAKTUK_TIMEOUT="O";
TAKTUK_PUT="P";
TAKTUK_REDUCE_RESULT="Q";
TAKTUK_REDUCE="R";
TAKTUK_SPREAD="S";
TAKTUK_TAKTUK_CODE="T";
TAKTUK_UPDATE_FAILED="U";
TAKTUK_OPTIONS="V";
TAKTUK_WAIT_MESSAGE="W";
TAKTUK_RESIGN="X";
TAKTUK_ARGUMENTS="a";
TAKTUK_BROADCAST="b";
TAKTUK_DOWN="d";
TAKTUK_EXECUTE="e";
TAKTUK_FILE="f";
TAKTUK_GET_INFO="g";
TAKTUK_INPUT="i";
TAKTUK_KILL="k";
TAKTUK_MESSAGE="m";
TAKTUK_NUMBERED="n";
TAKTUK_OUTPUT="o";
TAKTUK_POSITION="p";
TAKTUK_QUIT="q";
TAKTUK_READY="r";
TAKTUK_STEAL="s";
TAKTUK_SEND_TO="t";
TAKTUK_FORWARD_UP="u";
TAKTUK_WORK="w";
TAKTUK_SYNCHRONIZE="x";
TAKTUK_PIPE="z";

# Reduce types
TAKTUK_REDUCE_COUNT = 'c';
TAKTUK_REDUCE_TREE = 't';
TAKTUK_REDUCE_WAIT = 'w';


# Class Bridge
# Author Thomas Lavocat
# 
# Listen on a unix socket on one side and transfert messages to the taktuk
# network, and listen to the taktuk network and transfert the messages to the
# unix socket
class Bridge(Thread):

    # need a valid opened socket
    def __init__(self, controler_socket, debug_list, receive_callback=None):
        Thread.__init__(self)
        self.debug_list = debug_list
        self.debug      = "bridge" in self.debug_list
        #connect to the taktuk network
        self.ind      = int(os.getenv("TAKTUK_CONTROL_READ"))
        self.outd     = int(os.getenv("TAKTUK_CONTROL_WRITE"))
        self.rank     = os.getenv("TAKTUK_RANK")
        self.dead     = False
        #Opened for bytes transactions
        self.file_out = os.fdopen(self.outd, "wb")
        self.file_in  = os.fdopen(self.ind, "rb")
        flag = fcntl.fcntl(self.ind, fcntl.F_GETFL)
        fcntl.fcntl(self.ind, fcntl.F_SETFL, flag | os.O_NONBLOCK)

        self.taktuk_lock = Lock()
        #acquire until thread is started (it wont be long)
        self.taktuk_ready = False
        self.taktuk_lock.acquire()

        self.controler_socket = controler_socket
        self.receive_callback = receive_callback
        if self.controler_socket != None :
            self.flushprint("connected to erebor")
            self.controler_lock  = Lock()
            self.controler_ready = False
            self.controler_lock.acquire()
        self.daemon = True
        self.poll   = True

        self.message_queues = {}
        self.outputs        = []

    def flushprint(self, *args, **kwargs):
        if self.debug :
            print(*args, file=sys.stdout, **kwargs)
            sys.stdout.flush()

    # Write on taktuk every requested datas, this code is taken from C version
    def insistent_write(self, data) :
        size = len(data)
        if self.dead :
            return -1
        if size == 0 :
            return 0
        try :
            while self.poll and (size >0) and not self.dead and self.poll:
                #self.flushprint("write")
                result = self.file_out.write(data)
                if  result <= 0 or result == None:
                    return -1
                size -= result
                data = data [size:]
        except :
            return -1
        self.file_out.flush()
        return 0

    # close the taktuk's file descriptors
    def close(self):
        self.file_out.close()
        self.file_in.close()

    def run(self):
        epoll          = select.epoll()
        if self.controler_socket != None :
            self.out_epoll = select.epoll()
            self.out_epoll.register(self.controler_socket.fileno(), select.EPOLLOUT)
            epoll.register(self.controler_socket.fileno(), select.EPOLLIN)
            self.controler_ready = True
            self.controler_lock.release()
        epoll.register(self.ind, select.EPOLLIN)
        self.taktuk_ready = True
        self.taktuk_lock.release()

        try:
            connections = {};
            while self.poll and not self.dead :
                s_header_m     = None
                s_rest_header  = 0
                s_buffered_m   = None
                s_rest_to_read = 0
                t_header_m     = None
                t_rest_header  = 0
                t_buffered_m   = None
                t_rest_to_read = 0
                events = epoll.poll(consts.timeout)
                #self.flushprint("epolling")
                for fileno, event in events:
                    #self.flushprint("event to handle")
                    if event & select.EPOLLIN:
                        if (self.controler_socket != None and
                            fileno == self.controler_socket.fileno()) :
                            length = 0
                            # if we start a new message
                            if s_buffered_m == None :
                                #self.flushprint("new message")
                                data = bytearray()
                                # if we start a new header
                                if s_header_m == None :
                                    #self.flushprint("new header")
                                    data = self.controler_socket.recv(4)
                                # otherwise complete the previous header
                                else :
                                    data = s_header_m + self.controler_socket.recv(s_rest_header)
                                # If we havent received enough to have a valid
                                # header, wait for the rest to come
                                if len(data) < 4 :
                                    s_header_m    = data
                                    s_rest_header = 4 - len(s_header_m)
                                    length        = -1
                                # Otherwise, lets decode the rest of the message
                                else :
                                    # unpack the packet length
                                    length = struct.unpack_from('>i', data)[0]
                                    #self.flushprint("header complete {}".format(length))
                                    s_header_m = None
                            else :
                                length = s_rest_to_read
                            if length > -1 :
                                # read what we're supposed to
                                data = self.controler_socket.recv(length)
                                #self.flushprint("content read")
                                # if the received message is a full one, handle it,
                                # otherwise, store it for later
                                if len(data) == length :
                                    #self.flushprint("good size ")
                                    if s_buffered_m != None :
                                        data = s_buffered_m + data
                                        s_buffered_m = None
                                    self._handle_message_from_socket(data)
                                else :
                                    s_rest_to_read = length - len(data)
                                    if s_buffered_m == None :
                                        s_buffered_m = data
                                    else :
                                        s_buffered_m = s_buffered_m + data
                        if fileno == self.ind :
                            nbRead         = 0
                            read_something = True
                            error          = False
                            while self.poll and read_something and not error and not self.dead:
                                length       = 0
                                # if we start a new message
                                if t_buffered_m == None :
                                    data = bytearray()
                                    # if we start a new header
                                    if t_header_m == None :
                                        data = self.file_in.read(4)
                                        if data == None :
                                            read_something = False
                                            break
                                        else :
                                            if len(data) == 0 :
                                                read_something = False
                                                error = True
                                                break
                                    # otherwise complete the previous header
                                    else :
                                        temp = self.file_in.read(t_rest_header)
                                        if data == None :
                                            read_something = False
                                            break
                                        else :
                                            if len(data) == 0 :
                                                read_something = False
                                                error = True
                                                break
                                        data = t_header_m + temp
                                    # If we havent received enough to have a valid
                                    # header, wait for the rest to come
                                    if len(data) < 4 :
                                        t_header_m    = data
                                        t_rest_header = 4 - len(t_header_m)
                                        length        = -1
                                    # Otherwise, lets decode the rest of the message
                                    else :
                                        # unpack the packet length
                                        length = struct.unpack_from('>i', data)[0]
                                        t_header_m = None
                                else :
                                    length = t_rest_to_read
                                if length > -1 :
                                    # read what we're supposed to
                                    t_buffered_m = data
                                    data = self.file_in.read(length)
                                    if data == None :
                                        read_something = False
                                        break
                                    else :
                                        if len(data) == 0 :
                                            read_something = False
                                            error = True
                                            break
                                    # if the received message is a full one, handle it,
                                    # otherwise, store it for later
                                    if len(data) == length :
                                        if t_buffered_m != None :
                                            data = t_buffered_m + data
                                            t_buffered_m = None
                                        self.extract_taktuk_message(data)
                                    else :
                                        t_rest_to_read = length - len(data)
                                        if t_buffered_m == None :
                                            t_buffered_m = data
                                        else :
                                            t_buffered_m = t_buffered_m + data
                                if read_something :
                                    nbRead += 1
                            if nbRead == 0 or error :
                                self.bridge_dead()
                    else :
                        self.bridge_dead()
        except Exception as e :
            self.flushprint( "{}".format(e))
            raise
        finally:
            self.bridge_dead()
            self.flushprint("error")

    def bridge_dead(self):
        self.dead = True
        self.poll = False
        self.flushprint("bridge dead")
        toforward   = json.dumps({
            consts.FROM:consts.INTERNAL,
            consts.TYPE:consts.BRIDGED,
            });
        if self.controler_socket != None :
            self.send_message_on_socket(toforward)
        else :
            self.receive_callback(toforward)

    # Extract a message from taktuk and send it to the unix socket as a JSON
    # message TODO
    def extract_taktuk_message(self, to_unpack) :
        #self.flushprint("\n get datas \n")
        # The sent message by taktuk is of the following form
        # code + size in the header
        #   so 4 bytes + 1
        #self.flushprint("try to extract message {}".format(to_unpack))
        offset      = 0
        length      = struct.unpack_from('>I', to_unpack[offset:4])[0]
        offset     += 4
        #self.flushprint("length : {}".format(length))
        body_length = length - MSG_LENGTH
        #self.flushprint("body_length {}".format(body_length))
        code        = struct.unpack_from('s', to_unpack[offset:offset+1])[0]
        offset     += 1
        #self.flushprint("code {}".format(code))
        # FROM TODO
        from_size   = struct.unpack_from('>I', to_unpack[offset:offset+4])[0]
        offset     += 4
        #self.flushprint("from_size {}".format(from_size))
        from_       = struct.unpack_from('s', to_unpack[offset:offset+from_size])[0]
        offset     += from_size
        #self.flushprint("from {}".format(from_))
        # READ final datas
        body_length = body_length-5
        data        = to_unpack[offset:offset+body_length]
        final_data  = data.decode(consts.encoding)
        offset     += body_length
        #self.flushprint("final_data : {}".format(final_data))
        final_code  = code.decode(consts.encoding)
        final_from  = from_.decode(consts.encoding)
        #self.flushprint("body_length {}".format(body_length))
        #self.flushprint("data : {}".format(data))
        #self.flushprint("final_code : {}".format(final_code))
        # build JSON to send
        toforward   = json.dumps({"from":final_from, "type":final_code,
            "data": final_data});
        #self.log_to_father("end decode tofoward {}".format(toforward))
        #self.log_to_father("received message ".format(final_from))
        # send the message to top layer
        if self.controler_socket != None :
            self.send_message_on_socket(toforward)
        else :
            self.receive_callback(toforward)

    def write_on_taktuk(self, packed):
        if not self.taktuk_ready :
            self.taktuk_lock.acquire()
        s = self.file_out
        ret = self.insistent_write(packed)
        return ret

    # data need to be str format assuming utf-8
    # Will be send using
    def send_message_on_socket(self, data):
        if not self.controler_ready :
            self.controler_lock.acquire()
        #self.flushprint(data)
        to_send      = self.pack(data)
        rest_to_send = len(to_send)
        try :
            while self.poll and rest_to_send > 0 and not self.dead :
                events  = self.out_epoll.poll(consts.timeout)
                for fileno, event in events:
                    if event & select.EPOLLOUT :
                        byteswritten = self.controler_socket.send(to_send)
                        if byteswritten < rest_to_send :
                            to_send      = to_send[byteswritten:]
                        rest_to_send = rest_to_send - byteswritten
        except:
            self.bridge_dead()
            self.flushprint("ouch !")
            raise

    # transform string to packed datas
    # data need to be str format assuming utf-8
    def pack(self, data):
        # send the packed data and the packed length
        data = bytes(data,consts.encoding)
        return struct.pack(">i", len(data)) + data

    # close the thread
    def stop_select(self):
        self.poll = False

    # Send a log to the unix socket
    def propagate_taktuk_infos(self) :
        toforward   = json.dumps({
            consts.FROM:consts.INTERNAL,
            consts.TYPE:consts.INFOS,
            consts.RANK:self.rank,
            });
        if self.controler_socket != None :
            self.send_message_on_socket(toforward)
        else :
            self.receive_callback(toforward)

    # Send a log to the unix socket
    def log_to_father(self, data) :
        toforward   = json.dumps({consts.FROM:consts.INTERNAL,
            consts.TYPE:consts.LOG, consts.DATA: data});
        if self.controler_socket != None :
            self.send_message_on_socket(toforward)
        else :
            self.receive_callback(toforward)

    # dest : string
    # target : string
    # command : letter
    # data : string
    # sync_bool : bool
    def taktuk_send_message(self, dest, target, command, data, sync_bool) :
        data = bytes(data, consts.encoding)
        body_length=len(data)
        send_to = TAKTUK_SEND_TO;
        synchro = TAKTUK_SYNCHRONIZE

        # The first four bytes of the header encode its own size not including
        # the four bytes themselves
        #
        send_to = bytes(send_to  ,consts.encoding)
        dest    = bytes(dest     ,consts.encoding)
        command = bytes(command  ,consts.encoding)
        target  = bytes(target   ,consts.encoding)
        rank    = bytes(self.rank,consts.encoding)
        synchro = bytes(synchro  ,consts.encoding)

        #self.flushprint("send header "+str(send_to)+" "+str(rank)+" "+
        #        str(dest)+" "+str(target)+" "+str(body_length)+" "+str(command)
        #        +" "+str(data))

        dest_size        = len(dest)
        target_size      = len(target)
        taktuk_from_size = len(rank)

        # Do not take into account the first four bytes encoding the total size
        # Unfortunately I have to compute size first to allocate my memory if
        # needed ...
        #
        header_size  = consts.UINT32
        header_size += MSG_LENGTH
        header_size += consts.UINT32 + dest_size
        header_size += MSG_LENGTH
        header_size += consts.UINT32 + target_size
        header_size += consts.UINT32 + taktuk_from_size;
        if sync_bool :
            header_size += MSG_LENGTH

        packed  = struct.pack('>I', header_size-consts.UINT32+body_length)
        if sync_bool :
            packed += synchro
        packed += send_to
        packed += struct.pack('>I', dest_size)
        packed += dest
        packed += command
        packed += struct.pack('>I', target_size)
        packed += target
        packed += struct.pack('>I', taktuk_from_size)
        packed += rank
        packed += data

        assert len(packed) == header_size+body_length

        #self.flushprint("need to send all {}".format(packed))
        result = self.write_on_taktuk(packed);
        return result;

    # dest : string
    # command : letter
    # data : string
    # sync_bool : bool
    def taktuk_send_execute(self, dest, command, data, sync_bool) :
        data = bytes(data, consts.encoding)
        body_length=len(data)
        send_to = TAKTUK_SEND_TO;
        synchro = TAKTUK_SYNCHRONIZE

        # The first four bytes of the header encode its own size not including
        # the four bytes themselves
        #
        send_to = bytes(send_to  ,consts.encoding)
        dest    = bytes(dest     ,consts.encoding)
        command = bytes(command  ,consts.encoding)
        synchro = bytes(synchro  ,consts.encoding)

        #self.flushprint("send header "+str(send_to)+" "+str(rank)+" "+
        #        str(dest)+" "+str(target)+" "+str(body_length)+" "+str(command)
        #        +" "+str(data))

        dest_size        = len(dest)

        # Do not take into account the first four bytes encoding the total size
        # Unfortunately I have to compute size first to allocate my memory if
        # needed ...
        #
        header_size  = consts.UINT32
        header_size += MSG_LENGTH
        header_size += consts.UINT32 + dest_size
        header_size += MSG_LENGTH
        if sync_bool :
            header_size += MSG_LENGTH

        packed  = struct.pack('>I', header_size-consts.UINT32+body_length)
        if sync_bool :
            packed += synchro
        packed += send_to
        packed += struct.pack('>I', dest_size)
        packed += dest
        packed += command
        packed += data

        assert len(packed) == header_size+body_length

        #self.flushprint("need to send all {}".format(packed))
        result = self.write_on_taktuk(packed);
        return result;

    # dest : string
    # command : letter
    # option : letter
    # data : string
    # sync_bool : bool
    def taktuk_send_spawn_nodes(self, dest, command, option, data, sync_bool) :
        data = bytes(data, consts.encoding)
        body_length=len(data)
        send_to = TAKTUK_SEND_TO;
        synchro = TAKTUK_SYNCHRONIZE

        # The first four bytes of the header encode its own size not including
        # the four bytes themselves
        #
        send_to = bytes(send_to  ,consts.encoding)
        dest    = bytes(dest     ,consts.encoding)
        command = bytes(command  ,consts.encoding)
        option  = bytes(option  ,consts.encoding)
        synchro = bytes(synchro  ,consts.encoding)

        #self.flushprint("send header "+str(send_to)+" "+str(rank)+" "+
        #        str(dest)+" "+str(target)+" "+str(body_length)+" "+str(command)
        #        +" "+str(data))

        dest_size        = len(dest)

        # Do not take into account the first four bytes encoding the total size
        # Unfortunately I have to compute size first to allocate my memory if
        # needed ...
        #
        header_size  = consts.UINT32
        header_size += MSG_LENGTH
        header_size += consts.UINT32 + dest_size
        header_size += MSG_LENGTH
        header_size += MSG_LENGTH
        if sync_bool :
            header_size += MSG_LENGTH

        packed  = struct.pack('>I', header_size-consts.UINT32+body_length)
        if sync_bool :
            packed += synchro
        packed += send_to
        packed += struct.pack('>I', dest_size)
        packed += dest
        packed += command
        packed += option
        packed += data

        assert len(packed) == header_size+body_length

        #self.flushprint("need to send all {}".format(packed))
        result = self.write_on_taktuk(packed);
        return result;

    # sync_bool : bool
    def taktuk_send_network(self, sync_bool) :
        send_to = TAKTUK_REDUCE
        command = TAKTUK_SEND_TO
        synchro = TAKTUK_SYNCHRONIZE
        # The first four bytes of the header encode its own size not including
        # the four bytes themselves
        #
        send_to = bytes(send_to  ,consts.encoding)
        command = bytes(command  ,consts.encoding)
        synchro = bytes(synchro  ,consts.encoding)

        # Do not take into account the first four bytes encoding the total size
        # Unfortunately I have to compute size first to allocate my memory if
        # needed ...
        #
        header_size  = consts.UINT32
        header_size += MSG_LENGTH
        header_size += MSG_LENGTH
        if sync_bool :
            header_size += MSG_LENGTH

        packed  = struct.pack('>I', header_size-consts.UINT32)
        if sync_bool :
            packed += synchro
        packed += send_to
        packed += command

        assert len(packed) == header_size

        #self.flushprint("need to send all {}".format(packed))
        result = self.write_on_taktuk(packed);
        return result;

    # sync_bool : bool
    def taktuk_send_network_update(self, sync_bool) :
        first_l = TAKTUK_SPREAD
        send_to = TAKTUK_REDUCE
        command = TAKTUK_REDUCE_COUNT
        synchro = TAKTUK_SYNCHRONIZE
        miscp   = "1"
        # The first four bytes of the header encode its own size not including
        # the four bytes themselves
        #
        first_l = bytes(first_l  ,consts.encoding)
        send_to = bytes(send_to  ,consts.encoding)
        command = bytes(command  ,consts.encoding)
        synchro = bytes(synchro  ,consts.encoding)
        miscp   = bytes(miscp    ,consts.encoding)

        # Do not take into account the first four bytes encoding the total size
        # Unfortunately I have to compute size first to allocate my memory if
        # needed ...
        #
        header_size  = consts.UINT32
        header_size += MSG_LENGTH
        header_size += MSG_LENGTH
        header_size += MSG_LENGTH
        if sync_bool :
            header_size += MSG_LENGTH
        header_size += MSG_LENGTH

        packed  = struct.pack('>I', header_size-consts.UINT32)
        if sync_bool :
            packed += synchro
        packed += first_l
        packed += send_to
        packed += command
        packed += miscp

        assert len(packed) == header_size

        #self.flushprint("need to send all {}".format(packed))
        result = self.write_on_taktuk(packed);
        return result;

    # sync_bool : bool
    def taktuk_send_network_renumber(self, sync_bool) :
        first_l = TAKTUK_SPREAD
        send_to = TAKTUK_REDUCE
        command = TAKTUK_REDUCE_COUNT
        synchro = TAKTUK_SYNCHRONIZE
        # The first four bytes of the header encode its own size not including
        # the four bytes themselves
        #
        first_l = bytes(first_l  ,consts.encoding)
        send_to = bytes(send_to  ,consts.encoding)
        command = bytes(command  ,consts.encoding)
        synchro = bytes(synchro  ,consts.encoding)

        # Do not take into account the first four bytes encoding the total size
        # Unfortunately I have to compute size first to allocate my memory if
        # needed ...
        #
        header_size  = consts.UINT32
        header_size += MSG_LENGTH
        header_size += MSG_LENGTH
        header_size += MSG_LENGTH
        if sync_bool :
            header_size += MSG_LENGTH

        packed  = struct.pack('>I', header_size-consts.UINT32)
        if sync_bool :
            packed += synchro
        packed += first_l
        packed += send_to
        packed += command

        assert len(packed) == header_size

        #self.flushprint("need to send all {}".format(packed))
        result = self.write_on_taktuk(packed);
        return result;

    # dest : string
    # command : letter
    # option : letter
    # data : string
    # sync_bool : bool
    # Message to send : xSB1all
    def taktuk_wait_reduce(self, data, sync_bool) :
        data = bytes(data, consts.encoding)
        body_length=len(data)
        synchro = TAKTUK_SYNCHRONIZE
        spread  = TAKTUK_SPREAD
        wait    = TAKTUK_WAIT
        miscp   = "1"

        # The first four bytes of the header encode its own size not including
        # the four bytes themselves
        #
        synchro = bytes(synchro  ,consts.encoding)
        spread  = bytes(spread  ,consts.encoding)
        wait    = bytes(wait     ,consts.encoding)
        miscp   = bytes(miscp    ,consts.encoding)

        # Do not take into account the first four bytes encoding the total size
        # Unfortunately I have to compute size first to allocate my memory if
        # needed ...
        #
        header_size  = consts.UINT32
        if sync_bool :
            header_size += MSG_LENGTH
        header_size += MSG_LENGTH
        header_size += MSG_LENGTH
        header_size += MSG_LENGTH

        packed  = struct.pack('>I', header_size-consts.UINT32+body_length)
        if sync_bool :
            packed += synchro
        packed += spread
        packed += wait
        packed += miscp
        packed += data

        assert len(packed) == header_size+body_length

        #self.flushprint("need to send all {}".format(packed))
        result = self.write_on_taktuk(packed);
        return result;

    # Is called when something comes from the unix socket
    # JSON format is required
    # TODO implement intelligence here
    def _handle_message_from_socket(self, data):
        if self.dead :
            return;
        #self.flushprint("not dead")
        try:
            data = data.decode(consts.encoding)
            json_object = json.loads(data)
        except ValueError :
            #self.flushprint("Gimme valid JSON !")
            self.log_to_father("Gimme valid JSON !")
            return
        #TODO protect against field miss
        #self.flushprint("received {}".format(json.dumps(data)))
        #self.flushprint("decoded")
        # If the message if of the control type, just ignore, its an ack
        if json_object[consts.TYPE] == consts.CONTROL :
            #self.flushprint("control")
            if json_object[consts.VALUE] == consts.ACK :
                #self.flushprint("ack")
                pass
            elif json_object[consts.VALUE] == consts.INVJSON :
                self.flushprint("Ouch, I sent invalid datas")
            elif json_object[consts.VALUE] == consts.INFOS :
                #self.flushprint("value")
                self.propagate_taktuk_infos()
            else :
                self.flushprint("Unknown value {}".format(data))
        else :
            # otherwise, we need to interpret the type of command we are dealing
            # with, TYPE variable must be present.
            type_of_work_to_do = json_object[consts.TYPE]
            synchro            = False
            if consts.SYNCHRO in json_object.keys() :
                synchro = json_object[consts.SYNCHRO] == consts.TRUE
            # Message to send to a node
            dead = False
            if type_of_work_to_do == consts.MESSAGE:
                #self.flushprint("message to send")
                command            = TAKTUK_COMMAND_MESSAGE
                # send the meta message
                dead= self.taktuk_send_message(
                        json_object[consts.DEST],
                        json_object[consts.TARGET],
                        command,
                        json_object[consts.DATA],
                        synchro
                        ) < 0
            # Command to be execute by a node
            elif type_of_work_to_do == consts.EXECUTE:
                #self.flushprint("command to execute")
                command = TAKTUK_EXECUTE
                dead= self.taktuk_send_execute(
                        json_object[consts.DEST],
                        command,
                        json_object[consts.DATA],
                        synchro
                        ) < 0
            # node to be spawned
            elif type_of_work_to_do == consts.SPAWN:
                #self.flushprint("nodes to spawn")
                command = TAKTUK_OPTION
                option  = "m"
                dead= self.taktuk_send_spawn_nodes(
                        json_object[consts.DEST],
                        command,
                        option,
                        json_object[consts.DATA],
                        synchro
                        ) < 0
            # Ask infos on the network
            elif type_of_work_to_do == consts.NETWORK:
                #self.flushprint("network to print")
                dead= self.taktuk_send_network(synchro) < 0
            # Update the numbering
            elif type_of_work_to_do == consts.NUPDATE:
                #self.flushprint("network to update")
                dead= self.taktuk_send_network_update(synchro) < 0
            # renumber the whole network
            elif type_of_work_to_do == consts.NNUMBER:
                #self.flushprint("network to renumber")
                dead= self.taktuk_send_network_renumber(synchro) < 0
            # Wait reduce on
            elif type_of_work_to_do == consts.WAITR:
                #self.flushprint("wait reduce")
                command = TAKTUK_OPTION
                dead= self.taktuk_wait_reduce(
                        json_object[consts.DATA],
                        synchro
                        ) < 0
            else :
                self.log_to_father("error, command not valid")
            if dead :
                self.bridge_dead()

# This program is a broker between taktuk and the main one.
# It exist because to access the taktuk unix socket, a program need to be
# launched by taktuk.
# This one will be asked to be launched by the main one on taktuk.
# The main one will access to the bridge through another unix socket, on the file
# given on parameters
def main(argv):
    sys.stderr = sys.stdout
    try:
        options, argv = getopt.getopt(
                argv[1:],
                "d:s",
                [ "debug=","socket=" ]
                )
    except getopt.GetoptError as message:
        sys.stdout.write("toto")
    #get the name of the controler program
    control_adress = ""
    log=[]
    for option, value in options:
        if option in ["-s", "--socket"]:
            control_adress = value;
        if option in ["-d", "--debug"]:
            if value == "*" :
                log = ["erebor", "network", "isengard", "wrapper",
                "unix_socket", "bridge"]
            else :
                log = value.split(",")

    #connect to the mainpython socket
    controler_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    controler_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    controler_socket.connect(control_adress)
    controler_socket.setblocking(0)
    bridge = Bridge(controler_socket, log)
    bridge.start()
    bridge.log_to_father("control -> {}".format(control_adress))
    bridge.join()

if __name__ == "__main__":
    sys.exit(main(sys.argv))