Source

ginsfsm / ginsfsm / router.py

The default branch has multiple heads

Full commit
   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
# -*- encoding: utf-8 -*-
""" GRouter GObj

.. autoclass:: GRouter
    :members:

"""

"""

GinsFSM forma parte de GObj-Ecosistema, un sistema donde el elemento basico
es un GObj, un objecto cuyo comportamiento esta definido por un automata,
y donde toda la comunicación con el objecto se realiza a traves de eventos.
El GObj define qué eventos de entrada soporta, y que eventos de salida ofrece.
A un GObj puedes enviarle un evento, o subscribirte a sus eventos de salida.

Puedes enviar y subscribir eventos de un GObj que esté en tu mismo thread,
en otros threads o subprocesos de tu aplicación, o en procesos corriendo
en la misma o diferente maquina. Esto incluye también a los browsers.

El transporte de los eventos se realiza mediante el protocolo websocket.
Cada thread o subproceso, representado por el object GAplic,
puede levantar un servicio websocket como
servidor o establecer tantas conexiones cliente como necesite (GRouter)
Se puede configurar un servidor websocket en cualquier puerto.
tambien en el puerto 80 o 443,
en este caso retringido a usar un servidor sockjs integrado
en el framework Pyramid, soportando ademas conexiones de browsers.

Para los GObj corriendo en browsers se usa la libreria sockjs. Esto permite
usar tanto navegadores modernos que soporten websocket, como navegadores
antiguos que no dispongan de websocket.

En el GObj-Ecosistema los threads o suprocesos estan representados por el
objecto GAplic, que además de ser el contenedor de todos los GObj del thread,
y suministrar el event loop, se puede definir con un nombre y uno varios roles.

Puedes configurar una red de gaplics, e intercambiar eventos entre ellos
simplemente conociendo el nombre o role del gaplic, y el nombre del gobj


NEW IDEAS:
Los eventos se garantiza que se entregan al siguiente nodo.
Si se ha podido entregar entonces llega el ack
que provoca que se borre de la cola.
Motivos para que no llege:
    destino desconectado,
    destinatario desconocido en el destino
    cola destinatario llena.

Las tarjetas de presentación son obligatorias si se quiere tener
eventos en sentido contrario, de retorno,
por ejemplo cuando se quiere recibir el return de la acción.

Las tarjetas de presentación no necesitan ack.
En cada conexión automáticamente se enviará la tarjeta de presentación
(solo los clientes: el cliente enviará al servidor conectado su tj.pr.)

Se podría tener un ack de la tr.pr.
que serviría para actualizar, comprobar, ampliar el nombre/roles
que disponemos de ese cliente.
El nombre y roles con que hemos configurado la url de una ruta estática,
no tiene porque coincidir con la que realmente tenga
el dueño de la ruta estática.

Para el sistema de alarmas es importante conocer los nak producidos,
donde se producen y el motivo.
Con esta información se podrán subsanar errores de configuración en el sistema.

Para el sistema de alarmas es importante conocer las desconexiones de las
rutas estáticas.
(CONECTADO/DESCONECTADO)
Con esta información se podrá poner en marcha un sistema de alerta
y comunicación a los afectados, para subsanar lo antes posible el problema.
En este caso, ya no es competencia exclusiva nuestra, sino que pueden
necesitar intervenir agentes externos.

Otro nivel superior de alarmas se puede establecer para informar
de la falta de acuses de recibo a nivel de mensajes de aplicación.
(PROVEEDOR NO CONTESTA)
No sé si se podrá establecer algo genérico para todos.

A nivel de estadísticas, eventos y bytes recibidos y transmitidos por
cada ruta (aparte de los estados de conexión, log activado, etc).

Los eventos podrán tener la propiedad de garantizados:
garantizados por un tiempo: finito o infinito.

Los eventos garantizados se enviarán al role Contenedor de garantizados.
En el Contenedor de garantizados, el estado optimo es todo vacio.
Las alarmas se fijarán en los niveles de llenado del contenedor.
El contenedor se encargará de borrar los eventos caducados e informar al
sistema de alarmas.

El contenedor de garantizados, podrá consultar al registro global de gobjs,
para ver si puede entregar los eventos.

El registro global de gobjs... todos los gaplics deberian registrarse alli.
"""

import datetime
from collections import deque
from ginsfsm.gobj import (
    GObj,
    GObjError,
)
from ginsfsm.c_srv_sock import GServerSock
from ginsfsm.c_connex import GConnex
from ginsfsm.c_timer import GTimer
from ginsfsm.protocols.sockjs.server.c_websocket import GWebSocket
from ginsfsm.protocols.sockjs.server.conn import SockJSConnection
from ginsfsm.protocols.sockjs.server.c_sockjs_server import GSockjsServer
from ginsfsm.utils import (
    get_host_port_from_urls,
    get_path_from_url,
    hexdump,
    random_key,
)
from ginsfsm.protocols.sockjs.server.proto import json_decode


class ExternalSubscription(object):
    """ Container of external subscription.
    """
    def __init__(self, intra_event, route_ref):
        self.event_name = intra_event.event_name
        self.destination_gaplic = intra_event.destination_gaplic
        self.destination_role = intra_event.destination_role
        self.destination_gobj = intra_event.destination_gobj
        self.origin_gaplic = intra_event.origin_gaplic
        self.origin_role = intra_event.origin_role
        self.origin_gobj = intra_event.origin_gobj
        self.route_ref = route_ref
        self.isubscription = None  # reference to internal subscription


class IntraEvent(object):
    """ Container of intra event.
    """
    event_fields = [
        'message_type',
        'serial',
        'event_name',
        'destination_gaplic',
        'destination_role',
        'destination_gobj',
        'origin_gaplic',
        'origin_role',
        'origin_gobj',
        'kw',
    ]
    event_ack_fields = [
        'message_type',
        'serial',
        'event_name',
        'reference',
    ]
    event_nack_fields = [
        'message_type',
        'serial',
        'event_name',
        'error_message',
    ]
    identity_card_fields = [
        'message_type',
        'my_gaplic_name',
        'my_roles',
    ]
    identity_card_ack_fields = [
        'message_type',
        'my_gaplic_name',
        'my_roles',
    ]

    def __init__(
            self,
            message_type=None,
            route_ref=None,
            serial=None,
            event_name=None,
            destination_gaplic=None,
            destination_role=None,
            destination_gobj=None,
            origin_gaplic=None,
            origin_role=None,
            origin_gobj=None,
            my_gaplic_name=None,
            my_roles=None,
            kw=None,
            error_message=None,
            reference=None):
        self.message_type = message_type
        self.route_ref = route_ref
        self.serial = serial
        self.event_name = event_name
        self.destination_gaplic = destination_gaplic
        self.destination_role = destination_role
        self.destination_gobj = destination_gobj
        self.origin_gaplic = origin_gaplic
        self.origin_role = origin_role
        self.origin_gobj = origin_gobj
        self.my_gaplic_name = my_gaplic_name
        self.my_roles = my_roles
        if kw:
            self.kw = kw
        else:
            self.kw = {}
        self.error_message = error_message
        self.reference = reference

    def toJSON(self):
        message_type = self.message_type
        ret = {}
        fn = lambda f: ret.update({f: getattr(self, f)})
        if message_type == '__event__':
            list(map(fn, self.event_fields))
        elif message_type == '__event_ack__':
            list(map(fn, self.event_ack_fields))
        elif message_type == '__event_nack__':
            list(map(fn, self.event_nack_fields))
        elif message_type == '__identity_card__':
            list(map(fn, self.identity_card_fields))
        elif message_type == '__identity_card_ack__':
            list(map(fn, self.identity_card_ack_fields))
        else:
            self.logger.info(
                'ERROR unknown message type %r' % message_type)
        return ret

    def copy(self, new_message_type):
        """ Copy the intra event to new message type
            with only the necessary fields to new type.
        """
        fields = {}
        fn = lambda f: fields.update({f: getattr(self, f)})
        if new_message_type == '__event__':
            list(map(fn, self.event_fields))
        elif new_message_type == '__event_ack__':
            list(map(fn, self.event_ack_fields))
        elif new_message_type == '__event_nack__':
            list(map(fn, self.event_nack_fields))
        elif new_message_type == '__identity_card__':
            list(map(fn, self.identity_card_fields))
        elif new_message_type == '__identity_card_ack__':
            list(map(fn, self.identity_card_ack_fields))
        else:
            self.logger.info(
                'ERROR unknown message type %r' % new_message_type)
        fields.update({'message_type': new_message_type})
        new = IntraEvent(**fields)
        return new

    def __repr__(self):
        return "%r" % self.toJSON()


class StaticRoute(object):
    """ Static route (when we are clients)
    """
    def __init__(self, name, roles, urls, connex):
        self.gaplic_name = name
        if isinstance(roles, (list, tuple,)):
            self.roles = roles
        elif roles:
            self.roles = [roles]
        else:
            self.roles = []
        if isinstance(urls, (list, tuple)):
            self.urls = urls
        else:
            self.urls = [urls]
        if not self.urls:
            raise ValueError(
                'StaticRoute needs urls'
            )

        connex.route = self
        self.connex = connex
        self.idx_url = 0        # current url connection if client
        self.dl_output_events = deque()  # queue of pending output events
        self.cur_pending_event = None
        self.write = None
        self.route_ref = hash(connex)
        self.identity_ack = False
        self.serial = 0
        self.ws = None
        self.their_roles = None  # their roles anwered in identity ack (with *)

    def incr_serial(self):
        self.serial += 1
        if self.serial > 10:
            self.serial = 1
        return self.serial

    def __str__(self):
        return "%s %s" % (self.gaplic_name, self.route_ref)

    def __repr__(self):
        return "\nSTATIC ROUTE:\n  gaplic_name: %s\n  roles: %s\n  " \
            "route_ref: %s\n  connex: %s\n  their_roles: %s\n" % (
                self.gaplic_name,
                self.roles,
                self.route_ref,
                self.connex.config.destinations,
                self.their_roles,
            )


class DynamicRoute(object):
    """ Dynamic route (when we are servers)
    """
    def __init__(self, name, roles, write, gsock):
        self.gaplic_name = name
        self.roles = roles
        if isinstance(roles, (list, tuple,)):
            self.roles = roles
        elif roles:
            self.roles = [roles]
        else:
            self.roles = []
        self.dl_output_events = deque()  # queue of pending output events
        self.cur_pending_event = None
        self.connex = None
        self.write = write
        self.gsock = gsock
        self.route_ref = hash(gsock)
        self.identity_ack = True
        self.serial = 0
        self.ws = None
        self.their_roles = None  # their roles anwered in identity (with ^)

    def incr_serial(self):
        self.serial += 1
        if self.serial > 10:
            self.serial = 1
        return self.serial

    def __str__(self):
        return "%s %s" % (self.gaplic_name, self.route_ref)

    def __repr__(self):
        return "\DINAMYC ROUTE:\n  gaplic_name: %s\n  roles: %s\n  " \
            "route_ref: %s\n  gsock: %r\n  their_roles: %r\n" % (
                self.gaplic_name,
                self.roles,
                self.route_ref,
                self.gsock,
                self.their_roles,
            )


class EmptyRoute(object):
    """ Empty route
    """
    def __init__(self):
        self.route_ref = None
        self.identity_ack = False

    def __str__(self):
        return "%s" % (self.route_ref)

    def __repr__(self):
        return "\EMPTY ROUTE:\n  route_ref: %s\n" % (
            self.route_ref,
        )


class GAplicRegistry(object):
    """ GAplics registry.
    """
    def __init__(self, router):
        self.router = router
        self.my_gaplic_name = router.gaplic.name  # self gaplic name
        self.my_roles = router.gaplic.roles  # self role
        self.static_routes = {}
        self.dynamic_routes = {}
        self.broadcasted_roles = []

    def add_static_route(self, name, roles, urls, connex_mode=None):
        if not isinstance(urls, (list, tuple)):
            urls = [urls]
        destinations = get_host_port_from_urls(urls)
        if not destinations:
            return None
        connex = self.router.create_gobj(
            'static_route',
            GConnex,
            self.router,
            transmit_ready_event_name=None,
            destinations=destinations,
        )
        r = StaticRoute(name, roles, urls, connex)
        self.static_routes[r.route_ref] = r
        return r

    def add_dynamic_route(self, name, role, write, gsock):
        if not name:
            # anonymous gaplic name
            name = "^%s%s" % (gsock.get_peername(), gsock.get_sockname())
        r = DynamicRoute(name, role, write, gsock)
        self.dynamic_routes[r.route_ref] = r
        return r

    def get_route_by_ref(self, route_ref):
        route = self.static_routes.get(route_ref, None)
        if not route:
            route = self.dynamic_routes.get(route_ref, None)
        return route

    def search_route(self, gaplic_name, role):
        registry = self

        #------------------------------#
        #   Search by gaplic_name
        #------------------------------#

        # search in static routes
        static_routes = registry.static_routes
        for route_ref in static_routes:
            route = static_routes[route_ref]
            if route.gaplic_name == gaplic_name:
                return route

        # search in dynamic routes
        dynamic_routes = registry.dynamic_routes
        for route_ref in dynamic_routes:
            route = dynamic_routes[route_ref]
            if route.gsock.is_disconnected():
                continue
            if route.gaplic_name == gaplic_name:
                return route

        #------------------------------#
        #   Search by role
        #------------------------------#

        # search in static routes
        static_routes = registry.static_routes
        for route_ref in static_routes:
            route = static_routes[route_ref]
            roles = route.roles
            for ro in roles:
                if ro == role:
                    return route

        # search in dynamic routes
        dynamic_routes = registry.dynamic_routes
        for route_ref in dynamic_routes:
            route = dynamic_routes[route_ref]
            if route.gsock.is_disconnected():
                continue
            roles = route.roles
            # TODO: busca el rol conectado si hay varios
            for ro in roles:
                ro = ro.lstrip('^')  # TODO: search removing ^ one to one
                if ro == role:
                    return route

        return None

    def enqueue_pending_event(self, route, intra_event):
        dl_output_events = route.dl_output_events
        ln = len(dl_output_events)
        if ln > self.router.config.limit_pending_output:
            self.router.logger.error("ERROR output event queue FULL: %d" % ln)
            self.check_route(route)
            return False
        dl_output_events.append(intra_event)
        return True

    def check_route(self, route):
        if isinstance(route, DynamicRoute):
            if route.gsock.is_closed() or route.gsock.is_disconnected():
                self.delete_route(route.route_ref)

    def delete_route(self, route_ref):
        key = route_ref
        dicc = self.dynamic_routes
        if key in dicc:
            self.router.logger.info("DELETING dynamic ROUTER %r" % (key))
            route = dicc[key]
            if route.ws:
                GObj.destroy_gobj(route.ws)
                route.ws = None
            del dicc[key]
            return True
        dicc = self.static_routes
        if key in dicc:
            self.router.logger.info("DELETING static ROUTER %r" % (key))
            route = dicc[key]
            if route.ws:
                GObj.destroy_gobj(route.ws)
                route.ws = None
            del dicc[key]
            return True
        return False

    def fire_pending_events(self, route):
        if not route.route_ref:
            return
        write = route.write
        trace_router = self.router.config.trace_router

        if not write:
            if trace_router:
                self.router.logger.info("    * route DISCONNECTED!!")
            return False

        if not route.identity_ack:
            # TODO: improve sending identity card with timeouts
            self.router.send_identity_card(route)
            return

        if route.cur_pending_event:
            try:
                msg = route.cur_pending_event.toJSON()
            except Exception as e:
                self.router.logger.exception(e)
                route.cur_pending_event = None  # trash message
                return False
            if trace_router:
                prefix = '%s ==> %s' % (
                    self.my_gaplic_name, route)
                self.router.trace_intra_event(prefix, route.cur_pending_event)
            write(msg)
            return True

        dl_output_events = route.dl_output_events
        if len(dl_output_events) > 0:
            route.cur_pending_event = dl_output_events.popleft()
            try:
                msg = route.cur_pending_event.toJSON()
            except Exception as e:
                self.router.logger.exception(e)
                route.cur_pending_event = None  # trash message
                return False
            if trace_router:
                prefix = '%s ==> %s' % (
                    self.my_gaplic_name, route)
                self.router.trace_intra_event(prefix, route.cur_pending_event)
            write(msg)
            return True
        return False

    def subcontracted_roles(self):
        """ Roles of static routes are our subcontracted roles
        """
        registry = self
        found_roles = set()

        # search in static routes
        static_routes = registry.static_routes
        for route_ref in static_routes:
            route = static_routes[route_ref]
            for ro in route.roles:
                found_roles.add(ro)

        found_roles = list(found_roles)
        return tuple(map(lambda x: '*' + x, found_roles))

    def get_roles_back_way(self):
        registry = self
        found_roles = set()

        # search in dynamic routes
        dynamic_routes = registry.dynamic_routes
        for route_ref in dynamic_routes:
            route = dynamic_routes[route_ref]
            if route.gsock.is_disconnected():
                continue
            roles = route.roles
            for ro in roles:
                found_roles.add(ro)
        found_roles = list(found_roles)
        return tuple(map(lambda x: '^' + x, found_roles))

    def check_broadcast_roles_back_way(self, roles):
        #broadcasted_roles = self.broadcasted_roles  # TODO: must be per route
        broadcasted_roles = []
        to_broadcast = []

        pure_roles = list(
            map(lambda x: x.lstrip('^'), roles)
        )

        for idx, ro in enumerate(pure_roles):
            if ro in self.my_roles:
                continue  # avoid loops
            if not ro in broadcasted_roles:
                to_broadcast.append('^' + roles[idx])
                broadcasted_roles.append(ro)

        if to_broadcast:
            self.broadcast_role_back_way(to_broadcast)

    def broadcast_role_back_way(self, roles_back_way):
        registry = self
        if self.router.config.trace_router:
            self.router.logger.info("BROAD BACK WAY ====> %r" % roles_back_way)
        # search in static routes
        static_routes = registry.static_routes
        for route_ref in static_routes:
            route = static_routes[route_ref]
            if route.connex.is_disconnected():
                continue
            self.router.send_identity_card(route, roles_back_way)

    def role_level(self, role):
        role = role.strip()
        level = 0
        for level, char in enumerate(role):
            if not role[level] in ('^', '*'):
                break
        return level, role[level:]


class RouterConnection(SockJSConnection):
    """ Websocket application to work with Pyramid router.

    The messages come by here when the router server is a Pyramid web server.
    """
    clients = set()

    def on_open(self, info):
        session = self.session
        if session:
            session.write = session.send_message
            session.gsock = session.handler.gsock

    def on_message(self, msg):
        session = self.session
        router = session.gaplic.router
        try:
            msg = json_decode(msg)
        except Exception as e:
            router.logger.exception("ERROR %s:\n%s" % (e, hexdump('<==', msg)))
            return
        router.send_event(
            router,
            'EV_INPUT_MESSAGE',
            msg=msg,
            session=session,
        )

    def on_close(self):
        session = self.session
        router = session.gaplic.router
        route = session.route
        if route:
            router.registry.delete_route(route.route_ref)
        else:
            pass  # TODO: delete gsock or channel


def get_first_name(name):
    if '^' in name:
        name = name.split()[0]
    return name


def ac_connected(self, event):
    """ Someone is connected.
    By here we receive the connection of both client and server routers
    that are not pyramid routes.
    The GWebSocket gobj will take possession of all their events.
    """
    gsock = event.gsock
    source_gobj = event.source[-1]
    if hasattr(event, 'connex'):
        # client connection
        connex = event.connex
        route_ref = hash(connex)
        route = self.registry.get_route_by_ref(route_ref)
        # all urls must have the same path!!
        resource = get_path_from_url(route.urls[0])
        if not resource:
            resource = '/'
        ws = self.create_gobj(
            'websock_cli-' + source_gobj.name,
            GWebSocket,
            self,
            gsock=connex,
            iam_server=False,
            subscriber=self,
            resource=resource,
        )
        ws.route_ref = route_ref
        ws.route = route
        route.ws = ws
        route.write = ws.send_jsonfied_message

    else:
        # clisrv connection
        ws = self.create_gobj(
            'websock_srv-' + source_gobj.name,
            GWebSocket,
            self,
            gsock=gsock,
            iam_server=True,
            subscriber=self,
        )
        ws.route_ref = None
        ws.route = None


def ac_disconnected(self, event):
    """
    """


def ac_add_static_route(self, event):
    """ Add external gaplic.
    """
    name = event.kw.get('name', None)
    roles = event.kw.get('roles', '')
    urls = event.urls
    connex_mode = event.kw.get('connex_mode', None)

    route = self.registry.add_static_route(name, roles, urls, connex_mode)
    if not route:
        return -1
    if self.config.trace_router:
        self.logger.info("%s: NEW STATIC route: %r" % (
            self.registry.my_gaplic_name,
            route
        ))
    return route.route_ref


def ac_on_open(self, event):
    """
    By here we receive from both client and server routers
    that are not pyramid routes.
    """
    ws = event.source[-1]
    ws.write = ws.send_jsonfied_message

    # send our identity card if iam client
    # we only send the identity card in static routes!
    if not ws.config.iam_server:
        self.send_identity_card(ws.route)


def ac_on_close(self, event):
    """
    By here we receive from both client and server routers
    that are not pyramid routes.
    """
    ws = event.source[-1]
    route = ws.route
    if isinstance(route, DynamicRoute):
        self.registry.delete_route(route.route_ref)


def ac_on_message(self, event):
    """
    By here we receive from both client and server routers
    that are not pyramid routes.
    """
    ws = event.source[-1]
    msg = event.data

    try:
        msg = json_decode(msg)
    except Exception as e:
        self.logger.exception(
            "ERROR json_decode %s:\n%s" % (e, hexdump('<==', msg)),
        )
        return
    self.send_event(
        self,
        'EV_INPUT_MESSAGE',
        msg=msg,
        websocket=ws,
    )


def ac_input_message(self, event):
    """ Event attributes:
        * :attr:`msg`: received message.
    """
    registry = self.registry
    msg = event.msg
    try:
        intra_event = IntraEvent(**msg)
    except Exception as e:
        self.logger.error(
            "ERROR %s:\n%s" % (e, hexdump('<==', msg)),
            exc_info=True,
        )
        return
        raise
    message_type = intra_event.message_type
    trace_router = self.config.trace_router
    this_route = EmptyRoute()
    session = event.kw.get('session', None)  # entry by pyramid
    websocket = event.kw.get('websocket', None)  # entry by direct websocket
    if session:
        write = session.write
        gsock = session.gsock
        if hasattr(session, 'route'):
            if session.route:
                this_route = session.route
    elif websocket:
        write = websocket.write
        gsock = websocket.gsock
        if websocket.route:
            this_route = websocket.route

    if trace_router:
        prefix = '%s <== %s' % (
            registry.my_gaplic_name,
            this_route,
        )
        self.trace_intra_event(prefix, intra_event)

    if message_type == '__identity_card__':
        # Register a dynamic router
        gaplic_name = intra_event.my_gaplic_name
        roles = intra_event.my_roles
        if isinstance(this_route, EmptyRoute):
            # new dynamic route
            case = 'NEW'
            this_route = registry.add_dynamic_route(
                gaplic_name,
                roles,
                write,
                gsock,
            )
            if session:
                session.route = this_route
            elif websocket:
                websocket.route = this_route
                this_route.ws = websocket
            else:
                self.logger.error("ERROR no session neither websocket")
        else:
            # update dynamic route
            case = 'UPDATE'
            this_route.roles = roles  # TODO: check roles?

        if self.config.trace_router:
            self.logger.info("%s: %s DYNAMIC route: %s: %s: %s: %s" % (
                registry.my_gaplic_name,
                case,
                this_route.route_ref,
                this_route.gaplic_name,
                this_route.roles,
                gsock.addr))

        ack = IntraEvent(
            message_type='__identity_card_ack__',
            my_gaplic_name=registry.my_gaplic_name,
            my_roles=registry.my_roles + registry.subcontracted_roles(),
        )
        if trace_router:
            prefix = '%s ==> %s' % (
                registry.my_gaplic_name, this_route)
            self.trace_intra_event(prefix, ack)
        write(ack.toJSON())

        #
        #   Broadcast forward the new role's back ways.
        #
        registry.check_broadcast_roles_back_way(this_route.roles)
        return

    elif message_type == '__identity_card_ack__':
        # TODO: check if the info we have is correct
        this_route.identity_ack = True
        if intra_event.my_gaplic_name:
            if this_route.gaplic_name != intra_event.my_gaplic_name:
                self.logger.info(
                    "WARNING: updating route %r, GAPLIC_NAME! to %r" % (
                    this_route.route_ref,
                    intra_event.my_gaplic_name))
                this_route.gaplic_name = intra_event.my_gaplic_name

        # check their roles
        for r in intra_event.my_roles:
            if not r in this_route.roles:
                if self.config.update_unknown_roles:
                    self.logger.warn(
                        "WARNING: updating route %r, adding ROLE %r" % (
                        this_route.route_ref,
                        r))
                    this_route.roles.append(r)

        # check if our subcontracted roles are all
        for r in this_route.roles:
            pure_roles = list(
                map(lambda x: x.lstrip('*'), intra_event.my_roles)
            )
            if not r in pure_roles:
                self.logger.error(
                    "ERROR: %r LACKS role %r, it has only %r" % (
                    this_route,
                    r,
                    intra_event.my_roles))
        this_route.their_roles = intra_event.my_roles[:]

        if self.config.trace_router:
            self.logger.info("%s: UPDATE STATIC route: %r" % (
                self.registry.my_gaplic_name,
                this_route
            ))

        registry.fire_pending_events(this_route)
        return

    elif message_type == '__event_ack__' or message_type == '__event_nack__':
        if this_route.route_ref:
            cur_pending_event = this_route.cur_pending_event
            if not cur_pending_event:
                self.logger.error("ERROR processing ack: NO cur_pending_event")

            if cur_pending_event and \
                    intra_event.serial != cur_pending_event.serial:
                self.logger.error("ERROR processing ack: DIFFERENT SERIAL")

            del this_route.cur_pending_event
            this_route.cur_pending_event = None
            registry.fire_pending_events(this_route)
        return

    elif message_type == '__event__':
        #--------------------------------------------------#
        #   It's an event. Search if for us or to resend
        #--------------------------------------------------#
        own = False

        if isinstance(this_route, DynamicRoute):
            if not intra_event.origin_gaplic:
                #  Set our extended gaplic name
                intra_event.origin_gaplic = this_route.gaplic_name

        # search by gaplic
        if intra_event.destination_gaplic and registry.my_gaplic_name:
            first_gaplic_name = get_first_name(intra_event.destination_gaplic)
            if first_gaplic_name == registry.my_gaplic_name:
                own = True

        # search by role
        if intra_event.destination_role and registry.my_roles:
            if intra_event.destination_role in registry.my_roles:
                own = True

        if own:
            #------------------------------------#
            #   The event is for own gaplic.
            #------------------------------------#
            dst_gobj = intra_event.destination_gobj
            try:
                named_gobj = self.gaplic.find_unique_gobj(dst_gobj)
            except GObjError as e:
                ack = intra_event.copy('__event_nack__')
                ack.error_message = e
                if trace_router:
                    prefix = '%s ==> %s' % (
                        registry.my_gaplic_name, this_route)
                    self.trace_intra_event(prefix, ack)
                write(ack.toJSON())
                return

            if not named_gobj:
                ack = intra_event.copy('__event_nack__')
                ack.error_message = "GObj %r UNKNOWN" % dst_gobj
                if trace_router:
                    prefix = '%s ==> %s' % (
                        registry.my_gaplic_name, this_route)
                    self.trace_intra_event(prefix, ack)
                write(ack.toJSON())
                return

            if trace_router:
                self.logger.info("   !!! IntraEvent MINE !!!")

            if intra_event.kw.get('__subscribe_event__', False):
                # it's a external subscription
                external_subscriptor_ref = self.make_external_subscription(
                    intra_event,
                    this_route.route_ref
                )
                if not external_subscriptor_ref:
                    ack = intra_event.copy('__event_nack__')
                    ack.error_message = "Cannot make external subscription"
                    if trace_router:
                        prefix = '%s ==> %s' % (
                            registry.my_gaplic_name, this_route)
                        self.trace_intra_event(prefix, ack)
                    write(ack.toJSON())
                    return

                subs_kw = {
                    '__rename_event_name__': 'EV_SUBSCRIPTION',
                    '__subscription_reference__': external_subscriptor_ref,
                }
                try:
                    isubscription = named_gobj.subscribe_event(
                        intra_event.event_name,
                        self,
                        **subs_kw
                    )
                except Exception as e:
                    self.remove_external_subscription(external_subscriptor_ref)
                    ack = intra_event.copy('__event_nack__')
                    ack.error_message = "Cannot subscribe event: " + e
                    if trace_router:
                        prefix = '%s ==> %s' % (
                            registry.my_gaplic_name, this_route)
                        self.trace_intra_event(prefix, ack)
                    write(ack.toJSON())
                    return
                esubscription = self.get_external_subscription(
                    external_subscriptor_ref)
                esubscription.isubscription = isubscription

                # simple ack, no checkout, for the sender could remove the msg.
                ack = intra_event.copy('__event_ack__')
                ack.reference = external_subscriptor_ref
                if trace_router:
                    prefix = '%s ==> %s' % (
                        registry.my_gaplic_name, this_route)
                    self.trace_intra_event(prefix, ack)
                write(ack.toJSON())
                return

            if intra_event.kw.get('__unsubscribe_event__', False):
                # it's a external unsubscription
                subscription_reference = intra_event.kw.get(
                    '__subscription_reference__', None)

                if subscription_reference:
                    self.remove_external_subscription(subscription_reference)
                else:
                    # TODO: find and delete external subscription
                    self.logger.error("ERROR no __subscription_reference__")

                # simple ack, no checkout, for the sender could remove the msg.
                ack = intra_event.copy('__event_ack__')
                if trace_router:
                    prefix = '%s ==> %s' % (
                        registry.my_gaplic_name, this_route)
                    self.trace_intra_event(prefix, ack)
                write(ack.toJSON())
                return

            # simple ack, no checkout, for the sender could remove the msg.
            ack = intra_event.copy('__event_ack__')
            if trace_router:
                prefix = '%s ==> %s' % (
                    registry.my_gaplic_name, this_route)
                self.trace_intra_event(prefix, ack)
            write(ack.toJSON())

            # inject the event in the gaplic
            ret = self.send_event(
                named_gobj,
                intra_event.event_name,
                __intra_event__=intra_event,
                **intra_event.kw
            )

            # send action resp as event if they subscribe it.
            if intra_event.kw.get('__subscribe_response__', False):
                resp = IntraEvent(
                    message_type='__event__',
                    route_ref=None,
                    serial=this_route.incr_serial(),
                    event_name=intra_event.event_name,
                    destination_gaplic=intra_event.origin_gaplic,
                    destination_gobj=intra_event.origin_gobj,
                    origin_gaplic=registry.my_gaplic_name,
                    origin_gobj=named_gobj.name,
                    kw={
                        'action_return': ret,
                    }
                )

                registry.enqueue_pending_event(
                    this_route,
                    resp,
                )
                if not this_route.cur_pending_event:
                    registry.fire_pending_events(this_route)

            return

        #-------------------------------------------#
        #       The event is for resend.
        #       Search in routes.
        #-------------------------------------------#
        route_dst = registry.search_route(
            intra_event.destination_gaplic,
            intra_event.destination_role)

        if not route_dst:
            # nothing found
            ack = intra_event.copy('__event_nack__')
            ack.error_message = "Destination gaplic %r or role % r" \
                " NOT FOUND" % (
                    intra_event.destination_gaplic,
                    intra_event.destination_role
                )
            if trace_router:
                prefix = '%s ==> %s' % (
                    registry.my_gaplic_name, this_route)
                self.trace_intra_event(prefix, ack)
            write(ack.toJSON())
            return

        if trace_router:
            self.logger.info("    * IntraEvent FORWARD!!")

        if not route_dst.write:
            # nothing found
            ack = intra_event.copy('__event_nack__')
            ack.error_message = "Route found but DISCONNECTED"
            if trace_router:
                prefix = '%s ==> %s' % (
                    registry.my_gaplic_name, this_route)
                self.trace_intra_event(prefix, ack)
            write(ack.toJSON())
            return

        # enqueue the action response event
        ret = registry.enqueue_pending_event(
            route_dst,
            intra_event,
        )
        # simple ack, no checkout, for the sender could remove the msg.
        if ret:
            ack = intra_event.copy('__event_ack__')
        else:
            ack = intra_event.copy('__event_nack__')
            if trace_router:
                self.logger.info("    * event queue FULL!!")
            ack.error_message = "route_dst event queue FULL"
        if trace_router:
            prefix = '%s ==> %s' % (
                registry.my_gaplic_name, this_route)
            self.trace_intra_event(prefix, ack)
        write(ack.toJSON())

        if not route_dst.cur_pending_event:
            registry.fire_pending_events(route_dst)
        else:
            if ret:
                if trace_router:
                    self.logger.info("    * route_dst BUSY!!")

    else:
        self.logger.error("=================================================")
        self.logger.error("ERROR message_type UNKNOWN: %r" % message_type)


def ac_timeout(self, event):
    something_todo = self.check_routes()
    if something_todo:
        self.set_timeout(self.config.timeout_idle)


def ac_show_routes(self, event):
    ret = self.mt_show_routes()
    return ret


def ac_command(self, event):
    command = event.command
    ret = self.mt_execute_command(command)
    return ret


def ac_subscription(self, event):
    subscription_reference = event.__subscription_reference__
    subscription = self.external_subscriptions.get(
        subscription_reference, None)
    if subscription:
        self._send_event_to_external_route(
            subscription.route_ref,
            subscription.origin_gaplic,
            subscription.origin_role,
            subscription.origin_gobj,
            subscription.event_name,
            subscription.destination_gobj,
            event.kw)


def ac_send_event_outside(self, event):
    gaplic_name = event.gaplic_name
    role = event.role
    gobj_name = event.gobj_name
    event_name_ = event.event_name_
    subscriber_gobj = event.subscriber_gobj
    origin_role = event.origin_role
    kw = event.kw

    registry = self.registry
    route = registry.search_route(gaplic_name, role)
    if not route:
        self.logger.error(
            "ERROR ac_send_event_outside() "
            "route NOT FOUND: %r %r" % (gaplic_name, role))
        return False

    intra_event = IntraEvent(
        message_type='__event__',
        serial=route.incr_serial(),
        event_name=event_name_,
        destination_gaplic=gaplic_name,
        destination_role=role,
        destination_gobj=gobj_name,
        origin_gaplic=registry.my_gaplic_name,
        origin_role=origin_role if origin_role else registry.my_roles[0],
        origin_gobj=subscriber_gobj,
        kw=kw)

    registry.enqueue_pending_event(route, intra_event)
    if not route.cur_pending_event:
        registry.fire_pending_events(route)
    return True


GROUTER_FSM = {
    'event_list': (
        'EV_ADD_STATIC_ROUTE: top input',
        'EV_COMMAND: top input',
        'EV_SHOW_ROUTES: top input',
        'EV_CONNECTED: bottom input',
        'EV_DISCONNECTED: bottom input',
        'EV_ON_OPEN: bottom input',
        'EV_ON_CLOSE: bottom input',
        'EV_ON_MESSAGE: bottom input',
        'EV_INPUT_MESSAGE: bottom input',
        'EV_TIMEOUT: bottom input',
        'EV_SUBSCRIPTION: bottom input',
        'EV_SEND_EVENT_OUTSIDE: top output',
    ),
    'state_list': ('ST_IDLE',),
    'machine': {
        'ST_IDLE':
        (
            ('EV_COMMAND',              ac_command,             None),
            ('EV_SHOW_ROUTES',          ac_show_routes,         None),
            ('EV_ADD_STATIC_ROUTE',     ac_add_static_route,    None),
            ('EV_CONNECTED',            ac_connected,           None),
            ('EV_DISCONNECTED',         ac_disconnected,        None),
            ('EV_ON_OPEN',              ac_on_open,             None),
            ('EV_ON_CLOSE',             ac_on_close,            None),
            ('EV_ON_MESSAGE',           ac_on_message,          None),
            ('EV_INPUT_MESSAGE',        ac_input_message,       None),
            ('EV_TIMEOUT',              ac_timeout,             None),
            ('EV_SUBSCRIPTION',         ac_subscription,        None),
            ('EV_SEND_EVENT_OUTSIDE',   ac_send_event_outside,  None),
        ),
    }
}


def validate_static_routes(value):
    """
    sca1, sca+sca, http://localhost:8002+http://localhost:8002;
    sca2, sca+sca, http://localhost:8003+http://localhost:8003;

    must convert in:

    ((
        'sca1',
        ('sca','sca'),
        ('http://localhost:8002', 'http://localhost:8002'),
    ),
    (
        'sca2',
        ('sca','sca'),
        ('http://localhost:8003', 'http://localhost:8003'),
    ))

    """
    routes = []
    if value:
        # save each route separated by ;
        value = value.split(';')
        for r in value:
            r = r.strip()
            if r:
                routes.append(r)

        # split each route by ,
        for idx, r in enumerate(routes):
            items = r.split(',')
            v = []
            for it in items:
                it = it.strip()
                if it:
                    v.append(it)
            routes[idx] = v

        for r in routes:
            for idx, field in enumerate(r):
                v = ()
                if not '+' in field:
                    v += (field,)
                    continue
                items = field.split('+')
                for e in items:
                    e = e.strip()
                    if e:
                        v += (e,)
                r[idx] = v

    return routes


GROUTER_GCONFIG = {
    #TODO: dns router with a short range ports?
    'server': [
        bool, False, 0, None,
        'Server router. Any gaplic with public services must be server'
    ],
    'localhost_route_ports': [
        tuple, range(2690, 2700), 0, None,
        'List of posible listening ports acting as localhost tcp router server'
    ],
    'pyramid_router_url': [
        str, '__pyramid_router__', 0, None,
        'pyramid url to start the router'
    ],
    'pyramid_root': [None, None, 0, None, 'pyramid root (parent)'],
    'trace_router': [bool, False, 0, None, "trace route messages"],
    'limit_pending_output': [int, 2, 0, None, "output queue size"],
    'timeout_idle': [int, 5, 0, None, "idle timeout"],
    'static_routes': [
        tuple, None, 0, validate_static_routes,
        'static routes with format:'
        'name, role1+role2, url1+url2; name2, role2, url2; ...'
    ],
    'update_unknown_roles': [bool, False, 0, None, "update unknown roles"],
}


class GRouter(GObj):
    """  GRouter GObj.
    Exchange events between GAplic's of same or different hosts.
    This gobj is permanent and direct child of his GAplic.

    The GRouter have two options:

    * open an own listening port,
    * use a url in a http server environment.

    The first option only works with a pure websocket channel.
    The second option needs an application done with Pyramid framework
    and implements sockjs-protocol.

    .. ginsfsm::
       :fsm: GROUTER_FSM
       :gconfig: GROUTER_GCONFIG

    *Input-Events:*
        * :attr:`'EV_TIMEOUT'`: Timer over.
            Start the machine.

        * :attr:`'EV_CONNECTED'`: New client.

        * :attr:`'EV_DISCONNECTED'`: Client disconnected.

    *Output-Events:*

    """
    def __init__(self):
        GObj.__init__(self, GROUTER_FSM, GROUTER_GCONFIG)
        self.server_sock = None  # server sock of tcp router
        self.local_router = None
        self.external_subscriptions = {}

    def start_up(self):
        """ Initialization zone.
        """
        self.registry = GAplicRegistry(self)
        if self.config.pyramid_router_url:
            # router inside pyramid.
            self.sockjs = self.create_gobj(
                self.config.pyramid_router_url,       # named gobj
                GSockjsServer,          # gclass
                self.config.pyramid_root,      # parent
                sockjs_app_class=RouterConnection,
                response_limit=4096,
                #disabled_transports=('websocket',)  # we need support IE8
            )
        elif self.config.server:
            # router with server sock
            self.start_router_server()

        self._timer = self.create_gobj(
            None,
            GTimer,
            self,
            timeout_event_name='EV_TIMEOUT')
        self.set_timeout(self.config.timeout_idle)

        if self.config.static_routes:
            routes = self.config.static_routes
            for r in routes:
                name, roles, urls = r
                self.send_event(
                    self,
                    'EV_ADD_STATIC_ROUTE',
                    name=name,
                    roles=roles,
                    urls=urls,
                )

    def set_timeout(self, seconds):
        if self._timer:  # protect from overwrite_parameters
            self.send_event(self._timer, 'EV_SET_TIMER', seconds=seconds)

    def clear_timeout(self):
        if self._timer:  # protect from overwrite_parameters
            self.send_event(self._timer, 'EV_SET_TIMER', seconds=-1)

    def mt_execute_command(self, command):
        ret = 'EXECUTED ' + command + ' Ok'
        return ret

    def mt_show_routes(self):
        registry = self.registry
        s = 'My gaplic name: %r\n' % registry.my_gaplic_name
        s += 'My roles: %r\n\n' % registry.my_roles
        static_routes = registry.static_routes
        s += 'Static routes:\n'
        for key in static_routes:
            r = static_routes[key]
            name = r.gaplic_name
            roles = r.roles
            urls = r.urls
            acked = 'Yes Acked' if r.identity_ack else 'NOT Acked'
            s += '  route_ref: %-12s | name:%r | roles:%r | %s | %s\n' % (
                key,
                name,
                roles,
                urls,
                acked,
            )
        s += '\n'

        s += 'Dynamic routes:\n'
        dynamic_routes = registry.dynamic_routes
        for key in dynamic_routes:
            r = dynamic_routes[key]
            name = r.gaplic_name
            roles = r.roles
            s += '  route_ref: %-12s | name:%s | roles:%s\n' % (
                key, name, roles)
        s += '\n'
        return s

    def check_routes(self):
        registry = self.registry
        static_routes = registry.static_routes
        ret = False
        for key in static_routes:
            r = static_routes[key]
            if not r.identity_ack:
                # TODO: retransmite la identity si timeout
                ret = True

            # TODO: retransmite cur_pending_event si timeout

        dynamic_routes = registry.dynamic_routes
        for key in dynamic_routes:
            r = dynamic_routes[key]
            # TODO: retransmite cur_pending_event si timeout
            pass

        return ret

    def trace_intra_event(self, prefix, intra_event):
        hora = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        message_type = intra_event.message_type

        if message_type == '__event__':
            fields = intra_event.event_fields
        elif message_type == '__event_ack__':
            fields = intra_event.event_ack_fields
        elif message_type == '__event_nack__':
            fields = intra_event.event_nack_fields
        elif message_type == '__identity_card__':
            fields = intra_event.identity_card_fields
        elif message_type == '__identity_card_ack__':
            fields = intra_event.identity_card_ack_fields
        else:
            self.logger.info(
                'ERROR unknown message type %r' % message_type)

        try:
            trace = "\n%s %s\n" % (
                hora,
                prefix,
            )
            for f in fields:
                trace += "    %s: %r\n" % (f, getattr(intra_event, f))
            self.logger.info(trace)

        except Exception as e:
            self.logger.error(
                "ERROR %s:\n%r" % (e, intra_event),
                exc_info=True,
            )

    def send_identity_card(self, route, roles_back_way=None):
        my_gaplic_name = self.registry.my_gaplic_name
        my_roles = self.registry.my_roles
        if roles_back_way:
            my_roles_back_way = roles_back_way
            prefix = '%s ^==> %s' % (my_gaplic_name, route)
        else:
            my_roles_back_way = self.registry.get_roles_back_way()
            prefix = '%s ==> %s' % (my_gaplic_name, route)

        idc = IntraEvent(
            message_type='__identity_card__',
            route_ref=None,
            serial=None,
            my_gaplic_name=my_gaplic_name,
            my_roles=list(my_roles) + list(my_roles_back_way),
            kw={},
        )

        if self.config.trace_router:
            self.trace_intra_event(prefix, idc)
        x = idc.toJSON()
        route.write(x)

    def find_local_router(self):
        if self.local_router:
            return  # already created.

        ports = list(self.config.localhost_route_ports)
        if self.server_sock:
            # remove own port if iam-server
            try:
                index = ports.index(self.server_sock.port)
                ports.pop(index)
            except ValueError:
                pass

        destinations = list((lambda x: ('localhost', x), ports))
        self.local_router = self.create_gobj(
            'local_router_client',
            GConnex,
            self,
            transmit_ready_event_name=None,
            destinations=destinations,
        )

    def start_router_server(self):
        self.server_sock = self.create_gobj(
            self.gaplic.name + '-router',
            GServerSock,
            self,
            host='0.0.0.0',
            ports=self.config.localhost_route_ports,
            use_multi_ports=True,
            transmit_ready_event_name=None,
        )

    def _send_event_to_external_route(
            self,
            route_ref,
            gaplic_name,
            role,
            gobj_name,
            event_name,
            subscriber_gobj,
            kw):
        registry = self.registry
        route = registry.get_route_by_ref(route_ref)
        if not route:
            self.logger.error("ERROR route_ref NOT FOUND: %r" % route_ref)
            return False

        intra_event = IntraEvent(
            message_type='__event__',
            serial=route.incr_serial(),
            event_name=event_name,
            destination_gaplic=gaplic_name,
            destination_role=role,
            destination_gobj=gobj_name,
            origin_gaplic=registry.my_gaplic_name,
            origin_role=registry.my_roles,  # use destination_role?
            origin_gobj=subscriber_gobj,
            kw=kw)

        registry.enqueue_pending_event(route, intra_event)
        if not route.cur_pending_event:
            registry.fire_pending_events(route)
        return True

    def make_external_subscription(self, intra_event, route_ref):
        k = random_key()
        subscription = ExternalSubscription(intra_event, route_ref)
        self.external_subscriptions[k] = subscription
        return k

    def remove_external_subscription(self, subscription_reference):
        if subscription_reference in self.external_subscriptions:
            subs = self.external_subscriptions[subscription_reference]
            if subs:
                isubscription = subs.isubscription
                named_gobj = self.gaplic.find_unique_gobj(
                    subs.destination_gobj)
                if named_gobj:
                    named_gobj.delete_subscription_by_object(isubscription)
            del self.external_subscriptions[subscription_reference]

    def get_external_subscription(self, subscription_reference):
        if subscription_reference in self.external_subscriptions:
            subs = self.external_subscriptions[subscription_reference]
            return subs