def create_template(self, **kwargs): templates = kwargs['templates_extra']['templates'] template_attributes = kwargs['templates_extra']['template_attributes'] template_names = kwargs['templates_extra']['template_names'] values = kwargs['templates_extra']['values'] if len(templates) > 0: try: self._lb._channel.System.Session.start_transaction() self._lb._channel.LocalLB.Monitor.create_template( templates=templates, template_attributes=template_attributes ) except Exception, e: self._lb._channel.System.Session.rollback_transaction() raise base_exceptions.CommandErrorException(e) else: self._lb._channel.System.Session.submit_transaction() try: self._lb._channel.System.Session.start_transaction() self._lb._channel.LocalLB.Monitor.set_template_string_property( template_names=template_names, values=values ) except Exception, e: self._lb._channel.System.Session.rollback_transaction() raise base_exceptions.CommandErrorException(e) else:
def waitString(self, wait_str_ok_regex='>', wait_str_invalid_regex=None, wait_str_failed_regex=None): if wait_str_invalid_regex is None: wait_str_invalid_regex = self.INVALID_REGEX if wait_str_failed_regex is None: wait_str_failed_regex = self.ERROR_REGEX confirm_regex = "[Y/N]" confirm_command = 'Y' string_ok = 0 recv_string = '' while not string_ok: while not self.channel.recv_ready(): sleep(1) recv_string = self.channel.recv(9999) file_name_string = self.removeDisallowedChars(recv_string) if re.search(wait_str_failed_regex, recv_string): log.error('Equipment raised INVALID error: %s' % recv_string) raise exceptions.InvalidCommandException(file_name_string) elif re.search(wait_str_invalid_regex, recv_string): log.error('Equipment raised Failed error: %s' % recv_string) raise exceptions.CommandErrorException(file_name_string) elif re.search(wait_str_ok_regex, recv_string): log.debug('Equipment output: %s' % recv_string) string_ok = 1 elif re.search(confirm_regex, recv_string): self.channel.send('%s\n' % confirm_command) return recv_string
def update_vip(self, vips): pools_ins = list() pools_del = list() tratado = util.trata_param_vip(vips) vts = virtualserver.VirtualServer(self._lb) dict_create_vip = { 'vips_cache': tratado.get('vips_cache_filter_to_insert'), 'vips': tratado.get('vips_filter_to_insert'), 'pool': tratado.get('pool_filter_to_insert') } dict_delete_vip = { 'vips_cache': tratado.get('vips_cache_filter_to_delete'), 'vips': tratado.get('vips_filter_to_delete'), 'pool_created': list() } # delete ports try: log.info('try delete ports') pools_del = self._delete_vip(dict_delete_vip) vts = virtualserver.VirtualServer(self._lb) except Exception, e: # rollback delete of ports log.info('rollback delete of ports') pools_del = self._delete_vip(dict_create_vip) log.error('error to delete ports') log.error(e) raise base_exceptions.CommandErrorException(e)
def waitString(self, wait_str_ok_regex='', wait_str_invalid_regex=None, wait_str_failed_regex=None): if wait_str_invalid_regex is None: wait_str_invalid_regex = self.INVALID_REGEX if wait_str_failed_regex is None: wait_str_failed_regex = self.ERROR_REGEX string_ok = 0 recv_string = '' while not string_ok: while not self.channel.recv_ready(): sleep(1) recv_string = self.channel.recv(9999) file_name_string = self.removeDisallowedChars(recv_string) if re.search(wait_str_invalid_regex, recv_string, re.DOTALL): raise exceptions.CommandErrorException(file_name_string) elif re.search(wait_str_failed_regex, recv_string, re.DOTALL): raise exceptions.InvalidCommandException(file_name_string) elif re.search(wait_str_ok_regex, recv_string, re.DOTALL): string_ok = 1 return recv_string
def get_flows(self): """ Returns All flows for table 0 of all switches of a environment """ nodes_ids = self._get_nodes_ids() # if len(nodes_ids) < 1: # raise exceptions.ControllerInventoryIsEmpty(msg="No nodes found") flows_list = {} for node_id in nodes_ids: try: path = "/restconf/config/opendaylight-inventory:nodes/node/" \ "%s/flow-node-inventory:table/0/" % (node_id) inventory = self._request(method="get", path=path, contentType='json') flows_list[node_id] = inventory["flow-node-inventory:table"] except HTTPError as e: if e.response.status_code == 404: flows_list[node_id] = [] else: raise exceptions.CommandErrorException( msg=self._parse_errors(e.response.json())) except Exception as e: raise e return flows_list
def update_all_flows(self, data, flow_type=FlowTypes.ACL): current_flows = self.get_flows() for node in current_flows.keys(): log.info("Starting update all flows for node %s" % node) if flow_type == FlowTypes.ACL: builder = AclFlowBuilder(data, self.environment, version=self.version) new_flows_set = builder.build() #Makes a diff operations = self._diff_flows(current_flows[node], new_flows_set) try: for flow in operations["delete"]: self.del_flow(flow_id=flow['id'], nodes_ids=[node]) for flow in operations["insert"]: self._flow(flow_id=flow['id'], method='put', data=json.dumps({'flow': [flow]}), nodes_ids=[node]) except Exception as e: message = self._parse_errors(e.response.json()) log.error("ERROR while updating all flows: %s" % message) raise exceptions.CommandErrorException(msg=message)
def inner(self, *args, **kwargs): if not kwargs.__contains__('connection') or kwargs['connection']: try: access = args[0].get('access').filter( tipo_acesso__protocolo='https').uniqueResult() self._lb = lb.Lb(access.fqdn, access.user, access.password) if not kwargs.__contains__('transation') or kwargs['transation']: log.info('Transaction Started') with bigsuds.Transaction(self._lb._channel): return func(self, *args, **kwargs) else: return func(self, *args, **kwargs) except bigsuds.OperationFailed, e: log.error(e) raise base_exceptions.CommandErrorException(e) except Exception, e: log.error('Error %s' % e) raise base_exceptions.CommandErrorException(e)
def inner(self, *args, **kwargs): try: access = args[0].get('access').filter( tipo_acesso__protocolo='https').uniqueResult() self._lb = lb.Lb(access.fqdn, access.user, access.password, False) return func(self, *args, **kwargs) except bigsuds.OperationFailed, e: log.error(e) raise base_exceptions.CommandErrorException(e)
def inner(self, *args, **kwargs): try: access = args[0].get('access').filter( tipo_acesso__protocolo='https').uniqueResult() self._lb = lb.Lb(access.fqdn, access.user, access.password) self._lb._channel.System.Session.set_transaction_timeout(60) return func(self, *args, **kwargs) except bigsuds.OperationFailed, e: log.error(e) raise base_exceptions.CommandErrorException(e)
def _delete_pool(self, pools): pls = util.trata_param_pool(pools) pl = pool.Pool(self._lb) mon = monitor.Monitor(self._lb) try: monitor_associations = pl.get_monitor_association( names=pls['pools_names']) except Exception, e: log.error(e) raise base_exceptions.CommandErrorException(e)
def create_vip(self, vips): try: if vips.get('layers'): for vip_id in vips.get('layers'): for id_layer in vips.get('layers').get(vip_id): vip_request = vips.get('layers').get(vip_id).get( id_layer).get('vip_request') command = 'gerador_vips -i %s --cria --aceonly' % vip_request[ 'id'] log.info('calling script: %s' % command) code, stdout, stderr = exec_script(command) except Exception, e: log.error(e) raise base_exceptions.CommandErrorException(e)
def partial_update_vip(self, vips): tratado = util.trata_param_vip(vips) vts = virtualserver.VirtualServer(self._lb) try: log.info('try update vips') if tratado.get('vips_filter'): vts.partial_update(vips=tratado.get('vips_filter')) except Exception, e: log.info('error update vips') log.error(e) raise base_exceptions.CommandErrorException(e)
def __init__(self, hostname, username, password, session=True): self._hostname = hostname self._username = username self._password = password self._time_reconn = 10 try: self._channel = bigsuds.BIGIP(hostname=self._hostname, username=self._username, password=self._password) except Exception, e: logging.critical('Unable to connect to BIG-IP. Details: %s' % (e)) raise base_exceptions.CommandErrorException(e)
def __delete_pool(self, pools): pls = util.trata_param_pool(pools) pl = pool.Pool(self._lb) mon = monitor.Monitor(self._lb) try: self._lb._channel.System.Session.start_transaction() monitor_associations = pl.get_monitor_association( names=pls['pools_names']) pl.remove_monitor_association(names=pls['pools_names']) except Exception, e: log.error(e) self._lb._channel.System.Session.rollback_transaction() raise base_exceptions.CommandErrorException(e)
def add_flow(self, data=None, flow_id=0, flow_type=FlowTypes.ACL, nodes_ids=[]): if flow_type == FlowTypes.ACL: builder = AclFlowBuilder(data, self.environment, version=self.version) flows_set = builder.build() try: for flows in flows_set: for flow in flows['flow']: self._flow(flow_id=flow['id'], method='put', data=json.dumps({'flow': [flow]}), nodes_ids=nodes_ids) except HTTPError as e: raise exceptions.CommandErrorException( msg=self._parse_errors(e.response.json()))
def __init__(self, hostname, username, password): self._hostname = hostname self._username = username self.service_clients = None try: device = { 'management_ip': hostname, 'user': username, 'password': password } self.service_clients = (ClientCache.get_adx_service_client(device)) except Exception, e: logging.critical('Unable to connect to BROCADE. Details: %s' % (e)) raise base_exceptions.CommandErrorException(e)
def _create_vip(self, tratado): pools_ins = list() vts = virtualserver.VirtualServer(self._lb) # vip create if tratado.get('pool'): self.__create_pool({'pools': tratado.get('pool')}) pools_ins = [ server_pool.get('id') for server_pool in tratado.get('pool') ] try: if tratado.get('vips'): vts.create(vips=tratado.get('vips')) except Exception, e: if tratado.get('pool'): self._delete_pool({'pools': tratado.get('pool')}) log.error(e) raise base_exceptions.CommandErrorException(e)
def flush_flows(self): nodes_ids = self._get_nodes_ids() # if len(nodes_ids) < 1: # raise exceptions.ControllerInventoryIsEmpty(msg="No nodes found") for node_id in nodes_ids: try: path = "/restconf/config/opendaylight-inventory:nodes/node/" \ "%s/flow-node-inventory:table/0/" % node_id self._request(method="delete", path=path, contentType='json') except HTTPError as e: if e.response.status_code == 404: pass else: raise exceptions.CommandErrorException( msg=self._parse_errors(e.response.json())) except Exception as e: raise e
def _request(self, **kwargs): # Params and default values params = { 'method': 'get', 'uri': '', 'data': None, 'contentType': 'json', 'verify': False } # Setting params via kwargs or use the defaults for param in params: if param in kwargs: params[param] = kwargs.get(param) headers = self._get_headers(contentType=params["contentType"]) try: func = getattr(requests, params["method"] ) #Raises AttributeError if method is not valid request = func(params["uri"], auth=self._get_auth(), headers=headers, verify=params["verify"], data=params["data"]) request.raise_for_status() if params["contentType"] == 'json': return json.loads(request.text) else: return request.text except AttributeError: self.logger.error( 'Request method must be valid HTTP request. ie: GET, POST, PUT, DELETE' ) except HTTPError: error = self._parse(request.text) self.logger.error(error) raise exceptions.CommandErrorException()
else: # cache layer try: if tratado.get('vips_cache'): vts.create(vips=tratado.get('vips_cache')) except Exception, e: # rollback vip create try: if tratado.get('vips'): vps_names = [vp['name'] for vp in tratado.get('vips')] vts.delete(vps_names=vps_names) except Exception, e: log.error(e) raise base_exceptions.CommandErrorException(e) else: if tratado.get('pool'): self._delete_pool({'pools': tratado.get('pool')}) log.error(e) raise base_exceptions.CommandErrorException(e) return pools_ins @logger @util.connection def update_vip(self, vips): pools_ins = list() pools_del = list()
def __update_pool(self, pools): monitor_associations = [] pls = util.trata_param_pool(pools) pl = pool.Pool(self._lb) mon = monitor.Monitor(self._lb) # get template currents monitor_associations_old = pl.get_monitor_association( names=pls['pools_names']) # creates templates monitor_associations, monitor_associations_nodes, templates_extra = mon.prepare_template( names=pls['pools_names'], members=pls['pools_members']['members'], healthcheck=pls['pools_healthcheck']) mon.create_template(templates_extra=templates_extra) try: self._lb._channel.System.Session.start_transaction() pl.set_monitor_association( monitor_associations=monitor_associations) pl.set_lb_method(names=pls['pools_names'], lbmethod=pls['pools_lbmethod']) pl.set_service_down_action(names=pls['pools_names'], actions=pls['pools_actions']) plm = poolmember.PoolMember(self._lb) if pls['pools_members']['members_remove']: plm.remove(names=pls['pools_names'], members=pls['pools_members']['members_remove']) if pls['pools_members']['members_new']: plm.create(names=pls['pools_names'], members=pls['pools_members']['members_new']) plm.set_connection_limit( names=pls['pools_names'], members=pls['pools_members']['members'], connection_limit=pls['pools_members']['limit']) plm.set_priority(names=pls['pools_names'], members=pls['pools_members']['members'], priority=pls['pools_members']['priority']) plm.set_ratio(names=pls['pools_names'], members=pls['pools_members']['members'], ratio=pls['pools_members']['weight']) # plm.set_member_description( # names=pls['pools_names'], # members=pls['pools_members']['members'], # description=pls['pools_members']['description']) plm.set_states(names=pls['pools_names'], members=pls['pools_members']['members'], monitor_state=pls['pools_members']['monitor'], session_state=pls['pools_members']['session']) except Exception, e: self._lb._channel.System.Session.rollback_transaction() # delete templates created template_names = [ m for m in list( itertools.chain(*[ m['monitor_rule']['monitor_templates'] for m in monitor_associations ])) if 'MONITOR' in m ] if template_names: mon.delete_template(template_names=template_names) log.error(e) raise base_exceptions.CommandErrorException(e)
def prepare_template(self, **kwargs): templates = [] template_attributes = [] template_names = [] values = [] monitor_associations = [] monitor_associations_nodes = { 'nodes': list(), 'monitor_rules': list() } try: if kwargs.get('healthcheck'): for i, pool in enumerate(kwargs['names']): if kwargs['healthcheck'][i]: monitor_association = { 'pool_name': None, 'monitor_rule': { 'monitor_templates': [], 'type': None, 'quorum': None } } if kwargs['healthcheck'][i]['healthcheck_request'] != '' or \ kwargs['healthcheck'][i]['healthcheck_expect'] != '' or \ kwargs['healthcheck'][i]['destination'] != '*:*': name = kwargs['healthcheck'][i]['identifier'] template = { 'template_name': name, 'template_type': types.template_type(kwargs['healthcheck'][i]['healthcheck_type']) } templates.append(template) template_attributes.append({ 'parent_template': kwargs['healthcheck'][i]['healthcheck_type'].lower(), 'interval': 5, 'timeout': 16, 'dest_ipport': types.address_type(kwargs['healthcheck'][i]['destination']), 'is_read_only': 0, 'is_directly_usable': 1 }) hr = kwargs['healthcheck'][i]['healthcheck_request'] healthcheck_expect = kwargs['healthcheck'][i]['healthcheck_expect'] if kwargs['healthcheck'][i]['healthcheck_type'] in ['HTTP', 'HTTPS']: rg = '^([\" ]?)+(GET|HEAD|POST|PUT|CONNECT|DELETE|OPTIONS|TRACE|PATCH)' if not valid_regex(hr, rg): hr = 'GET ' + hr # do escape when healthcheck has simple \r\n rg = '((\\r\\n))' if valid_regex(hr, rg): log.debug('adding unicode-escape') hr = hr.encode('unicode-escape') # add HTTP/1.\\r\\n\\r\\n when plugin no receive in # healthcheck rg = 'HTTP\/1' if not valid_regex(hr, rg): log.debug('adding HTTP/1.\\r\\n\\r\\n') hr = hr + ' HTTP/1.0\\r\\n\\r\\n' # add \\r\\n\\r\\n when plugin no receive in # healthcheck rg = '(?:((\\r\\n)|(\\\\r\\\\n)){1,2}?)$' if not valid_regex(hr, rg): log.debug('adding \\r\\n\\r\\n') hr = hr + '\\r\\n\\r\\n' healthcheck_request = hr template_names.append(name) values.append({ 'type': 'STYPE_SEND', 'value': healthcheck_request }) template_names.append(name) values.append({ 'type': 'STYPE_RECEIVE', 'value': healthcheck_expect }) else: name = kwargs['healthcheck'][i]['healthcheck_type'].lower() monitor_association['pool_name'] = kwargs['names'][i] monitor_association['monitor_rule']['monitor_templates'].append(name) monitor_association['monitor_rule']['type'] = 'MONITOR_RULE_TYPE_SINGLE' monitor_association['monitor_rule']['quorum'] = 0 monitor_associations.append(monitor_association) if name == 'udp': for node in kwargs['members'][i]: monitor_association_node = { 'monitor_templates': [], 'type': None, 'quorum': None } monitor_association_node['monitor_templates'].append('icmp') monitor_association_node['type'] = 'MONITOR_RULE_TYPE_SINGLE' monitor_association_node['quorum'] = 0 monitor_associations_nodes['monitor_rules'].append(monitor_association_node) monitor_associations_nodes['nodes'].append(node['address']) except Exception, e: log.error(e) raise base_exceptions.CommandErrorException(e)