summaryrefslogtreecommitdiffstats
path: root/tests/blueprints/tosca-vnfd-hello-ves/monitor.py
blob: b34bed95f570010d10a45199601ba24a86e255e6 (plain)
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
#!/usr/bin/env python
#
# Copyright 2016 AT&T Intellectual Property, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# What this is: Monitor and closed-loop policy agent as part of the OPNFV VES 
# vHello_VES demo. 
#
# Status: this is a work in progress, under test.

from wsgiref.simple_server import make_server, WSGIRequestHandler
import sys
import os
import platform
import traceback
import time
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import ConfigParser
import logging.handlers
from base64 import b64decode
import string
import json
import jsonschema
import select

monitor_mode = "f"
vdu_id = ['','','','']
summary_e = ['***** Summary of key stats *****','','','']
summary_c = ['Collectd agents:']
status = ['','Started','Started','Started']
base_url = ''
template_404 = b'''POST {0}'''
columns = 0
rows = 0

class JSONObject:
  def __init__(self, d):
    self.__dict__ = d

class NoLoggingWSGIRequestHandler(WSGIRequestHandler):
  def log_message(self, format, *args):
    pass

base_url = ''
template_404 = b'''POST {0}'''

def notfound_404(environ, start_response):
  print('Unexpected URL/Method: {0} {1}'.format(
                                           environ['REQUEST_METHOD'].upper(),
                                           environ['PATH_INFO']))
  start_response('404 Not Found', [ ('Content-type', 'text/plain') ])
  return [template_404.format(base_url)]

class PathDispatcher:
  def __init__(self):
    self.pathmap = { }

  def __call__(self, environ, start_response):
    #----------------------------------------------------------------------
    # Extract the method and path from the environment.
    #----------------------------------------------------------------------
    method = environ['REQUEST_METHOD'].lower()
    path = environ['PATH_INFO']

    #----------------------------------------------------------------------
    # See if we have a handler for this path, and if so invoke it.
    # Otherwise, return a 404.
    #----------------------------------------------------------------------
    handler = self.pathmap.get((method, path), notfound_404)
    return handler(environ, start_response)

  def register(self, method, path, function):
    print('Registering for {0} at {1}'.format(method, path))
    self.pathmap[method.lower(), path] = function
    return function

#--------------------------------------------------------------------------
# Event processing
#--------------------------------------------------------------------------
def process_event(e):
  global status
  global summary_e
  global summary_c
  global vdu_id
  vdu = 0


  epoch = e.event.commonEventHeader.lastEpochMicrosec
  sourceId = e.event.commonEventHeader.sourceId

  report_time = time.strftime('%Y-%m-%d %H:%M:%S', 
                  time.localtime(int(epoch)/1000000))

  host = e.event.commonEventHeader.reportingEntityName
  if 'VDU1' in host or 'vdu1' in host: vdu = 1
  if 'VDU2' in host or 'vdu2' in host: vdu = 2
  if 'VDU3' in host or 'vdu3' in host: vdu = 3
  
  domain = e.event.commonEventHeader.domain

  if domain == 'measurementsForVfScaling':
    if vdu >= 1:
      requestRate = e.event.measurementsForVfScaling.requestRate
      summary_e[vdu] = host + ": state=" + status[vdu] + ", tps=" + str(requestRate)
    else:
      aggregateCpuUsage = e.event.measurementsForVfScalingFields.aggregateCpuUsage
      vNicUsageArray = e.event.measurementsForVfScalingFields.vNicUsageArray
      s = ""
      for i in range(1,len(vdu_id)):
        if sourceId.upper() in vdu_id[i].upper():
          s = "(VDU"+ str(i) + ") "
      if s:
        s += host + ": cpu=" + str(aggregateCpuUsage)
        found = False
        for i in range(1,len(summary_c)):
          if host in summary_c[i]:
            summary_c[i] = s
            found = True
            break
        if not found:
          summary_c.extend([s])

  for s in summary_e:
    print '{0}'.format(s)
  for s in summary_c:
    print '{0}'.format(s)

  if domain == 'fault' and vdu >= 1:
    alarmCondition = e.event.faultFields.alarmCondition
    specificProblem = e.event.faultFields.specificProblem
#    status[vdu] = e.event.faultFields.vfStatus
    status[vdu] = e.event.faultFields.specificProblem

#--------------------------------------------------------------------------
# Main monitoring and logging procedure
#--------------------------------------------------------------------------
def ves_monitor(environ, start_response):

  # Check for keyboard input
  if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
    line = sys.stdin.readline()
    if "f" in line: monitor_mode = "f"
    if "c" in line: monitor_mode = "c"

  print('==== ' + time.asctime() + ' ' + '=' * 49)

  #--------------------------------------------------------------------------
  # Extract the content from the request.
  #--------------------------------------------------------------------------
  length = int(environ.get('CONTENT_LENGTH', '0'))
  body = environ['wsgi.input'].read(length)

  mode, b64_credentials = string.split(environ.get('HTTP_AUTHORIZATION',
                                                     'None None'))
  if (b64_credentials != 'None'):
      credentials = b64decode(b64_credentials)
  else:
      credentials = None

  #--------------------------------------------------------------------------
  # See whether the user authenticated themselves correctly.
  #--------------------------------------------------------------------------
  if (credentials == (vel_username + ':' + vel_password)):
    start_response('204 No Content', [])
    yield ''
  else:
    print('Failed to authenticate agent')
    start_response('401 Unauthorized', [ ('Content-type',
                                          'application/json')])
    req_error = { 'requestError': {
                    'policyException': {
                      'messageId': 'POL0001',
                       'text': 'Failed to authenticate'
                    }
                  }
                }
    yield json.dumps(req_error)

  #--------------------------------------------------------------------------
  # Decode the JSON body
  #--------------------------------------------------------------------------

  try:
    decoded_body = json.loads(body)
    print('{0}'.format(json.dumps(decoded_body,
                                sort_keys=True,
                                indent=4,
                                separators=(',', ': '))))
    decoded_body = json.loads(body, object_hook=JSONObject)
    process_event(decoded_body)

  except Exception as e:
    print('JSON body is not valid for unexpected reason! {0}'.format(e))

def main(argv=None):
  global columns
  global rows

  a,b = os.popen('stty size', 'r').read().split()
  rows = int(a)
  columns = int(b)

  if argv is None:
    argv = sys.argv
  else:
    sys.argv.extend(argv)

  try:
    #----------------------------------------------------------------------
    # Setup argument parser so we can parse the command-line.
    #----------------------------------------------------------------------
    parser = ArgumentParser(description='',
                            formatter_class=ArgumentDefaultsHelpFormatter)
    parser.add_argument('-v', '--verbose',
                        dest='verbose',
                        action='count',
                        help='set verbosity level')
    parser.add_argument('-V', '--version',
                        action='version',
                        version='1.0',
                        help='Display version information')
    parser.add_argument('-c', '--config',
                        dest='config',
                        default='/etc/opt/att/collector.conf',
                        help='Use this config file.',
                        metavar='<file>')
    parser.add_argument('-s', '--section',
                        dest='section',
                        default='default',
                        metavar='<section>',
                        help='section to use in the config file')

    #----------------------------------------------------------------------
    # Process arguments received.
    #----------------------------------------------------------------------
    args = parser.parse_args()
    verbose = args.verbose
    config_file = args.config
    config_section = args.section
    #----------------------------------------------------------------------
    # Now read the config file, using command-line supplied values as
    # overrides.
    #----------------------------------------------------------------------
    defaults = {'log_file': 'ves.log',
                'vel_port': '30000',
                'vel_path': '',
                'vel_topic_name': ''
               }
    overrides = {}
    config = ConfigParser.SafeConfigParser(defaults)
    config.read(config_file)

    #----------------------------------------------------------------------
    # extract the values we want.
    #----------------------------------------------------------------------
    log_file = config.get(config_section, 'log_file', vars=overrides)
    vel_port = config.get(config_section, 'vel_port', vars=overrides)
    vel_path = config.get(config_section, 'vel_path', vars=overrides)
    vel_topic_name = config.get(config_section,
                                'vel_topic_name',
                                vars=overrides)
    global vel_username
    global vel_password
    global vdu_id
    vel_username = config.get(config_section,
                              'vel_username',
                              vars=overrides)
    vel_password = config.get(config_section,
                              'vel_password',
                              vars=overrides)
    vel_schema_file = config.get(config_section,
                                 'schema_file',
                                 vars=overrides)
    base_schema_file = config.get(config_section,
                             'base_schema_file',
                              vars=overrides)
    vdu_id[1] = config.get(config_section,
                           'vdu1_id',
                            vars=overrides)
    vdu_id[2] = config.get(config_section,
                           'vdu2_id',
                            vars=overrides)
    vdu_id[3] = config.get(config_section,
                           'vdu3_id',
                            vars=overrides)
    base_schema_file = config.get(config_section,
                             'base_schema_file',
                              vars=overrides)

    #----------------------------------------------------------------------
    # Perform some basic error checking on the config.
    #----------------------------------------------------------------------
    if (int(vel_port) < 1024 or int(vel_port) > 65535):
      raise RuntimeError('Invalid Vendor Event Listener port ({0}) '
                         'specified'.format(vel_port))

    if (len(vel_path) > 0 and vel_path[-1] != '/'):
      vel_path += '/'

    #----------------------------------------------------------------------
    # Load up the vel_schema and base_schema, if they exist.
    #----------------------------------------------------------------------
    if (os.path.exists(vel_schema_file)):
        global vel_schema
        vel_schema = json.load(open(vel_schema_file, 'r'))
        if (os.path.exists(base_schema_file)):
          base_schema = json.load(open(base_schema_file, 'r'))
          vel_schema.update(base_schema)

    #----------------------------------------------------------------------
    # We are now ready to get started with processing. Start-up the various
    # components of the system in order:
    #
    #  1) Create the dispatcher.
    #  2) Register the functions for the URLs of interest.
    #  3) Run the webserver.
    #----------------------------------------------------------------------
    root_url = '/{0}eventListener/v{1}{2}'.format(vel_path,
                                               '1',
                                               '/' + vel_topic_name
                                                 if len(vel_topic_name) > 0
                                                 else '')

    base_url = root_url
    dispatcher = PathDispatcher()
    dispatcher.register('GET', root_url, ves_monitor)
    dispatcher.register('POST', root_url, ves_monitor)
    httpd = make_server('', 30000, dispatcher, handler_class=NoLoggingWSGIRequestHandler)
    httpd.serve_forever()

    return 0

  except Exception as e:
    #----------------------------------------------------------------------
    # Handle unexpected exceptions.
    #----------------------------------------------------------------------
    indent = len('VES Monitor') * ' '
    sys.stderr.write('VES Monitor: ' + repr(e) + '\n')
    sys.stderr.write(indent + '  for help use --help\n')
    sys.stderr.write(traceback.format_exc())
    return 2

#------------------------------------------------------------------------------
# MAIN SCRIPT ENTRY POINT.
#------------------------------------------------------------------------------
if __name__ == '__main__':
    sys.exit(main())