/
opserver.py
2537 lines (2288 loc) · 103 KB
/
opserver.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.
#
#
# Opserver
#
# Operational State Server for VNC
#
from gevent import monkey
monkey.patch_all()
try:
from collections import OrderedDict
except ImportError:
# python 2.6 or earlier, use backport
from ordereddict import OrderedDict
from collections import namedtuple
TableSchema = namedtuple("TableSchema", ("name", "datatype", "index", "suffixes"))
from uveserver import UVEServer
import sys
import ConfigParser
import bottle
import json
import uuid
import argparse
import time
import redis
import base64
import socket
import struct
import signal
import errno
import copy
import datetime
import pycassa
import platform
from analytics_db import AnalyticsDb
from pycassa.pool import ConnectionPool
from pycassa.columnfamily import ColumnFamily
from pysandesh.util import UTCTimestampUsec
from pysandesh.sandesh_base import *
from pysandesh.sandesh_session import SandeshWriter
from pysandesh.gen_py.sandesh_trace.ttypes import SandeshTraceRequest
from pysandesh.connection_info import ConnectionState
from sandesh_common.vns.ttypes import Module, NodeType
from sandesh_common.vns.constants import ModuleNames, CategoryNames,\
ModuleCategoryMap, Module2NodeType, NodeTypeNames, ModuleIds,\
INSTANCE_ID_DEFAULT, COLLECTOR_DISCOVERY_SERVICE_NAME,\
ANALYTICS_API_SERVER_DISCOVERY_SERVICE_NAME, ALARM_GENERATOR_SERVICE_NAME, \
OpServerAdminPort, CLOUD_ADMIN_ROLE, APIAAAModes, \
AAA_MODE_CLOUD_ADMIN, AAA_MODE_NO_AUTH
from sandesh.viz.constants import _TABLES, _OBJECT_TABLES,\
_OBJECT_TABLE_SCHEMA, _OBJECT_TABLE_COLUMN_VALUES, \
_STAT_TABLES, STAT_OBJECTID_FIELD, STAT_VT_PREFIX, \
STAT_TIME_FIELD, STAT_TIMEBIN_FIELD, STAT_UUID_FIELD, \
STAT_SOURCE_FIELD, SOURCE, MODULE
from sandesh.viz.constants import *
from sandesh.analytics.ttypes import *
from sandesh.nodeinfo.ttypes import NodeStatusUVE, NodeStatus
from sandesh.nodeinfo.cpuinfo.ttypes import *
from sandesh.nodeinfo.process_info.ttypes import *
from sandesh.discovery.ttypes import CollectorTrace
import discoveryclient.client as discovery_client
from opserver_util import OpServerUtils
from opserver_util import ServicePoller
from sandesh_req_impl import OpserverSandeshReqImpl
from sandesh.analytics_database.ttypes import *
from sandesh.analytics_database.constants import PurgeStatusString
from overlay_to_underlay_mapper import OverlayToUnderlayMapper, \
OverlayToUnderlayMapperError
from generator_introspect_util import GeneratorIntrospectUtil
from stevedore import hook, extension
from partition_handler import PartInfo, UveStreamer, UveCacheProcessor
from functools import wraps
from vnc_cfg_api_client import VncCfgApiClient
from opserver_local import LocalApp
from sandesh.analytics_api_info.ttypes import UVEDbCacheTablesRequest, \
UVEDbCacheTable, UVEDbCacheTablesResponse, UVEDbCacheTableKeysRequest, \
UVEDbCacheTableKey, UVEDbCacheTableKeysResponse, \
UVEDbCacheUveRequest, UVEDbCacheUveResponse
_ERRORS = {
errno.EBADMSG: 400,
errno.ENOBUFS: 403,
errno.EINVAL: 404,
errno.ENOENT: 410,
errno.EIO: 500,
errno.EBUSY: 503
}
@bottle.error(400)
@bottle.error(403)
@bottle.error(404)
@bottle.error(410)
@bottle.error(500)
@bottle.error(503)
def opserver_error(err):
return err.body
#end opserver_error
class LinkObject(object):
def __init__(self, name, href):
self.name = name
self.href = href
# end __init__
# end class LinkObject
class OpserverStdLog(object):
def __init__(self, server_name, http_port):
self._server_name = server_name
self._port = http_port
def write(self, text):
sys.stderr.write('[' + self._server_name + ':' + str(self._port) + ']' + text)
class ContrailGeventServer(bottle.GeventServer):
def run(self, handler):
from gevent import wsgi as wsgi_fast, pywsgi, monkey, local
if self.options.get('monkey', True):
import threading
if not threading.local is local.local: monkey.patch_all()
wsgi = wsgi_fast if self.options.get('fast') else pywsgi
self._std_log = OpserverStdLog("API", self.port)
self.srv = wsgi.WSGIServer((self.host, self.port), handler, log = self._std_log)
self.srv.serve_forever()
def stop(self):
if hasattr(self, 'srv'):
self.srv.stop()
gevent.sleep(0)
def obj_to_dict(obj):
# Non-null fields in object get converted to json fields
return dict((k, v) for k, v in obj.__dict__.iteritems())
# end obj_to_dict
def redis_query_start(host, port, redis_password, qid, inp, columns):
redish = redis.StrictRedis(db=0, host=host, port=port,
password=redis_password)
for key, value in inp.items():
redish.hset("QUERY:" + qid, key, json.dumps(value))
col_list = []
if columns is not None:
for col in columns:
m = TableSchema(name = col.name, datatype = col.datatype, index = col.index, suffixes = col.suffixes)
col_list.append(m._asdict())
query_metadata = {}
query_metadata['enqueue_time'] = OpServerUtils.utc_timestamp_usec()
redish.hset("QUERY:" + qid, 'query_metadata', json.dumps(query_metadata))
redish.hset("QUERY:" + qid, 'enqueue_time',
OpServerUtils.utc_timestamp_usec())
redish.hset("QUERY:" + qid, 'table_schema', json.dumps(col_list))
redish.lpush("QUERYQ", qid)
res = redish.blpop("REPLY:" + qid, 10)
if res is None:
return None
# Put the status back on the queue for the use of the status URI
redish.lpush("REPLY:" + qid, res[1])
resp = json.loads(res[1])
return int(resp["progress"])
# end redis_query_start
def redis_query_status(host, port, redis_password, qid):
redish = redis.StrictRedis(db=0, host=host, port=port,
password=redis_password)
resp = {"progress": 0}
chunks = []
# For now, the number of chunks will be always 1
res = redish.lrange("REPLY:" + qid, -1, -1)
if not res:
return None
chunk_resp = json.loads(res[0])
ttl = redish.ttl("REPLY:" + qid)
if int(ttl) != -1:
chunk_resp["ttl"] = int(ttl)
query_time = redish.hmget("QUERY:" + qid, ["start_time", "end_time"])
chunk_resp["start_time"] = query_time[0]
chunk_resp["end_time"] = query_time[1]
if chunk_resp["progress"] == 100:
chunk_resp["href"] = "/analytics/query/%s/chunk-final/%d" % (qid, 0)
chunks.append(chunk_resp)
resp["progress"] = chunk_resp["progress"]
resp["chunks"] = chunks
return resp
# end redis_query_status
def redis_query_chunk_iter(host, port, redis_password, qid, chunk_id):
redish = redis.StrictRedis(db=0, host=host, port=port,
password=redis_password)
iters = 0
fin = False
while not fin:
#import pdb; pdb.set_trace()
# Keep the result line valid while it is being read
redish.persist("RESULT:" + qid + ":" + str(iters))
elems = redish.lrange("RESULT:" + qid + ":" + str(iters), 0, -1)
yield elems
if elems == []:
fin = True
else:
redish.delete("RESULT:" + qid + ":" + str(iters), 0, -1)
iters += 1
return
# end redis_query_chunk_iter
def redis_query_chunk(host, port, redis_password, qid, chunk_id):
res_iter = redis_query_chunk_iter(host, port, redis_password, qid, chunk_id)
dli = u''
starter = True
fin = False
yield u'{"value": ['
outcount = 0
while not fin:
#import pdb; pdb.set_trace()
# Keep the result line valid while it is being read
elems = res_iter.next()
fin = True
for elem in elems:
fin = False
outcount += 1
if starter:
dli += '\n' + elem
starter = False
else:
dli += ', ' + elem
if not fin:
yield dli + '\n'
dli = u''
if outcount == 0:
yield '\n' + u']}'
else:
yield u']}'
return
# end redis_query_chunk
def redis_query_result(host, port, redis_password, qid):
try:
status = redis_query_status(host, port, redis_password, qid)
except redis.exceptions.ConnectionError:
yield bottle.HTTPError(_ERRORS[errno.EIO],
'Failure in connection to the query DB')
except Exception as e:
self._logger.error("Exception: %s" % e)
yield bottle.HTTPError(_ERRORS[errno.EIO], 'Error: %s' % e)
else:
if status is None:
yield bottle.HTTPError(_ERRORS[errno.ENOENT],
'Invalid query id (or) query result purged from DB')
if status['progress'] == 100:
for chunk in status['chunks']:
chunk_id = int(chunk['href'].rsplit('/', 1)[1])
for gen in redis_query_chunk(host, port, redis_password, qid,
chunk_id):
yield gen
else:
yield {}
return
# end redis_query_result
def redis_query_result_dict(host, port, redis_password, qid):
stat = redis_query_status(host, port, redis_password, qid)
prg = int(stat["progress"])
res = []
if (prg < 0) or (prg == 100):
done = False
gen = redis_query_result(host, port, redis_password, qid)
result = u''
while not done:
try:
result += gen.next()
#import pdb; pdb.set_trace()
except StopIteration:
done = True
res = (json.loads(result))['value']
return prg, res
# end redis_query_result_dict
def redis_query_info(redish, qid):
query_data = {}
query_dict = redish.hgetall('QUERY:' + qid)
query_metadata = json.loads(query_dict['query_metadata'])
del query_dict['query_metadata']
query_data['query_id'] = qid
query_data['query'] = str(query_dict)
query_data['enqueue_time'] = query_metadata['enqueue_time']
return query_data
# end redis_query_info
class OpStateServer(object):
def __init__(self, logger, redis_password=None):
self._logger = logger
self._redis_list = []
self._redis_password= redis_password
# end __init__
def update_redis_list(self, redis_list):
self._redis_list = redis_list
# end update_redis_list
def redis_publish(self, msg_type, destination, msg):
# Get the sandesh encoded in XML format
sandesh = SandeshWriter.encode_sandesh(msg)
msg_encode = base64.b64encode(sandesh)
redis_msg = '{"type":"%s","destination":"%s","message":"%s"}' \
% (msg_type, destination, msg_encode)
# Publish message in the Redis bus
for redis_server in self._redis_list:
redis_inst = redis.StrictRedis(redis_server[0],
redis_server[1], db=0,
password=self._redis_password)
try:
redis_inst.publish('analytics', redis_msg)
except redis.exceptions.ConnectionError:
# Update connection info
ConnectionState.update(conn_type = ConnectionType.REDIS_UVE,
name = 'UVE', status = ConnectionStatus.DOWN,
message = 'Connection Error',
server_addrs = ['%s:%d' % (redis_server[0], \
redis_server[1])])
self._logger.error('No Connection to Redis [%s:%d].'
'Failed to publish message.' \
% (redis_server[0], redis_server[1]))
return True
# end redis_publish
# end class OpStateServer
class AnalyticsApiStatistics(object):
def __init__(self, sandesh, obj_type):
self.obj_type = obj_type
self.time_start = UTCTimestampUsec()
self.api_stats = None
self.sandesh = sandesh
def collect(self, resp_size, resp_size_bytes):
time_finish = UTCTimestampUsec()
useragent = bottle.request.headers.get('X-Contrail-Useragent')
if not useragent:
useragent = bottle.request.headers.get('User-Agent')
# Create api stats object
self.api_stats = AnalyticsApiSample(
operation_type=bottle.request.method,
remote_ip=bottle.request.environ.get('REMOTE_ADDR'),
request_url=bottle.request.url,
object_type=self.obj_type,
response_time_in_usec=(time_finish - self.time_start),
response_size_objects=resp_size,
response_size_bytes=resp_size_bytes,
resp_code='200',
useragent=useragent,
node=self.sandesh.source_id())
def sendwith(self):
stats_log = AnalyticsApiStats(api_stats=self.api_stats,
sandesh=self.sandesh)
stats_log.send(sandesh=self.sandesh)
class OpServer(object):
"""
This class provides ReST API to get operational state of
Contrail VNS system.
The supported **GET** APIs are:
* ``/analytics/virtual-network/<name>``
* ``/analytics/virtual-machine/<name>``
* ``/analytics/vrouter/<name>``:
* ``/analytics/bgp-router/<name>``
* ``/analytics/bgp-peer/<name>``
* ``/analytics/xmpp-peer/<name>``
* ``/analytics/collector/<name>``
* ``/analytics/tables``:
* ``/analytics/table/<table>``:
* ``/analytics/table/<table>/schema``:
* ``/analytics/table/<table>/column-values``:
* ``/analytics/table/<table>/column-values/<column>``:
* ``/analytics/query/<queryId>``
* ``/analytics/query/<queryId>/chunk-final/<chunkId>``
* ``/analytics/send-tracebuffer/<source>/<module>/<name>``
* ``/analytics/operation/analytics-data-start-time``
The supported **POST** APIs are:
* ``/analytics/query``:
* ``/analytics/operation/database-purge``:
"""
def disc_publish(self):
data = {
'ip-address': self._args.host_ip,
'port': self._args.rest_api_port,
}
self.disc.set_sandesh(self._sandesh)
self._logger.info("Disc Publish to %s : %d - %s"
% (self._args.disc_server_ip,
self._args.disc_server_port, str(data)))
self.disc.publish(ANALYTICS_API_SERVER_DISCOVERY_SERVICE_NAME, data)
# end disc_publish
def validate_user_token(func):
@wraps(func)
def _impl(self, *f_args, **f_kwargs):
if self._args.auth_conf_info.get('cloud_admin_access_only') and \
bottle.request.app == bottle.app():
user_token = bottle.request.headers.get('X-Auth-Token')
if not user_token or not \
self._vnc_api_client.is_role_cloud_admin(user_token):
raise bottle.HTTPResponse(status = 401,
body = 'Authentication required',
headers = self._reject_auth_headers())
return func(self, *f_args, **f_kwargs)
return _impl
# end validate_user_token
def _reject_auth_headers(self):
header_val = 'Keystone uri=\'%s\'' % \
self._args.auth_conf_info.get('auth_uri')
return { "WWW-Authenticate" : header_val }
def __init__(self, args_str=' '.join(sys.argv[1:])):
self.gevs = []
self._args = None
self._usecache = True
self._parse_args(args_str)
print args_str
self._homepage_links = []
self._homepage_links.append(
LinkObject('documentation', '/documentation/index.html'))
self._homepage_links.append(
LinkObject('Message documentation', '/documentation/messages/index.html'))
self._homepage_links.append(LinkObject('analytics', '/analytics'))
super(OpServer, self).__init__()
self._webserver = None
module = Module.OPSERVER
self._moduleid = ModuleNames[module]
node_type = Module2NodeType[module]
self._node_type_name = NodeTypeNames[node_type]
if self._args.worker_id:
self._instance_id = self._args.worker_id
else:
self._instance_id = INSTANCE_ID_DEFAULT
self.table = "ObjectCollectorInfo"
self._hostname = socket.gethostname()
if self._args.dup:
self._hostname += 'dup'
self._sandesh = Sandesh()
opserver_sandesh_req_impl = OpserverSandeshReqImpl(self)
# Reset the sandesh send rate limit value
if self._args.sandesh_send_rate_limit is not None:
SandeshSystem.set_sandesh_send_rate_limit( \
self._args.sandesh_send_rate_limit)
self.disc = None
if self._args.disc_server_ip:
dss_kwargs = {}
if self._args.disc_server_ssl:
dss_kwargs.update(
{'cert' : self._args.disc_server_cert,
'key' : self._args.disc_server_key,
'cacert' : self._args.disc_server_cacert})
self.disc = discovery_client.DiscoveryClient(
self._args.disc_server_ip,
self._args.disc_server_port,
ModuleNames[Module.OPSERVER],
**dss_kwargs)
self._sandesh.init_generator(
self._moduleid, self._hostname, self._node_type_name,
self._instance_id, self._args.collectors, 'opserver_context',
int(self._args.http_server_port), ['opserver.sandesh'],
self.disc, 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,
file=self._args.log_file,
enable_syslog=self._args.use_syslog,
syslog_facility=self._args.syslog_facility)
ConnectionState.init(self._sandesh, self._hostname, self._moduleid,
self._instance_id,
staticmethod(ConnectionState.get_process_state_cb),
NodeStatusUVE, NodeStatus, self.table)
self._uvepartitions_state = None
# Trace buffer list
self.trace_buf = [
{'name':'DiscoveryMsg', 'size':1000}
]
# Create trace buffers
for buf in self.trace_buf:
self._sandesh.trace_buffer_create(name=buf['name'], size=buf['size'])
self._logger = self._sandesh._logger
self._get_common = self._http_get_common
self._put_common = self._http_put_common
self._delete_common = self._http_delete_common
self._post_common = self._http_post_common
self._collector_pool = None
self._state_server = OpStateServer(self._logger, self._args.redis_password)
body = gevent.queue.Queue()
self._vnc_api_client = None
if self._args.auth_conf_info.get('cloud_admin_access_only'):
self._vnc_api_client = VncCfgApiClient(self._args.auth_conf_info,
self._sandesh, self._logger)
self._uvedbstream = UveStreamer(self._logger, None, None,
self.get_agp, self._args.redis_password)
# On olders version of linux, kafka cannot be
# relied upon. DO NOT use it to serve UVEs
(PLATFORM, VERSION, EXTRA) = platform.linux_distribution()
if PLATFORM.lower() == 'ubuntu':
if VERSION.find('12.') == 0:
self._usecache = False
if PLATFORM.lower() == 'centos':
if VERSION.find('6.') == 0:
self._usecache = False
if self._args.partitions == 0:
self._usecache = False
if not self._usecache:
self._logger.error("NOT using UVE Cache")
else:
self._logger.error("Initializing UVE Cache")
self._uve_server = UVEServer(('127.0.0.1',
self._args.redis_server_port),
self._logger,
self._args.redis_password,
self._uvedbstream, self._usecache)
self._LEVEL_LIST = []
for k in SandeshLevel._VALUES_TO_NAMES:
if (k < SandeshLevel.UT_START):
d = {}
d[k] = SandeshLevel._VALUES_TO_NAMES[k]
self._LEVEL_LIST.append(d)
self._CATEGORY_MAP =\
dict((ModuleNames[k], [CategoryNames[ce] for ce in v])
for k, v in ModuleCategoryMap.iteritems())
self.agp = {}
if self._usecache:
ConnectionState.update(conn_type = ConnectionType.UVEPARTITIONS,
name = 'UVE-Aggregation', status = ConnectionStatus.INIT)
self._uvepartitions_state = ConnectionStatus.INIT
else:
ConnectionState.update(conn_type = ConnectionType.UVEPARTITIONS,
name = 'UVE-Aggregation', status = ConnectionStatus.UP)
self._uvepartitions_state = ConnectionStatus.UP
if self._args.disc_server_ip:
self.disc_publish()
else:
for part in range(0,self._args.partitions):
pi = PartInfo(ip_address = self._args.host_ip,
acq_time = UTCTimestampUsec(),
instance_id = "0",
port = self._args.redis_server_port)
self.agp[part] = pi
self.redis_uve_list = []
try:
if type(self._args.redis_uve_list) is str:
self._args.redis_uve_list = self._args.redis_uve_list.split()
for redis_uve in self._args.redis_uve_list:
redis_ip_port = redis_uve.split(':')
redis_elem = (redis_ip_port[0], int(redis_ip_port[1]),0)
self.redis_uve_list.append(redis_elem)
except Exception as e:
self._logger.error('Failed to parse redis_uve_list: %s' % e)
else:
self._state_server.update_redis_list(self.redis_uve_list)
self._uve_server.update_redis_uve_list(self.redis_uve_list)
ConnectionState.update(conn_type = ConnectionType.UVEPARTITIONS,
name = 'UVE-Aggregation', status = ConnectionStatus.UP,
message = 'Partitions:%d' % self._args.partitions)
self._uvepartitions_state = ConnectionStatus.UP
self._analytics_links = ['uves', 'uve-types', 'tables',
'queries', 'alarms', 'uve-stream', 'alarm-stream']
self._VIRTUAL_TABLES = copy.deepcopy(_TABLES)
listmgrs = extension.ExtensionManager('contrail.analytics.alarms')
for elem in listmgrs:
self._logger.info('Loaded extensions for %s: %s doc %s' % \
(elem.name , elem.entry_point, elem.plugin.__doc__))
for t in _OBJECT_TABLES:
obj = query_table(
name=t, display_name=_OBJECT_TABLES[t].objtable_display_name,
schema=_OBJECT_TABLE_SCHEMA,
columnvalues=_OBJECT_TABLE_COLUMN_VALUES)
self._VIRTUAL_TABLES.append(obj)
stat_tables = []
# read the stat table schemas from vizd first
for t in _STAT_TABLES:
attributes = []
for attr in t.attributes:
suffixes = []
if attr.suffixes:
for suffix in attr.suffixes:
suffixes.append(suffix)
attributes.append({"name":attr.name,"datatype":attr.datatype,"index":attr.index,"suffixes":suffixes})
new_table = {"stat_type":t.stat_type,
"stat_attr":t.stat_attr,
"display_name":t.display_name,
"obj_table":t.obj_table,
"attributes":attributes}
stat_tables.append(new_table)
# read all the _stats_tables.json files for remaining stat table schema
topdir = '/usr/share/doc/contrail-docs/html/messages/'
extn = '_stats_tables.json'
stat_schema_files = []
for dirpath, dirnames, files in os.walk(topdir):
for name in files:
if name.lower().endswith(extn):
stat_schema_files.append(os.path.join(dirpath, name))
for schema_file in stat_schema_files:
with open(schema_file) as data_file:
data = json.load(data_file)
for _, tables in data.iteritems():
for table in tables:
if table not in stat_tables:
stat_tables.append(table)
for table in stat_tables:
stat_id = table["stat_type"] + "." + table["stat_attr"]
scols = []
keyln = stat_query_column(name=STAT_SOURCE_FIELD, datatype='string', index=True)
scols.append(keyln)
tln = stat_query_column(name=STAT_TIME_FIELD, datatype='int', index=False)
scols.append(tln)
tcln = stat_query_column(name="CLASS(" + STAT_TIME_FIELD + ")",
datatype='int', index=False)
scols.append(tcln)
teln = stat_query_column(name=STAT_TIMEBIN_FIELD, datatype='int', index=False)
scols.append(teln)
tecln = stat_query_column(name="CLASS(" + STAT_TIMEBIN_FIELD+ ")",
datatype='int', index=False)
scols.append(tecln)
uln = stat_query_column(name=STAT_UUID_FIELD, datatype='uuid', index=False)
scols.append(uln)
cln = stat_query_column(name="COUNT(" + table["stat_attr"] + ")",
datatype='int', index=False)
scols.append(cln)
isname = False
for aln in table["attributes"]:
if aln["name"]==STAT_OBJECTID_FIELD:
isname = True
if "suffixes" in aln.keys():
aln_col = stat_query_column(name=aln["name"], datatype=aln["datatype"], index=aln["index"], suffixes=aln["suffixes"]);
else:
aln_col = stat_query_column(name=aln["name"], datatype=aln["datatype"], index=aln["index"]);
scols.append(aln_col)
if aln["datatype"] in ['int','double']:
sln = stat_query_column(name= "SUM(" + aln["name"] + ")",
datatype=aln["datatype"], index=False)
scols.append(sln)
scln = stat_query_column(name= "CLASS(" + aln["name"] + ")",
datatype=aln["datatype"], index=False)
scols.append(scln)
sln = stat_query_column(name= "MAX(" + aln["name"] + ")",
datatype=aln["datatype"], index=False)
scols.append(sln)
scln = stat_query_column(name= "MIN(" + aln["name"] + ")",
datatype=aln["datatype"], index=False)
scols.append(scln)
scln = stat_query_column(name= "PERCENTILES(" + aln["name"] + ")",
datatype='percentiles', index=False)
scols.append(scln)
scln = stat_query_column(name= "AVG(" + aln["name"] + ")",
datatype='avg', index=False)
scols.append(scln)
if not isname:
keyln = stat_query_column(name=STAT_OBJECTID_FIELD, datatype='string', index=True)
scols.append(keyln)
sch = query_schema_type(type='STAT', columns=scols)
stt = query_table(
name = STAT_VT_PREFIX + "." + stat_id,
display_name = table["display_name"],
schema = sch,
columnvalues = [STAT_OBJECTID_FIELD, SOURCE])
self._VIRTUAL_TABLES.append(stt)
self._analytics_db = AnalyticsDb(self._logger,
self._args.cassandra_server_list,
self._args.redis_query_port,
self._args.redis_password,
self._args.cassandra_user,
self._args.cassandra_password)
# Register introspect request handlers
UVEDbCacheTablesRequest.handle_request = \
self.handle_UVEDbCacheTablesRequest
UVEDbCacheTableKeysRequest.handle_request = \
self.handle_UVEDbCacheTableKeysRequest
UVEDbCacheUveRequest.handle_request = self.handle_UVEDbCacheUveRequest
bottle.route('/', 'GET', self.homepage_http_get)
bottle.route('/analytics', 'GET', self.analytics_http_get)
bottle.route('/analytics/uves', 'GET', self.uves_http_get)
bottle.route('/analytics/uve-types', 'GET', self.uve_types_http_get)
bottle.route('/analytics/alarms/acknowledge', 'POST',
self.alarms_ack_http_post)
bottle.route('/analytics/query', 'POST', self.query_process)
bottle.route(
'/analytics/query/<queryId>', 'GET', self.query_status_get)
bottle.route('/analytics/query/<queryId>/chunk-final/<chunkId>',
'GET', self.query_chunk_get)
bottle.route('/analytics/queries', 'GET', self.show_queries)
bottle.route('/analytics/tables', 'GET', self.tables_process)
bottle.route('/analytics/operation/database-purge',
'POST', self.process_purge_request)
bottle.route('/analytics/operation/analytics-data-start-time',
'GET', self._get_analytics_data_start_time)
bottle.route('/analytics/table/<table>', 'GET', self.table_process)
bottle.route('/analytics/table/<table>/schema',
'GET', self.table_schema_process)
for i in range(0, len(self._VIRTUAL_TABLES)):
if len(self._VIRTUAL_TABLES[i].columnvalues) > 0:
bottle.route('/analytics/table/<table>/column-values',
'GET', self.column_values_process)
bottle.route('/analytics/table/<table>/column-values/<column>',
'GET', self.column_process)
bottle.route('/analytics/send-tracebuffer/<source>/<module>/<instance_id>/<name>',
'GET', self.send_trace_buffer)
bottle.route('/doc-style.css', 'GET',
self.documentation_messages_css_get)
bottle.route('/documentation/messages/<module>',
'GET', self.documentation_messages_http_get)
bottle.route('/documentation/messages/<module>/<sfilename>',
'GET', self.documentation_messages_http_get)
bottle.route('/documentation/<filename:path>',
'GET', self.documentation_http_get)
bottle.route('/analytics/uve-stream', 'GET', self.uve_stream)
bottle.route('/analytics/alarm-stream', 'GET', self.alarm_stream)
bottle.route('/analytics/uves/<tables>', 'GET', self.dyn_list_http_get)
bottle.route('/analytics/uves/<table>/<name:path>', 'GET', self.dyn_http_get)
bottle.route('/analytics/uves/<tables>', 'POST', self.dyn_http_post)
bottle.route('/analytics/alarms', 'GET', self.alarms_http_get)
# start gevent to monitor disk usage and automatically purge
if (self._args.auto_db_purge):
self.gevs.append(gevent.spawn(self._auto_purge))
# end __init__
def _parse_args(self, args_str=' '.join(sys.argv[1:])):
'''
Eg. python opserver.py --host_ip 127.0.0.1
--redis_server_port 6379
--redis_query_port 6379
--redis_password
--collectors 127.0.0.1:8086
--cassandra_server_list 127.0.0.1:9160
--http_server_port 8090
--rest_api_port 8081
--rest_api_ip 0.0.0.0
--log_local
--log_level SYS_DEBUG
--log_category test
--log_file <stdout>
--use_syslog
--syslog_facility LOG_USER
--worker_id 0
--partitions 15
--redis_uve_list 127.0.0.1:6379
--auto_db_purge
'''
# Source any specified config/ini file
# Turn off help, so we print all options in response to -h
conf_parser = argparse.ArgumentParser(add_help=False)
conf_parser.add_argument("-c", "--conf_file", action='append',
help="Specify config file", metavar="FILE")
args, remaining_argv = conf_parser.parse_known_args(args_str.split())
defaults = {
'host_ip' : "127.0.0.1",
'collectors' : None,
'cassandra_server_list' : ['127.0.0.1:9160'],
'http_server_port' : 8090,
'rest_api_port' : 8081,
'rest_api_ip' : '0.0.0.0',
'log_local' : False,
'log_level' : 'SYS_DEBUG',
'log_category' : '',
'log_file' : Sandesh._DEFAULT_LOG_FILE,
'use_syslog' : False,
'syslog_facility' : Sandesh._DEFAULT_SYSLOG_FACILITY,
'dup' : False,
'redis_uve_list' : ['127.0.0.1:6379'],
'auto_db_purge' : True,
'db_purge_threshold' : 70,
'db_purge_level' : 40,
'analytics_data_ttl' : 48,
'analytics_config_audit_ttl' : -1,
'analytics_statistics_ttl' : -1,
'analytics_flow_ttl' : -1,
'logging_conf': '',
'logger_class': None,
'partitions' : 15,
'sandesh_send_rate_limit': SandeshSystem. \
get_sandesh_send_rate_limit(),
'aaa_mode' : AAA_MODE_CLOUD_ADMIN,
'api_server' : '127.0.0.1:8082',
'admin_port' : OpServerAdminPort,
'cloud_admin_role' : CLOUD_ADMIN_ROLE,
'api_server_use_ssl': False,
'use_aggregated_uve_db' : 'true',
}
redis_opts = {
'redis_server_port' : 6379,
'redis_query_port' : 6379,
'redis_password' : None,
}
disc_opts = {
'disc_server_ip' : None,
'disc_server_port' : 5998,
'disc_server_ssl' : False,
'disc_server_cert' : None,
'disc_server_key' : None,
'disc_server_cacert' : None,
}
cassandra_opts = {
'cassandra_user' : None,
'cassandra_password' : None,
}
keystone_opts = {
'auth_host': '127.0.0.1',
'auth_protocol': 'http',
'auth_port': 35357,
'admin_user': 'admin',
'admin_password': 'contrail123',
'admin_tenant_name': 'default-domain'
}
# read contrail-analytics-api own conf file
config = None
if args.conf_file:
config = ConfigParser.SafeConfigParser()
config.read(args.conf_file)
if 'DEFAULTS' in config.sections():
defaults.update(dict(config.items("DEFAULTS")))
if 'REDIS' in config.sections():
redis_opts.update(dict(config.items('REDIS')))
if 'DISCOVERY' in config.sections():
disc_opts.update(dict(config.items('DISCOVERY')))
if 'disc_server_ssl' in config.options('DISCOVERY'):
disc_opts['disc_server_ssl'] = config.getboolean(
'DISCOVERY', 'disc_server_ssl')
if 'CASSANDRA' in config.sections():
cassandra_opts.update(dict(config.items('CASSANDRA')))
if 'KEYSTONE' in config.sections():
keystone_opts.update(dict(config.items('KEYSTONE')))
# Override with CLI options
# Don't surpress add_help here so it will handle -h
parser = argparse.ArgumentParser(
# Inherit options from config_parser
parents=[conf_parser],
# print script description with -h/--help
description=__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
defaults.update(redis_opts)
defaults.update(disc_opts)
defaults.update(cassandra_opts)
defaults.update(keystone_opts)
defaults.update()
parser.set_defaults(**defaults)
parser.add_argument("--host_ip",
help="Host IP address")
parser.add_argument("--redis_server_port",
type=int,
help="Redis server port")
parser.add_argument("--redis_query_port",
type=int,
help="Redis query port")
parser.add_argument("--redis_password",
help="Redis server password")
parser.add_argument("--collectors",
help="List of Collector IP addresses in ip:port format",
nargs="+")
parser.add_argument("--http_server_port",
type=int,
help="HTTP server port")
parser.add_argument("--rest_api_port",
type=int,
help="REST API port")
parser.add_argument("--rest_api_ip",
help="REST API IP address")
parser.add_argument("--log_local", action="store_true",
help="Enable local logging of sandesh messages")
parser.add_argument(
"--log_level",
help="Severity level for local logging of sandesh messages")
parser.add_argument(
"--log_category",
help="Category filter for local logging of sandesh messages")
parser.add_argument("--log_file",
help="Filename for the logs to be written to")
parser.add_argument("--use_syslog",
action="store_true",
help="Use syslog for logging")
parser.add_argument("--syslog_facility",
help="Syslog facility to receive log lines")
parser.add_argument("--disc_server_ip",
help="Discovery Server IP address")
parser.add_argument("--disc_server_port",
type=int,
help="Discovery Server port")
parser.add_argument("--disc_server_cert",
help="Discovery Server ssl certificate")
parser.add_argument("--disc_server_key",
help="Discovery Server ssl key")
parser.add_argument("--disc_server_cacert",
help="Discovery Server ssl CA certificate")
parser.add_argument("--disc_server_ssl", action="store_true",
help="Discovery service is configured with ssl")
parser.add_argument("--dup", action="store_true",
help="Internal use")
parser.add_argument("--redis_uve_list",
help="List of redis-uve in ip:port format. For internal use only",
nargs="+")
parser.add_argument(
"--worker_id",
help="Worker Id")
parser.add_argument("--cassandra_server_list",
help="List of cassandra_server_ip in ip:port format",
nargs="+")
parser.add_argument("--auto_db_purge", action="store_true",
help="Automatically purge database if disk usage cross threshold")
parser.add_argument(
"--logging_conf",
help=("Optional logging configuration file, default: None"))
parser.add_argument(
"--logger_class",
help=("Optional external logger class, default: None"))
parser.add_argument("--cassandra_user",
help="Cassandra user name")
parser.add_argument("--cassandra_password",
help="Cassandra password")
parser.add_argument("--partitions", type=int,
help="Number of partitions for hashing UVE keys")
parser.add_argument("--sandesh_send_rate_limit", type=int,
help="Sandesh send rate limit in messages/sec")
parser.add_argument("--cloud_admin_role",
help="Name of cloud-admin role")
parser.add_argument("--aaa_mode", choices=APIAAAModes,
help="AAA mode")
parser.add_argument("--auth_host",
help="IP address of keystone server")
parser.add_argument("--auth_protocol",
help="Keystone authentication protocol")
parser.add_argument("--auth_port", type=int,
help="Keystone server port")