def display_sys(cls, header=False): try: width = 60 if not header: print BG_WHITE + "|%s|" % ('-' * width).ljust(width) + ENDC print '| SYSTEM INFO | TIME : ' + SYS.last_check_time.split('.')[0] + \ ("{0:>" + str(width - len(SYS.last_check_time.split('.')[0]) - len('SYSTEM INFO | TIME : ')) + "}").format('|') + ENDC print BG_WHITE + "|%s|" % ('-' * width).ljust(width) + ENDC sorted_list = sorted(SYS.sys_list.keys()) for sys in sorted_list: str_status = 'OK' status_list = (dict)(SYS.sys_list[sys]).values() for status in status_list: if (status == 'none'): str_status = 'loading' break elif not (status == 'ok' or status == 'normal'): str_status = 'NOK' break color = GREEN if status is not 'OK': color = RED print '| ' + sys.ljust(6) + ' [' + color + str_status + BG_WHITE + ']' + \ ("{0:>" + str(width - 6 - len(str_status) - 3) + "}").format('|') + ENDC print BG_WHITE + "|%s|" % ('-' * width).ljust(width) + ENDC except: LOG.exception_err_write()
def draw_event(cls, type='default'): try: warn_color = curses.color_pair(3) box_event = curses.newwin(3, MAIN_WIDTH, SYS.get_sys_line_count() + 3, 1) box_event.box() normalText = curses.A_NORMAL box_event.addstr(0, 22, ' EVENT ', normalText) if type == 'disconnect': box_event.addstr(1, 2, '[Server shutdown] check server and restart', warn_color) elif type == 'rest_warn': box_event.addstr(1, 2, '[Rest failure] check client and restart', warn_color) else: # if occur event if SYS.abnormal_flag: str = '[Event occurred]' box_event.addstr(1, 2, str, warn_color) box_event.addstr(1, 2 + len(str), ' Check the event history.', normalText) else: str = '[Event] normal' box_event.addstr(1, 2, str, normalText) box_event.refresh() except: LOG.exception_err_write()
def draw_select(menu_list, selected_menu_no): box_type = curses.newwin( len(menu_list) + 2, MAIN_WIDTH, SYS.get_sys_line_count() + 3 + 3, 1) box_type.box() try: highlightText = curses.color_pair(1) normalText = curses.A_NORMAL box_type.addstr(0, MAIN_CENTER - 3, ' MENU ', normalText) for i in range(1, len(menu_list) + 1): if i is selected_menu_no: box_type.addstr(i, 2, str(i) + "." + menu_list[i - 1], highlightText) else: box_type.addstr(i, 2, str(i) + "." + menu_list[i - 1], normalText) except: LOG.exception_err_write() return box_type
def display_event(cls): try: sorted_list = sorted(SYS.sys_list.keys()) title = (' system'.ljust(13)) for sys in sorted_list: item_list = (dict)(SYS.sys_list[sys]).keys() for item in item_list: title = title + item.ljust(10) break width = len(title) print BG_WHITE + "|%s|" % ('-' * width).ljust(width) + ENDC print '| SYSTEM INFO | TIME : ' + SYS.last_check_time.split('.')[0] + \ ("{0:>" + str(width - len(SYS.last_check_time.split('.')[0]) - len('SYSTEM INFO | TIME : ')) + "}").format('|') + ENDC print BG_WHITE + "|%s|" % ('-' * width).ljust(width) + ENDC print '|' + title + '|' print BG_WHITE + "|%s|" % ('-' * width).ljust(width) + ENDC for sys in sorted_list: line = (' ' + sys).ljust(13) status_list = (dict)(SYS.sys_list[sys]).values() for status in status_list: line = line + status.ljust(10) print '|' + line + '|' print BG_WHITE + "|%s|" % ('-' * width).ljust(width) + ENDC except: LOG.exception_err_write()
def send_trace(cls, ip, condition): try: # req trace cls.TRACE_LOG.trace_log('START TRACE | ip = ' + ip + ', condition = ' + condition) except: LOG.exception_err_write()
def display_status(cls): onos_list = ['TYPE', 'IP'] + ONOS_STATUS_ITEMS try: print '' cls.draw_grid('ONOS', onos_list) except: LOG.exception_err_write()
def set_search_list(cls): try: for cmd in cls.command_list: cls.cli_search_list.append(cmd) cls.cli_validate_list.append(cmd) if (CONFIG.get_config_instance().has_section(cmd)): opt_list = CONFIG.cli_get_value(cmd, CONFIG.get_cmd_opt_key_name()) tmp = [] for opt in opt_list.split(','): tmp.append(opt.strip()) cls.cli_validate_list.append(cmd + ' ' + opt.strip()) cls.cli_search_list_sub[cmd] = tmp cls.cli_search_list.append('menu') cls.cli_search_list.append('quit') cls.cli_search_list.append('exit') cls.cli_search_list.append('sys') cls.cli_search_list.append('dis-system') cls.cli_search_list.append('help') tmp_sys = [] tmp_sys.append('all') cls.cli_validate_list.append('sys all') for onos_name in SYS.get_sys_list(): tmp_sys.append(onos_name) cls.cli_validate_list.append('sys ' + onos_name) cls.cli_search_list_sub['sys'] = tmp_sys except: LOG.exception_err_write()
def start_trace(self, saved_data, real_data): try: if (len(self.data['COMPUTE'].strip()) == 0): self._scene.add_effect(PopUpDialog(self._screen, "Please enter a compute node name.", ["OK"])) return if not (TRACE.compute_list.has_key(self.data['COMPUTE'].strip())): self._scene.add_effect( PopUpDialog(self._screen, 'No ' + self.data["COMPUTE"].strip() + '(COMPUTE NODE) registered', ["OK"])) return if len(saved_data) == 0: self._scene.add_effect(PopUpDialog(self._screen, "Please enter a flow-trace condition.", ["OK"])) return num = len(self.trace_history) + 1 data = (saved_data, num) self.trace_history.insert(0, data) self.real_trace.append(real_data) self._list_view.value = len(self.trace_history) cmd_rt = TRACE.exec_trace(TRACE.compute_id, TRACE.compute_list[self.data['COMPUTE'].strip()], real_data) self._trace_result.value = cmd_rt except: LOG.exception_err_write()
def call_cli(): try: SCREEN.display_header('CLI') readline.set_completer(CLI.pre_complete_cli) while True: # mac OS if 'libedit' in readline.__doc__: CLI.modify_flag = True CLI.save_buffer = readline.get_line_buffer() # select_command (handling tab event) cmd = CLI.input_cmd() if CLI.is_menu(cmd): SCREEN.cli_flag = False return elif CLI.is_exit(cmd): SCREEN.set_exit() return else: # send command CLI.process_cmd(cmd) while not CLI.get_cli_ret_flag(): time.sleep(1) except: LOG.exception_err_write()
def pre_complete_cli(cls, text, state): try: BUFFER = readline.get_line_buffer() argtemp = [] if BUFFER != "": i = -1 while i != BUFFER.count(" "): if BUFFER.count(" ") >= 0: if BUFFER.count(" ") == 0: return cls.complete_cli(text, state, cls.get_cli_search_list()) else: # mac OS if 'libedit' in readline.__doc__: if cls.modify_flag: if cls.save_buffer != BUFFER: cls.modify_flag = False else: return cls.complete_cli( text, state, cls.get_cli_search_list()) index = 0 cmd = [] while cls.complete_cli(BUFFER.split()[0], index, cls.get_cli_search_list()): cmd.append( cls.complete_cli( BUFFER.split()[0], index, cls.get_cli_search_list())) index = index + 1 if len(cmd) == 1: cmd = cmd[0] if BUFFER.count(" ") >= 1: if BUFFER.count(" ") == 1: cmd = BUFFER.split()[0] if cls.cli_search_list_sub.has_key(cmd): return cls.complete_cli( text, state, cls.cli_search_list_sub[cmd]) else: index = 0 while cls.complete_cli( BUFFER[1], index, cls.cli_search_list_sub[cmd]): argtemp.append( cls.complete_cli( BUFFER[1], index, cls.cli_search_list_sub[cmd])) index = index + 1 if len(argtemp) == 1: argtemp == argtemp[0] i = i + 1 else: return cls.complete_cli(text, state, cls.get_cli_search_list()) except: LOG.exception_err_write()
def draw_refresh_time(cls, menu_list): try: time_color = curses.color_pair(3) str_time = 'Last Check Time [' + SYS.last_check_time.split('.')[0] + ']' cls.set_main_str(SYS.get_sys_line_count() + 2 + 3 + len(menu_list) + 2 + 1, MAIN_WIDTH - len(str_time), str_time, time_color) except: LOG.exception_err_write()
def input_cmd(cls): try: cmd = raw_input('CLI(' + cls.selected_sys + ')> ') return cmd except: LOG.exception_err_write() return ''
def do_POST(self): global global_evt global global_conn_evt global global_history_log try: request_sz = int(self.headers["Content-length"]) request_str = self.rfile.read(request_sz) request_obj = json.loads(request_str) LOG.debug_log('[REST-SERVER] CLIENT INFO = ' + str(self.client_address)) LOG.debug_log('[REST-SERVER] RECV HEADER = \n' + str(self.headers)) LOG.debug_log('[REST-SERVER] RECV BODY = \n' + json.dumps(request_obj, sort_keys=True, indent=4)) if self.path.startswith('/test'): t_id = request_obj['transaction_id'] if os.path.exists('log/flowtrace_' + t_id): os.remove('log/flowtrace_' + t_id) result_file = open('log/flowtrace_' + t_id, 'w') result_file.write(str(request_obj)) result_file.close() elif self.path.startswith('/traffictest'): t_id = request_obj['transaction_id'] if os.path.exists('log/traffictest_' + t_id): os.remove('log/traffictest_' + t_id) result_file = open('log/traffictest_' + t_id, 'w') result_file.write(str(request_obj)) result_file.close() elif self.headers.getheader('Authorization') is None: LOG.debug_log('[REST-SERVER] no auth header received') elif not self.path.startswith('/event'): LOG.debug_log('[REST-SERVER] ' + self.path + ' not found') elif self.auth_pw(self.headers.getheader('Authorization')): global_history_log.write_history('[%s][%s][%s][%s] %s', request_obj['system'], request_obj['item'], request_obj['grade'], request_obj['pre_grade'], request_obj['reason']) if request_obj['system'] == 'sonawatcher' and request_obj[ 'item'] == 'SONAWATCHER_DISCONNECT': global_conn_evt.set() LOG.debug_log('[REST-SERVER] ' + request_obj['reason']) else: global_evt.set() else: LOG.debug_log('[REST-SERVER] not authenticated') except: LOG.exception_err_write()
def display_header(cls, menu): try: width = 60 print BG_WHITE + "+%s+" % ('-' * width).ljust(width) + ENDC print BG_WHITE + '|' + BG_BLUEW + BOLD + \ ("{0:^" + str(width) + "}").format(menu) + BG_WHITE + '|' + ENDC print BG_WHITE + "+%s+" % ('-' * width).ljust(width) + ENDC except: LOG.exception_err_write()
def draw_system(cls, menu_list): try: box_system = cls.display_sys_info() cls.draw_refresh_time(menu_list) box_system.refresh() except: LOG.exception_err_write()
def complete_cli(cls, text, state, search_list): try: for cmd in search_list: if cmd.startswith(text): if not state: return str(cmd) else: state -= 1 except: LOG.exception_err_write()
def req_sys_info(cls): try: ret_code, myResponse = cls.send_rest(cls.sys_command) # rest timeout if ret_code == -1: return -1, myResponse except: LOG.exception_err_write() return myResponse.status_code, myResponse.content
def send_regi(cls, type='regi'): auth = cls.get_auth() url = 'http://' + str(CONFIG.get_rest_ip()) + ':' + str( CONFIG.get_rest_port()) + '/event' req_body = {'url': url} req_body_json = json.dumps(req_body) header = { 'Content-Type': 'application/json', 'Authorization': base64.b64encode(auth) } cls.CLI_LOG.cli_log( '---------------------------SEND CMD---------------------------') try: if type == 'regi': url = CONFIG.get_regi_uri() else: url = CONFIG.get_unregi_uri() cls.CLI_LOG.cli_log('URL = ' + url) cls.CLI_LOG.cli_log('AUTH = ' + auth) myResponse = requests.get(url, headers=header, data=req_body_json, timeout=CONFIG.get_rest_timeout()) cls.CLI_LOG.cli_log('HEADER = ' + json.dumps(header, sort_keys=True, indent=4)) cls.CLI_LOG.cli_log('BODY = ' + json.dumps(req_body, sort_keys=True, indent=4)) except: # req timeout LOG.exception_err_write() return False cls.CLI_LOG.cli_log( '---------------------------RECV RES---------------------------') cls.CLI_LOG.cli_log('RESPONSE CODE = ' + str(myResponse.status_code)) if myResponse.status_code == 200: result = json.loads(myResponse.content) if result['Result'] == 'SUCCESS': return True else: return False else: return False
def listen_evt(evt): while SYS.get_sys_thr_flag(): try: evt.wait(1) if evt.is_set(): evt.clear() # system check check_system() time.sleep(1) except: LOG.exception_err_write()
def display_help(cls): try: print '' for cmd in CLI.command_list: print '\t' + cmd.ljust(15) + ' ' + CONFIG.get_cmd_help(cmd) if (CONFIG.get_config_instance().has_section(cmd)): opt_list = CONFIG.cli_get_value(cmd, CONFIG.get_cmd_opt_key_name()) print '\t' + ' '.ljust(15) + ' - option : ' + opt_list.strip() print '' except: LOG.exception_err_write()
def changed_sys_info(cls, new_info): # if changed : return true try: new_sys_info = json.loads(new_info) cls.last_check_time = new_sys_info['time'] if cls.pre_sys_info == new_sys_info['result']: return False else: cls.set_sys_info(new_info) return True except: LOG.exception_err_write() return True
def run(evt, conn_evt): global global_conn_evt global global_evt LOG.debug_log("--- REST Server Start --- ") global_evt = evt global_conn_evt = conn_evt try: server_address = ("", CONFIG.get_rest_port()) httpd = HTTPServer(server_address, RestHandler) httpd.serve_forever() except: LOG.exception_err_write()
def display_event(cls, cnt=20): try: cmd = 'tail -n ' + str(cnt) + ' log/event_history.log' result = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True) output, error = result.communicate() if result.returncode != 0: LOG.debug_log("Cmd Fail, cause => %s", error) print 'Failed to load file' else: print '\n * Only the last ' + str(cnt) + ' logs are printed.' print ' * Please refer to the log file for details. (path = log/event_history.log)\n' print output except: LOG.exception_err_write()
def set_readline_opt(): try: delims = readline.get_completer_delims().replace("-", "^") readline.set_completer_delims(delims) # mac OS if 'libedit' in readline.__doc__: readline.parse_and_bind("bind -e") readline.parse_and_bind("bind '\t' rl_complete") else: readline.parse_and_bind("tab:complete") readline.parse_and_bind('set editing-mode vi') except: LOG.exception_err_write()
def key_name(self, key): try: default_width = 12 key = '* ' + key if len(key) < default_width: for i in range(default_width - len(key)): key = key + ' ' key = key + ' ' except: LOG.exception_err_write() return key
def valid_IPv4(address): try: parts = address.split(".") if len(parts) != 4: return False for item in parts: if len(item) > 3: return False if not 0 <= int(item) <= 255: return False return True except: LOG.exception_err_write() return False
def display_status(cls): onos_list = ['TYPE', 'IP', 'NETWORK', 'CPU', 'MEMORY', 'DISK', 'ONOS_APP', 'ONOS_REST', 'ONOS_OPENFLOW', 'ONOS_CLUSTER', 'OPENSTACK_NODE', 'TRAFFIC_CONTROLLER'] openstack_list = ['TYPE', 'IP', 'NETWORK', 'CPU', 'MEMORY', 'DISK', 'GATEWAY', 'TRAFFIC_GW', 'PORT_STAT_VXLAN', 'TRAFFIC_INTERNAL'] xos_list = ['TYPE', 'IP', 'NETWORK', 'CPU', 'MEMORY', 'DISK', 'XOS_SVC', 'SYNCHRONIZER', 'SWARM_SVC', 'SWARM_NODE'] ha_list = ['TYPE', 'IP', 'NETWORK', 'CPU', 'MEMORY', 'DISK', 'HA_SVC', 'HA_RATIO'] try: print '' cls.draw_grid('ONOS', onos_list) cls.draw_grid('HA', ha_list) cls.draw_grid('OPENSTACK', openstack_list) cls.draw_grid('XOS', xos_list) except: LOG.exception_err_write()
def display_sys_info(cls): box_sys = curses.newwin(SYS.get_sys_line_count() + 2, MAIN_WIDTH, 1, 1) box_sys.box() try: status_text_OK = curses.color_pair(2) status_text_NOK = curses.color_pair(3) normal_text = curses.A_NORMAL box_sys.addstr(0, 18, ' CONTROL PLAN ', normal_text) i = 1 sorted_list = sorted(SYS.sys_list.keys()) alarm_flag = False for sys in sorted_list: str_info = sys.ljust(6) + ' [' box_sys.addstr(i, 2, str_info) str_status = 'OK' status_list = (dict)(SYS.sys_list[sys]).values() for status in status_list: if (status == 'none'): str_status = 'loading' break elif not (status == 'ok' or status == 'normal'): str_status = 'NOK' alarm_flag = True break if str_status is 'OK': box_sys.addstr(i, 2 + len(str_info), str_status, status_text_OK) else: box_sys.addstr(i, 2 + len(str_info), str_status, status_text_NOK) box_sys.addstr(i, 2 + len(str_info) + len(str_status), ']') i += 1 SYS.abnormal_flag = alarm_flag except: LOG.exception_err_write() return box_sys
def set_sys_info(cls, sys_info): try: sys_info = json.loads(sys_info) sys_info = sys_info['result'] cls.pre_sys_info = sys_info for key in sys_info: dtl_list = {} for item in (dict)(sys_info[key]).keys(): dtl_list[item] = sys_info[key][item] cls.sys_list[key] = dtl_list except: LOG.exception_err_write()
def set_search_list(cls): try: for cmd in cls.command_list: cls.cli_search_list.append(cmd) cls.cli_validate_list.append(cmd) if (CONFIG.get_config_instance().has_section(cmd)): opt_list = CONFIG.cli_get_value( cmd, CONFIG.get_cmd_opt_key_name()) tmp = [] for opt in opt_list.split(','): tmp.append(opt.strip()) cls.cli_validate_list.append(cmd + ' ' + opt.strip()) cls.cli_search_list_sub[cmd] = tmp cls.cli_search_list.append('menu') cls.cli_search_list.append('exit') cls.cli_search_list.append('sys') cls.cli_search_list.append('onos-shell') cls.cli_search_list.append('os-shell') cls.cli_search_list.append('monitoring-details') cls.cli_search_list.append('event-history') cls.cli_search_list.append('flow-trace') cls.cli_search_list.append('traffic-test') cls.cli_search_list.append('help') onos_list = [] shell_list = [] tmp_sys = [] tmp_sys.append('all') cls.cli_validate_list.append('sys all') for sys_name in SYS.get_sys_list(): tmp_sys.append(sys_name) cls.cli_validate_list.append('sys ' + sys_name) cls.cli_validate_list.append('os-shell ' + sys_name) if dict(SYS.sys_list[sys_name])['TYPE'] == 'ONOS': onos_list.append(sys_name) shell_list.append(sys_name) cls.cli_search_list_sub['sys'] = tmp_sys cls.cli_search_list_sub['onos-shell'] = onos_list cls.cli_search_list_sub['os-shell'] = shell_list except: LOG.exception_err_write()