/
disc_server.py
1479 lines (1281 loc) · 54.4 KB
/
disc_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
"""
This is the main module in discovery service package. It manages interaction
between http/rest and database interfaces.
"""
import gevent
from gevent import monkey
monkey.patch_all()
from gevent import hub
from disc_cassdb import DiscoveryCassandraClient
import sys
import time
import logging
import signal
import os
import socket
from cfgm_common import jsonutils as json
import xmltodict
import uuid
import copy
import datetime
import argparse
import ConfigParser
from pprint import pformat
import random
from netaddr import IPNetwork, IPAddress, IPSet, IPRange
import bottle
from disc_utils import *
import disc_consts
import disc_exceptions
import output
import discoveryclient.client as discovery_client
# sandesh
from pysandesh.sandesh_base import *
from pysandesh.sandesh_logger import *
from pysandesh.gen_py.sandesh.ttypes import SandeshLevel
from sandesh_common.vns.ttypes import Module, NodeType
from pysandesh.connection_info import ConnectionState
from sandesh.discovery_introspect import ttypes as sandesh
from sandesh.cfgm_cpuinfo.ttypes import NodeStatusUVE, NodeStatus
from sandesh_common.vns.constants import ModuleNames, Module2NodeType, NodeTypeNames,\
INSTANCE_ID_DEFAULT
from gevent.coros import BoundedSemaphore
from cfgm_common.rest import LinkObject
import disc_auth_keystone
def obj_to_json(obj):
# Non-null fields in object get converted to json fields
return lambda obj: dict((k, v) for k, v in obj.__dict__.iteritems())
# end obj_to_json
class DiscoveryServer():
def __init__(self, args):
self._homepage_links = []
self._args = args
self.service_config = args.service_config
self.cassandra_config = args.cassandra_config
self._debug = {
'hb_stray': 0,
'msg_pubs': 0,
'msg_subs': 0,
'msg_query': 0,
'msg_hbt': 0,
'ttl_short': 0,
'policy_rr': 0,
'policy_lb': 0,
'policy_fi': 0,
'db_upd_hb': 0,
'throttle_subs':0,
'503': 0,
'lb_count': 0,
'lb_auto': 0,
'db_exc_unknown': 0,
'db_exc_info': '',
'wl_rejects_pub': 0,
'wl_rejects_sub': 0,
'auth_failures': 0,
}
self._ts_use = 1
self.short_ttl_map = {}
self._sem = BoundedSemaphore(1)
self._pub_wl = None
self._sub_wl = None
self._base_url = "http://%s:%s" % (self._args.listen_ip_addr,
self._args.listen_port)
self._pipe_start_app = None
bottle.route('/', 'GET', self.homepage_http_get)
# heartbeat
bottle.route('/heartbeat', 'POST', self.api_heartbeat)
# publish service
bottle.route('/publish', 'POST', self.api_publish)
self._homepage_links.append(
LinkObject(
'action',
self._base_url , '/publish', 'publish service'))
bottle.route('/publish/<end_point>', 'POST', self.api_publish)
# subscribe service
bottle.route('/subscribe', 'POST', self.api_subscribe)
self._homepage_links.append(
LinkObject(
'action',
self._base_url , '/subscribe', 'subscribe service'))
# query service
bottle.route('/query', 'POST', self.api_query)
self._homepage_links.append(
LinkObject(
'action',
self._base_url , '/query', 'query service'))
# collection - services
bottle.route('/services', 'GET', self.show_all_services)
self._homepage_links.append(
LinkObject(
'action',
self._base_url , '/services', 'show published services'))
bottle.route('/services.json', 'GET', self.services_json)
self._homepage_links.append(
LinkObject(
'action',
self._base_url , '/services.json',
'List published services in JSON format'))
# show a specific service type
bottle.route('/services/<service_type>', 'GET', self.show_all_services)
# api to perform on-demand load-balance across available publishers
bottle.route('/load-balance/<service_type>', 'POST', self.api_lb_service)
# update service
bottle.route('/service/<id>', 'PUT', self.service_http_put)
# get service info
bottle.route('/service/<id>', 'GET', self.service_http_get)
bottle.route('/service/<id>/brief', 'GET', self.service_brief_http_get)
# delete (un-publish) service
bottle.route('/service/<id>', 'DELETE', self.service_http_delete)
# collection - clients
bottle.route('/clients', 'GET', self.show_all_clients)
bottle.route('/clients/<service_type>/<service_id>', 'GET', self.show_all_clients)
self._homepage_links.append(
LinkObject(
'action',
self._base_url , '/clients', 'list all subscribers'))
bottle.route('/clients.json', 'GET', self.clients_json)
self._homepage_links.append(
LinkObject(
'action',
self._base_url , '/clients.json',
'list all subscribers in JSON format'))
# show config
bottle.route('/config', 'GET', self.show_config)
self._homepage_links.append(
LinkObject(
'action',
self._base_url , '/config', 'show discovery service config'))
# show debug
bottle.route('/stats', 'GET', self.show_stats)
self._homepage_links.append(
LinkObject(
'action',
self._base_url , '/stats', 'show discovery service stats'))
# cleanup
bottle.route('/cleanup', 'GET', self.cleanup_http_get)
self._homepage_links.append(LinkObject('action',
self._base_url , '/cleanup', 'Purge inactive publishers'))
if not self._pipe_start_app:
self._pipe_start_app = bottle.app()
# sandesh init
self._sandesh = Sandesh()
if self._args.sandesh_send_rate_limit is not None:
SandeshSystem.set_sandesh_send_rate_limit( \
self._args.sandesh_send_rate_limit)
module = Module.DISCOVERY_SERVICE
module_name = ModuleNames[module]
node_type = Module2NodeType[module]
node_type_name = NodeTypeNames[node_type]
instance_id = self._args.worker_id
disc_client = discovery_client.DiscoveryClient(
self._args.listen_ip_addr, self._args.listen_port,
ModuleNames[Module.DISCOVERY_SERVICE])
self._sandesh.init_generator(
module_name, socket.gethostname(), node_type_name, instance_id,
self._args.collectors, 'discovery_context',
int(self._args.http_server_port), ['discovery.sandesh'], disc_client,
logger_class=self._args.logger_class,
logger_config_file=self._args.logging_conf)
self._sandesh.set_logging_params(enable_local_log=self._args.log_local,
category=self._args.log_category,
level=self._args.log_level,
enable_syslog=args.use_syslog,
file=self._args.log_file)
self._sandesh.trace_buffer_create(name="dsHeartBeatTraceBuf",
size=1000)
self._sandesh.trace_buffer_create(name="dsPublishTraceBuf",
size=1000)
self._sandesh.trace_buffer_create(name="dsSubscribeTraceBuf",
size=1000)
ConnectionState.init(self._sandesh, socket.gethostname(), module_name,
instance_id, staticmethod(ConnectionState.get_process_state_cb),
NodeStatusUVE, NodeStatus)
# DB interface initialization
self._db_connect(self._args.reset_config)
self._db_conn.db_update_service_entry_oper_state()
self._db_conn.db_update_service_entry_admin_state()
# build in-memory subscriber data
self._sub_data = {}
for (client_id, service_type) in self._db_conn.subscriber_entries():
self.create_sub_data(client_id, service_type)
# build white list
if self._args.white_list_publish:
self._pub_wl = IPSet()
for prefix in self._args.white_list_publish.split(" "):
self._pub_wl.add(prefix)
if self._args.white_list_subscribe:
self._sub_wl = IPSet()
for prefix in self._args.white_list_subscribe.split(" "):
self._sub_wl.add(prefix)
self._auth_svc = None
if self._args.auth == 'keystone':
ks_conf = {
'auth_host': self._args.auth_host,
'auth_port': self._args.auth_port,
'auth_protocol': self._args.auth_protocol,
'admin_user': self._args.admin_user,
'admin_password': self._args.admin_password,
'admin_tenant_name': self._args.admin_tenant_name,
'region_name': self._args.region_name,
}
self._auth_svc = disc_auth_keystone.AuthServiceKeystone(ks_conf)
# end __init__
def config_log(self, msg, level):
self._sandesh.logger().log(SandeshLogger.get_py_logger_level(level),
msg)
def syslog(self, log_msg):
log = sandesh.discServiceLog(
log_msg=log_msg, sandesh=self._sandesh)
log.send(sandesh=self._sandesh)
def create_sub_data(self, client_id, service_type):
if not client_id in self._sub_data:
self._sub_data[client_id] = {}
if not service_type in self._sub_data[client_id]:
sdata = {
'ttl_expires': 0,
'heartbeat': int(time.time()),
}
self._sub_data[client_id][service_type] = sdata
return self._sub_data[client_id][service_type]
# end
def delete_sub_data(self, client_id, service_type):
if (client_id in self._sub_data and
service_type in self._sub_data[client_id]):
del self._sub_data[client_id][service_type]
if len(self._sub_data[client_id]) == 0:
del self._sub_data[client_id]
# end
def get_sub_data(self, id, service_type):
if id in self._sub_data and service_type in self._sub_data[id]:
return self._sub_data[id][service_type]
return self.create_sub_data(id, service_type)
# end
# Public Methods
def get_args(self):
return self._args
# end get_args
def get_ip_addr(self):
return self._args.listen_ip_addr
# end get_ip_addr
def get_port(self):
return self._args.listen_port
# end get_port
def get_pipe_start_app(self):
return self._pipe_start_app
# end get_pipe_start_app
def homepage_http_get(self):
json_links = []
url = bottle.request.url[:-1]
for link in self._homepage_links:
json_links.append({'link': link.to_dict(with_url=url)})
json_body = \
{"href": self._base_url,
"links": json_links
}
return json_body
# end homepage_http_get
def get_service_config(self, service_type, item):
service = service_type.lower()
if (service in self.service_config and
item in self.service_config[service]):
return self.service_config[service][item]
elif item in self._args.__dict__:
return self._args.__dict__[item]
else:
return None
# end
def _db_connect(self, reset_config):
self._db_conn = DiscoveryCassandraClient("discovery",
self._args.cassandra_server_list, self.config_log, reset_config,
self._args.cluster_id)
# end _db_connect
def cleanup(self):
pass
# end cleanup
def get_ttl_short(self, client_id, service_type, default):
ttl = default
if not client_id in self.short_ttl_map:
self.short_ttl_map[client_id] = {}
if service_type in self.short_ttl_map[client_id]:
# keep doubling till we land in normal range
ttl = self.short_ttl_map[client_id][service_type] * 2
if ttl >= 32:
ttl = 32
self.short_ttl_map[client_id][service_type] = ttl
return ttl
# end
# check if service expired (return color along)
def service_expired(self, entry, include_color=False, include_down=True):
timedelta = datetime.timedelta(
seconds=(int(time.time()) - entry['heartbeat']))
if self._args.hc_interval <= 0:
# health check has been disabled
color = "#00FF00" # green - all good
expired = False
elif timedelta.seconds <= self._args.hc_interval:
color = "#00FF00" # green - all good
expired = False
elif (timedelta.seconds > (self._args.hc_interval *
self._args.hc_max_miss)):
color = "#FF0000" # red - publication expired
expired = True
else:
color = "#FFFF00" # yellow - missed some heartbeats
expired = False
if include_down and \
(entry['admin_state'] != 'up' or entry['oper_state'] != 'up'):
color = "#FF0000" # red - publication expired
expired = True
if include_color:
return (expired, color, timedelta)
else:
return expired
# end service_expired
# decorator to catch DB error
def db_error_handler(func):
def error_handler(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except disc_exceptions.ServiceUnavailable:
self._debug['503'] += 1
bottle.abort(503, 'Service Unavailable')
except Exception as e:
self._debug['db_exc_unknown'] += 1
self._debug['db_exc_info'] = str(sys.exc_info())
raise
return error_handler
# decorator to authenticate request
def authenticate(func):
def wrapper(self, *args, **kwargs):
if self._auth_svc and not self._auth_svc.is_admin(bottle.request):
self._debug['auth_failures'] += 1
bottle.abort(401, 'Unauthorized')
return func(self, *args, **kwargs)
return wrapper
# 404 forces republish
def heartbeat(self, sig):
# self.syslog('heartbeat from "%s"' % sig)
self._debug['msg_hbt'] += 1
info = sig.split(':')
if len(info) != 2:
self.syslog('Unable to parse heartbeat cookie %s' % sig)
bottle.abort(404, 'Unable to parse heartbeat')
service_type = info[1]
service_id = info[0]
entry = self._db_conn.lookup_service(service_type, service_id)
if not entry:
self.syslog('Received stray heartbeat with cookie %s' % (sig))
self._debug['hb_stray'] += 1
bottle.abort(404, 'Publisher %s not found' % sig)
# update heartbeat timestamp in database
entry['heartbeat'] = int(time.time())
# insert entry if timed out by background task
self._db_conn.update_service(
service_type, entry['service_id'], entry)
m = sandesh.dsHeartBeat(
publisher_id=sig, service_type=service_type,
sandesh=self._sandesh)
m.trace_msg(name='dsHeartBeatTraceBuf', sandesh=self._sandesh)
return '200 OK'
# end heartbeat
@db_error_handler
def api_heartbeat(self):
ctype = bottle.request.headers['content-type']
json_req = {}
try:
if 'application/xml' in ctype:
data = xmltodict.parse(bottle.request.body.read())
else:
data = bottle.request.json
except Exception as e:
self.syslog('Unable to parse heartbeat')
self.syslog(bottle.request.body.buf)
bottle.abort(400, 'Unable to parse heartbeat')
status = self.heartbeat(data['cookie'])
return status
@db_error_handler
def api_publish(self, end_point = None):
self._debug['msg_pubs'] += 1
source = bottle.request.headers.get('X-Forwarded-For', None)
if source and self._pub_wl and source not in self._pub_wl:
self._debug['wl_rejects_pub'] += 1
bottle.abort(401, 'Unauthorized request')
ctype = bottle.request.headers['content-type']
json_req = {}
try:
if 'application/json' in ctype:
data = bottle.request.json
elif 'application/xml' in ctype:
data = xmltodict.parse(bottle.request.body.read())
except Exception as e:
self.syslog('Unable to parse publish request')
self.syslog(bottle.request.body.buf)
bottle.abort(415, 'Unable to parse publish request')
# new format - publish tag to envelop entire content
if 'publish' in data:
data = data['publish']
for key, value in data.items():
json_req[key] = value
# old format didn't include explicit tag for service type
service_type = data.get('service-type', data.keys()[0])
# convert ordered dict to normal dict
try:
json_req[service_type] = data[service_type]
except (ValueError, KeyError, TypeError) as e:
bottle.abort(400, "Unknown service type")
info = json_req[service_type]
remote = json_req.get('remote-addr',
bottle.request.environ['REMOTE_ADDR'])
version = json_req.get('version', disc_consts.DEFAULT_VERSION)
sig = json_req.get('service-id', end_point) or \
publisher_id(remote, json.dumps(json_req))
# Avoid reading from db unless service policy is fixed
# Fixed policy is anchored on time of entry creation
policy = self.get_service_config(service_type, 'policy')
if policy == 'fixed':
entry = self._db_conn.lookup_service(service_type, service_id=sig)
if entry and self.service_expired(entry):
entry = None
else:
entry = None
if not entry:
entry = {
'service_type': service_type,
'service_id': sig,
'in_use': 0,
'ts_use': 0,
'ts_created': int(time.time()),
'oper_state': 'up',
'oper_state_msg': '',
'sequence': str(int(time.time())) + socket.gethostname(),
}
if 'oper-state' in json_req:
oper_state = json_req['oper-state']
if oper_state not in ['up', 'down']:
bottle.abort(400, "Invalid operational state")
entry['oper_state'] = oper_state
if 'oper-state-reason' in json_req:
osr = json_req['oper-state-reason']
if type(osr) != str and type(osr) != unicode:
bottle.abort(400, "Invalid format of operational state reason")
entry['oper_state_msg'] = osr
entry['info'] = info
entry['heartbeat'] = int(time.time())
entry['remote'] = remote
entry['version'] = version
entry['ep_type'] = service_type
entry['ep_id'] = sig
# insert entry if new or timed out
self._db_conn.update_service(service_type, sig, entry)
response = {'cookie': sig + ':' + service_type}
if ctype != 'application/json':
response = xmltodict.unparse({'response': response})
msg = 'service=%s, id=%s, info=%s' % (service_type, sig, json.dumps(info))
m = sandesh.dsPublish(msg=msg, sandesh=self._sandesh)
m.trace_msg(name='dsPublishTraceBuf', sandesh=self._sandesh)
return response
# end api_publish
# randomize services with same in_use count to handle requests arriving
# at the same time
def disco_shuffle(self, list):
if list is None or len(list) == 0:
return list
master_list = []
working_list = []
previous_use_count = list[0]['in_use']
list.append({'in_use': -1})
for item in list:
if item['in_use'] != previous_use_count:
random.shuffle(working_list)
master_list.extend(working_list)
working_list = []
working_list.append(item)
previous_use_count = item['in_use']
return master_list
# round-robin
def service_list_round_robin(self, pubs):
self._debug['policy_rr'] += 1
return sorted(pubs, key=lambda service: service['ts_use'])
# end
# load-balance
def service_list_load_balance(self, pubs):
self._debug['policy_lb'] += 1
temp = sorted(pubs, key=lambda service: service['in_use'])
return self.disco_shuffle(temp)
# end
# master election
def service_list_fixed(self, pubs):
self._debug['policy_fi'] += 1
return sorted(pubs, key=lambda service: service['sequence'])
# end
def service_list(self, service_type, pubs):
policy = self.get_service_config(service_type, 'policy') or 'load-balance'
if 'load-balance' in policy:
f = self.service_list_load_balance
elif policy == 'fixed':
f = self.service_list_fixed
else:
f = self.service_list_round_robin
return f(pubs)
# end
"""
read DSA rules
'dsa_rule_entry': {
u'subscriber': [{
u'ep_type': u'',
u'ep_id': u'',
u'ep_prefix': {u'ip_prefix': u'2.2.2.2', u'ip_prefix_len': 32},
u'ep_version': u''}],
u'publisher': {
u'ep_type': u'',
u'ep_id': u'',
u'ep_prefix': {u'ip_prefix': u'1.1.1.1', u'ip_prefix_len': 32},
u'ep_version': u''}
}
"""
def match_dsa_rule_ep(self, rule_ep, ep):
# self.syslog('dsa rule_ep %s, ep %s' % (rule_ep, ep))
if rule_ep['ep_type'] != '' and rule_ep['ep_type'] != ep['ep_type']:
return (False, 0)
if rule_ep['ep_id'] != '' and rule_ep['ep_id'] != ep['ep_id']:
return (False, 0)
if rule_ep['ep_version'] != '' and rule_ep['ep_version'] != ep['version']:
return (False, 0);
prefix = rule_ep['ep_prefix']
if prefix['ip_prefix'] == '':
return (True, 0)
network = IPNetwork('%s/%s' % (prefix['ip_prefix'], prefix['ip_prefix_len']))
remote = IPAddress(ep['remote'])
return (remote in network, prefix['ip_prefix_len'])
def match_subscriber(self, dsa_rule, sub):
for rule_sub in dsa_rule['subscriber']:
match, match_len = self.match_dsa_rule_ep(rule_sub, sub)
if match:
return True, match_len
return False, 0
def match_publishers(self, rule_list, pubs):
result = []
for pub in pubs:
for dsa_rule in rule_list:
ok, pfxlen = self.match_dsa_rule_ep(dsa_rule['publisher'], pub)
if ok:
result.append(pub)
return result
def apply_dsa_config(self, service_type, pubs, sub):
if len(pubs) == 0:
return pubs
dsa_rules = self._db_conn.read_dsa_config()
if dsa_rules is None:
return pubs
# self.syslog('dsa: rules %s' % dsa_rules)
lpm = -1
matched_rules = None
for rule in dsa_rules:
# ignore rule if publisher not relevant
if rule['publisher']['ep_type'] != service_type:
continue
# ignore rule if subscriber doesn't match
matched, matched_len = self.match_subscriber(rule, sub)
if not matched:
continue
self.syslog('dsa: matched sub %s' % sub)
# collect matched rules
if matched_len > lpm:
lpm = matched_len
matched_rules = [rule]
elif matched_len == lpm:
matched_rules.append(rule)
# end for
# return original list if there is no sub match
if not matched_rules:
return pubs
matched_pubs = self.match_publishers(matched_rules, pubs)
self.syslog('dsa: matched pubs %s' % matched_pubs)
return matched_pubs
# reorder services (pubs) based on what client is actually using (in_use_list)
# client's in-use list publishers are pushed to the top
def adjust_in_use_list(self, pubs, in_use_list):
if not in_use_list:
return pubs
pubid_list = in_use_list['publisher-id']
if not pubid_list:
return pubs
pubs_dict = {entry['service_id']:entry for entry in pubs}
result = [pubs_dict[pid] for pid in pubid_list if pid in pubs_dict]
x = [entry for entry in pubs if entry['service_id'] not in pubid_list]
return result + x
@db_error_handler
def api_subscribe(self):
self._debug['msg_subs'] += 1
source = bottle.request.headers.get('X-Forwarded-For', None)
if source and self._sub_wl and source not in self._sub_wl:
self._debug['wl_rejects_sub'] += 1
bottle.abort(401, 'Unauthorized request')
ctype = bottle.request.headers['content-type']
if 'application/json' in ctype:
json_req = bottle.request.json
elif 'application/xml' in ctype:
data = xmltodict.parse(bottle.request.body.read())
json_req = {}
for service_type, info in data.items():
json_req['service'] = service_type
json_req.update(dict(info))
else:
bottle.abort(400, e)
service_type = json_req['service']
client_id = json_req['client']
count = reqcnt = int(json_req['instances'])
client_type = json_req.get('client-type', '')
remote = json_req.get('remote-addr',
bottle.request.environ['REMOTE_ADDR'])
version = json_req.get('version', disc_consts.DEFAULT_VERSION)
assigned_sid = set()
r = []
ttl_min = int(self.get_service_config(service_type, 'ttl_min'))
ttl_max = int(self.get_service_config(service_type, 'ttl_max'))
ttl = random.randint(ttl_min, ttl_max)
# check client entry and any existing subscriptions
cl_entry, subs = self._db_conn.lookup_client(service_type, client_id)
if not cl_entry:
cl_entry = {
'instances': count,
'client_type': client_type,
'client_id': client_id,
}
self.create_sub_data(client_id, service_type)
cl_entry['remote'] = remote
cl_entry['version'] = version
cl_entry['ep_type'] = client_type
cl_entry['ep_id'] = client_id
self._db_conn.insert_client_data(service_type, client_id, cl_entry)
sdata = self.get_sub_data(client_id, service_type)
if sdata:
sdata['ttl_expires'] += 1
# send short ttl if no publishers
pubs = self._db_conn.lookup_service(service_type, include_count=True) or []
pubs_active = [item for item in pubs if not self.service_expired(item)]
pubs_active = self.apply_dsa_config(service_type, pubs_active, cl_entry)
pubs_active = self.service_list(service_type, pubs_active)
plist = dict((entry['service_id'],entry) for entry in pubs_active)
plist_all = dict((entry['service_id'],entry) for entry in pubs)
try:
inuse_list = json_req['service-in-use-list']['publisher-id']
# convert to list if singleton
if type(inuse_list) != list:
inuse_list = [inuse_list]
except Exception as e:
inuse_list = []
min_instances = int(json_req.get('min-instances', '0'))
assign = count or max(len(inuse_list), min_instances)
if len(pubs_active) < count or len(pubs_active) < min_instances:
ttl = random.randint(1, 32)
self._debug['ttl_short'] += 1
cid = "<cl=%s,st=%s>" % (client_id, service_type)
msg = '%s, ttl=%d, asked=%d pubs=%d/%d, subs=%d, m_i=%d, assign=%d, siul=%d' \
% (cid, ttl, count, len(pubs), len(pubs_active), len(subs),
min_instances, assign, len(inuse_list))
m = sandesh.dsSubscribe(msg=msg, sandesh=self._sandesh)
m.trace_msg(name='dsSubscribeTraceBuf', sandesh=self._sandesh)
if count == 0:
count = len(pubs_active)
expiry_dict = dict((service_id,expiry) for service_id, expiry in subs or [])
policy = self.get_service_config(service_type, 'policy')
# Auto load-balance is triggered if enabled and some servers are
# more than 5% off expected average allocation.
load_balance = (policy == 'dynamic-load-balance')
if load_balance:
total_subs = sum([entry['in_use'] for entry in pubs_active])
avg = total_subs/len(pubs_active)
# if subscriber in-use-list present, forget previous assignments
if len(inuse_list):
subs = [(service_id, expiry_dict.get(service_id, False)) for service_id in inuse_list]
if subs and count:
for service_id, expired in subs:
# expired True if service was marked for deletion by LB command
# previously published service is gone
# force renew for fixed policy since some service may have flapped
entry = plist.get(service_id, None)
if entry is None or expired or policy == 'fixed' or (load_balance and entry['in_use'] > int(1.05*avg)):
self.syslog("%s del sub, lb=%s, policy=%s, expired=%s" % (cid, load_balance, policy, expired))
self._db_conn.delete_subscription(service_type, client_id, service_id)
# load-balance one at at time to avoid churn
if load_balance and entry and entry['in_use'] > int(1.05*avg):
self._debug['lb_auto'] += 1
load_balance = False
continue
msg = ' subs service=%s, assign=%d, count=%d' % (service_id, assign, count)
m = sandesh.dsSubscribe(msg=msg, sandesh=self._sandesh)
m.trace_msg(name='dsSubscribeTraceBuf', sandesh=self._sandesh)
self.syslog("%s %s" % (cid, msg))
if assign:
assign -= 1
self._db_conn.insert_client(
service_type, service_id, client_id, entry['info'], ttl)
r.append(entry)
assigned_sid.add(service_id)
count -= 1
if count == 0:
break
# skip duplicates from existing assignments
pubs = [entry for entry in pubs_active if not entry['service_id'] in assigned_sid]
# take first 'count' publishers
for entry in pubs[:min(count, len(pubs))]:
r.append(entry)
msg = ' assign service=%s, info=%s' % \
(entry['service_id'], json.dumps(entry['info']))
m = sandesh.dsSubscribe(msg=msg, sandesh=self._sandesh)
m.trace_msg(name='dsSubscribeTraceBuf', sandesh=self._sandesh)
self.syslog("%s %s" % (cid, msg))
# create client entry
if assign:
assign -= 1
self._db_conn.insert_client(
service_type, entry['service_id'], client_id, entry['info'], ttl)
# update publisher TS for round-robin algorithm
entry['ts_use'] = self._ts_use
self._ts_use += 1
self._db_conn.update_service(
service_type, entry['service_id'], entry)
pubs = []
for entry in r:
result = entry['info'].copy()
result['@publisher-id'] = entry['service_id']
pubs.append(result)
response = {'ttl': ttl, service_type: pubs}
if 'application/xml' in ctype:
response = xmltodict.unparse({'response': response})
return response
# end api_subscribe
# on-demand API to load-balance existing subscribers across all currently available
# publishers. Needed if publisher gets added or taken down
@authenticate
def api_lb_service(self, service_type):
if service_type is None:
bottle.abort(405, "Missing service")
pubs = self._db_conn.lookup_service(service_type, include_count=True) or []
if pubs is None:
bottle.abort(405, 'Unknown service')
pubs_active = [item for item in pubs if not self.service_expired(item)]
# only load balance if over 5% deviation from average to avoid churn
avg_per_pub = sum([entry['in_use'] for entry in pubs_active])/len(pubs_active)
lb_list = dict((item['service_id'],(item['in_use']-int(avg_per_pub))) for item in pubs_active if item['in_use'] > int(1.05*avg_per_pub))
if len(lb_list) == 0:
return
clients = self._db_conn.get_all_clients(service_type=service_type)
if clients is None:
return
self.syslog('%s: Initial load-balance server-list: %s, avg-per-pub %d, clients %d' \
% (service_type, lb_list, avg_per_pub, len(clients)))
"""
Walk through all subscribers and mark one publisher per subscriber down
for deletion later. We could have deleted subscription right here.
However the discovery server view of subscribers will not match with actual
subscribers till respective TTL expire. Note that we only mark down ONE
publisher per subscriber to avoid much churn at the subscriber end.
self._db_conn.delete_subscription(service_type, client_id, service_id)
"""
clients_lb_done = []
for client in clients:
(service_type, client_id, service_id, mtime, ttl) = client
if client_id not in clients_lb_done and service_id in lb_list and lb_list[service_id] > 0:
self.syslog('expire client=%s, service=%s, ttl=%d' % (client_id, service_id, ttl))
self._db_conn.mark_delete_subscription(service_type, client_id, service_id)
clients_lb_done.append(client_id)
lb_list[service_id] -= 1
self._debug['lb_count'] += 1
return {}
# end api_lb_service
def api_query(self):
self._debug['msg_query'] += 1
ctype = bottle.request.headers['content-type']
if ctype == 'application/json':
json_req = bottle.request.json
elif ctype == 'application/xml':
data = xmltodict.parse(bottle.request.body.read())
json_req = {}
for service_type, info in data.items():
json_req['service'] = service_type
json_req.update(dict(info))
else:
bottle.abort(400, e)
service_type = json_req['service']
count = int(json_req['instances'])
r = []
# lookup publishers of the service
pubs = self._db_conn.query_service(service_type)
if not pubs:
return {service_type: r}
# eliminate inactive services
pubs_active = [item for item in pubs if not self.service_expired(item)]
self.syslog(' query: Found %s publishers, %d active, need %d' %
(len(pubs), len(pubs_active), count))
# find least loaded instances
pubs = pubs_active
# prepare response - send all if count 0
for index in range(min(count, len(pubs)) if count else len(pubs)):
entry = pubs[index]
result = entry['info']
r.append(result)
self.syslog(' assign service=%s, info=%s' %
(entry['service_id'], json.dumps(result)))
response = {service_type: r}
if 'application/xml' in ctype:
response = xmltodict.unparse({'response': response})
return response
# end api_subscribe
@db_error_handler
def show_all_services(self, service_type=None):
rsp = output.display_user_menu()
rsp += ' <table border="1" cellpadding="1" cellspacing="0">\n'
rsp += ' <tr>\n'
rsp += ' <td>Service Type</td>\n'
rsp += ' <td>Remote IP</td>\n'
rsp += ' <td>Service Id</td>\n'
rsp += ' <td>Oper State</td>\n'
rsp += ' <td>Admin State</td>\n'
rsp += ' <td>In Use</td>\n'
rsp += ' <td>Time since last Heartbeat</td>\n'
rsp += ' </tr>\n'
for pub in self._db_conn.lookup_service(service_type, include_count=True):
info = pub['info']
service_type = pub['service_type']
service_id = pub['service_id']
sig = service_id + ':' + service_type
rsp += ' <tr>\n'
if service_type:
rsp += ' <td>' + service_type + '</td>\n'
else:
link = do_html_url("/services/%s" % service_type, service_type)
rsp += ' <td>' + link + '</td>\n'
rsp += ' <td>' + pub['remote'] + '</td>\n'