def _add_snmp_config(self, ctxt, new_config): LOG.info("Add snmp config:%s" % new_config) storage_id = new_config.get("storage_id") version_int = self._get_snmp_version_int(ctxt, new_config.get("version")) if version_int == constants.SNMP_V2_INT or \ version_int == constants.SNMP_V1_INT: community_string = new_config.get("community_string") community_index = self._get_community_index(storage_id) config.addV1System(self.snmp_engine, community_index, community_string, contextName=community_string) else: username = new_config.get("username") engine_id = new_config.get("engine_id") auth_key = new_config.get("auth_key") auth_protocol = new_config.get("auth_protocol") privacy_key = new_config.get("privacy_key") privacy_protocol = new_config.get("privacy_protocol") if auth_key is not None: auth_key = cryptor.decode(auth_key) if privacy_key is not None: privacy_key = cryptor.decode(privacy_key) config.addV3User( self.snmp_engine, userName=username, authKey=auth_key, privKey=privacy_key, authProtocol=self._get_usm_auth_protocol(ctxt, auth_protocol), privProtocol=self._get_usm_priv_protocol(ctxt, privacy_protocol), securityEngineId=v2c.OctetString(hexValue=engine_id))
def _decrypt_auth_key(self, alert_source): auth_key = alert_source.get('auth_key', None) privacy_key = alert_source.get('privacy_key', None) if auth_key: alert_source['auth_key'] = cryptor.decode(auth_key) if privacy_key: alert_source['privacy_key'] = cryptor.decode(privacy_key) return alert_source
def _add_snmp_config(self, ctxt, new_config): storage_id = new_config.get("storage_id") LOG.info("Start to add snmp trap config for storage: %s", storage_id) try: version_int = self._get_snmp_version_int(ctxt, new_config.get("version")) if version_int == constants.SNMP_V2_INT or \ version_int == constants.SNMP_V1_INT: community_string = cryptor.decode( new_config.get("community_string")) community_string = encodeutils.to_utf8(community_string) community_index = self._get_community_index(storage_id) config.addV1System(self.snmp_engine, community_index, community_string, contextName=community_string) else: username = new_config.get("username") engine_id = new_config.get("engine_id") if engine_id: engine_id = v2c.OctetString(hexValue=engine_id) auth_key = new_config.get("auth_key") auth_protocol = new_config.get("auth_protocol") privacy_key = new_config.get("privacy_key") privacy_protocol = new_config.get("privacy_protocol") if auth_key: auth_key = encodeutils.to_utf8(cryptor.decode(auth_key)) if privacy_key: privacy_key = encodeutils.to_utf8( cryptor.decode(privacy_key)) config.addV3User( self.snmp_engine, userName=username, authKey=auth_key, privKey=privacy_key, authProtocol=self._get_usm_auth_protocol(ctxt, auth_protocol), privProtocol=self._get_usm_priv_protocol(ctxt, privacy_protocol), securityEngineId=engine_id) LOG.info("Add snmp trap config for storage: %s successfully.", storage_id) except Exception as e: msg = six.text_type(e) LOG.error("Failed to add snmp trap config for storage: %s. " "Reason: %s", storage_id, msg) raise e
def login(self): """Login dell_emc unity storage array.""" try: with self.session_lock: data = {} if self.session is None: self.init_http_head() self.session.headers.update({"X-EMC-REST-CLIENT": "true"}) self.session.auth = requests.auth.HTTPBasicAuth( self.rest_username, cryptor.decode(self.rest_password)) res = self.call_with_token(RestHandler.REST_AUTH_URL, data, 'GET') if res.status_code == 200: self.session.headers[RestHandler.AUTH_KEY] = \ cryptor.encode(res.headers[RestHandler.AUTH_KEY]) else: LOG.error("Login error.URL: %s,Reason: %s.", RestHandler.REST_AUTH_URL, res.text) if 'Unauthorized' in res.text: raise exception.InvalidUsernameOrPassword() elif 'Forbidden' in res.text: raise exception.InvalidIpOrPort() else: raise exception.BadResponse(res.text) except Exception as e: LOG.error("Login error: %s", six.text_type(e)) raise e
def establish_rest_session(self): """Establish the rest session. :returns: requests.session() -- session, the rest session """ LOG.info("Establishing REST session with %(base_uri)s", {'base_uri': self.base_uri}) if self.session: self.session.close() session = requests.session() session.headers = { 'content-type': 'application/json', 'accept': 'application/json', 'Application-Type': 'delfin' } session.auth = requests.auth.HTTPBasicAuth(self.user, cryptor.decode(self.passwd)) if not self.verify: session.verify = False else: LOG.debug("Enable certificate verification, ca_path: {0}".format( self.verify)) session.verify = self.verify session.mount("https://", ssl_utils.get_host_name_ignore_adapter()) self.session = session return session
def login(self): try: data = { 'request': { 'params': { "username": self.rest_username, "password": cryptor.decode(self.rest_password) } } } with self.session_lock: if self.session is None: self.init_http_head() res = self.call_with_token( RestHandler.REST_TOKEN_URL, data, 'POST') if res.status_code == 200: result = res.json() self.session.headers['X-Auth-Token'] = \ cryptor.encode(result.get('token').get('token')) else: LOG.error("Login error. URL: %(url)s,Reason: %(reason)s.", {"url": RestHandler.REST_TOKEN_URL, "reason": res.text}) if 'Authentication has failed' in res.text: raise exception.InvalidUsernameOrPassword() else: raise exception.StorageBackendException(res.text) except Exception as e: LOG.error("Login error: %s", six.text_type(e)) raise e finally: data = None
def get_rest_info(self, url, data=None, method='GET'): if 'login' == data: self.session.auth = requests.auth.HTTPBasicAuth( self.rest_username, cryptor.decode(self.rest_password)) else: self.login() self.session.auth = requests.auth.HTTPBasicAuth( self.rest_username, self.rest_auth_token) res = self.do_call(url, data, method) try: if res.status_code == 200: result_json = json.loads(res.text) elif res.status_code == 500: LOG.error('Connect Timeout error') raise exception.ConnectTimeout() elif res.status_code == 401: LOG.error('User authentication failed') raise exception.InvalidUsernameOrPassword else: raise exception.BadResponse() except Exception as err: LOG.exception( 'Get RestHandler.call failed: %(url)s.' ' Error: %(err)s', { 'url': url, 'err': err }) raise exception.InvalidResults(err) return result_json
def login(self): try: data = {} self.init_http_head() self.session.headers.update({ "username": self.rest_username, "password": cryptor.decode(self.rest_password) }) res = self.do_call(consts.REST_AUTH_URL, data, 'GET') if res.status_code != 200: LOG.error("Login error. URL: %(url)s\n" "Reason: %(reason)s.", { "url": consts.REST_AUTH_URL, "reason": res.text }) if 'User authentication failed' in res.text: raise exception.InvalidUsernameOrPassword() else: raise exception.StorageBackendException( six.text_type(res.text)) except Exception as e: LOG.error("Login error: %s", six.text_type(e)) raise e
def _cm_access_info_update(self, ctxt, access_info, body): access_info_dict = copy.deepcopy(access_info) unused = [ 'created_at', 'updated_at', 'storage_name', 'storage_id', 'extra_attributes' ] access_info_dict = AccessInfo.to_dict(access_info_dict) for field in unused: if access_info_dict.get(field): access_info_dict.pop(field) for access in constants.ACCESS_TYPE: if access_info_dict.get(access): access_info_dict.pop(access) access_info_list = db.access_info_get_all(ctxt, filters=access_info_dict) for cm_access_info in access_info_list: if cm_access_info['storage_id'] == access_info['storage_id']: continue for access in constants.ACCESS_TYPE: if cm_access_info.get(access): cm_access_info[access]['password'] = cryptor.decode( cm_access_info[access]['password']) if body.get(access): cm_access_info[access].update(body[access]) self.driver_api.update_access_info(ctxt, cm_access_info)
def create(self): ssh = paramiko.SSHClient() try: if self.ssh_pub_key is None: ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) else: host_key = '%s %s %s' % \ (self.ssh_host, self.ssh_pub_key_type, self.ssh_pub_key) self.set_host_key(host_key, ssh) ssh.connect(hostname=self.ssh_host, port=self.ssh_port, username=self.ssh_username, password=cryptor.decode(self.ssh_password), timeout=self.ssh_conn_timeout) if self.conn_timeout: transport = ssh.get_transport() transport.set_keepalive(self.SOCKET_TIMEOUT) return ssh except Exception as e: err = six.text_type(e) LOG.error('doexec InvalidUsernameOrPassword error') if 'timed out' in err: raise exception.InvalidIpOrPort() elif 'No authentication methods available' in err \ or 'Authentication failed' in err: raise exception.InvalidUsernameOrPassword() elif 'not a valid RSA private key file' in err: raise exception.InvalidPrivateKey() elif 'not found in known_hosts' in err: raise exception.SSHNotFoundKnownHosts(self.ssh_host) else: raise exception.SSHException(err)
def __init__(self, **kwargs): super().__init__(**kwargs) access_info = kwargs if access_info is None: raise exception.InvalidInput('Input access_info is missing') self.array_json = access_info.get("extra_attributes").get("path") with open(self.array_json) as f: data = json.load(f) # Verify Host & Port f_host = data.get("access_info").get("rest").get("host") f_port = data.get("access_info").get("rest").get("port") f_user = data.get("access_info").get("rest").get("username") f_pass = data.get("access_info").get("rest").get("password") a_host = access_info.get("rest").get("host") a_port = access_info.get("rest").get("port") a_user = access_info.get("rest").get("username") a_pass = access_info.get("rest").get("password") a_pass = cryptor.decode(a_pass) if f_host != a_host: raise exception.InvalidIpOrPort if f_port != a_port: raise exception.InvalidIpOrPort if f_user != a_user: raise exception.InvalidUsernameOrPassword if f_pass != a_pass: raise exception.InvalidUsernameOrPassword
def get_access_info(context, storage_id): access_info = db.access_info_get(context, storage_id) access_info_dict = access_info.to_dict() for access in constants.ACCESS_TYPE: if access_info.get(access): access_info[access]['password'] = cryptor.decode( access_info[access]['password']) return access_info_dict
def _cb_fun(self, state_reference, context_engine_id, context_name, var_binds, cb_ctx): """Callback function to process the incoming trap.""" exec_context = self.snmp_engine.observer.getExecutionContext( 'rfc3412.receiveMessage:request') LOG.debug("Get notification from: %s" % "#".join([str(x) for x in exec_context['transportAddress']])) alert = {} try: # transportAddress contains both ip and port, extract ip address source_ip = exec_context['transportAddress'][0] alert_source = self._get_alert_source_by_host(source_ip) # In case of non v3 version, community string is used to map the # trap. Pysnmp library helps to filter traps whose community string # are not configured. But if a given community name x is configured # for storage1, if the trap is received with x from storage 2, # library will allow the trap. So for non v3 version, we need to # verify that community name is configured at alert source db for # the storage which is sending traps. # context_name contains the incoming community string value if exec_context['securityModel'] != constants.SNMP_V3_INT \ and cryptor.decode(alert_source['community_string']) \ != str(context_name): msg = (_("Community string not matching with alert source %s, " "dropping it.") % source_ip) raise exception.InvalidResults(msg) for oid, val in var_binds: # Fill raw oid and values oid_str = str(oid) alert[oid_str] = str(val) # Fill additional info to alert info alert['transport_address'] = source_ip alert['storage_id'] = alert_source['storage_id'] filters = { 'mgmt_ip': source_ip, 'storage_id': alert_source['storage_id'] } ctxt = context.RequestContext() controllers = db.controller_get_all(ctxt, filters=filters) if controllers: alert['controller_name'] = controllers[0].get('name') # Handover to alert processor for model translation and export self.alert_processor.process_alert_info(alert) except exception.DelfinException as e: # Log and end the trap processing error flow err_msg = _("Failed to process alert report (%s).") % e.msg LOG.exception(err_msg) except Exception as e: err_msg = six.text_type(e) LOG.exception(err_msg)
def call_with_token(self, url, data, method): auth_key = None if self.session: auth_key = self.session.headers.get('X-Auth-Token', None) if auth_key: self.session.headers['X-Auth-Token'] \ = cryptor.decode(auth_key) res = self.do_call(url, data, method) if auth_key: self.session.headers['X-Auth-Token'] = auth_key return res
def login(self): """Login Hpe3par storage array.""" try: access_session = self.rest_client.rest_auth_token if self.rest_client.san_address: url = RestHandler.REST_AUTH_URL data = { "user": self.rest_client.rest_username, "password": cryptor.decode(self.rest_client.rest_password) } self.session_lock.acquire() if self.rest_client.rest_auth_token is not None: return self.rest_client.rest_auth_token self.rest_client.init_http_head() res = self.rest_client. \ do_call(url, data, 'POST', calltimeout=consts.SOCKET_TIMEOUT) if res is None: LOG.error('Login res is None') raise exception.InvalidResults('res is None') if res.status_code == consts. \ LOGIN_SUCCESS_STATUS_CODES: result = res.json() access_session = result.get('key') self.rest_client.rest_auth_token = access_session self.rest_client.session.headers[ RestHandler.REST_AUTH_KEY] = access_session else: LOG.error( "Login error. URL: %(url)s\n" "Reason: %(reason)s.", { "url": url, "reason": res.text }) if 'invalid username or password' in res.text: raise exception.InvalidUsernameOrPassword() else: raise exception.BadResponse(res.text) else: LOG.error('Login Parameter error') return access_session except Exception as e: LOG.error("Login error: %s", six.text_type(e)) raise e finally: self.session_lock.release()
def get_cli_command_str(self, host_ip=None, sub_command=None): if host_ip is None: host_ip = self.navi_host command_str = consts.NAVISECCLI_API % { 'username': self.navi_username, 'password': cryptor.decode(self.navi_password), 'host': host_ip, 'timeout': self.navi_timeout} if self.navi_port: command_str = '%s -port %d' % (command_str, self.navi_port) command_str = '%s %s' % (command_str, sub_command) return command_str
def call_with_token(self, url, data, method): auth_key = None if self.session: auth_key = self.session.headers.get(RestHandler.AUTH_KEY, None) if auth_key: self.session.headers[RestHandler.AUTH_KEY] \ = cryptor.decode(auth_key) res = self.do_call(url, data, method) if auth_key: self.session.headers[RestHandler.AUTH_KEY] = auth_key return res
def update(self, req, id, body): """Update storage access information.""" ctxt = req.environ.get('delfin.context') access_info = db.access_info_get(ctxt, id) for access in constants.ACCESS_TYPE: if access_info.get(access): access_info[access]['password'] = cryptor.decode( access_info[access]['password']) if body.get(access): access_info[access].update(body[access]) access_info = self.driver_api.update_access_info(ctxt, access_info) return self._view_builder.show(access_info)
def call_with_token(self, url, data=None, method='GET', calltimeout=consts.DEFAULT_TIMEOUT): auth_key = None if self.session: auth_key = self.session.headers.get(RestHandler.AUTH_KEY, None) if auth_key: self.session.headers[RestHandler.AUTH_KEY] \ = cryptor.decode(auth_key) res = self.do_call(url, data, method, calltimeout) if auth_key: self.session.headers[RestHandler.AUTH_KEY] = auth_key return res
def connect(self): self.ssh = paramiko.SSHClient() if self.ssh_pub_key is None: self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) else: host_key = '%s %s %s' % \ (self.ssh_host, self.ssh_pub_key_type, self.ssh_pub_key) self.set_host_key(host_key) self.ssh.connect(hostname=self.ssh_host, port=self.ssh_port, username=self.ssh_username, password=cryptor.decode(self.ssh_password), timeout=self.ssh_conn_timeout)
def get_token(self): try: succeed = False if self.san_address: url = '%s/%s/sessions' % \ (RestHandler.COMM_URL, self.storage_device_id) data = {} with self.session_lock: if self.session is None: self.init_http_head() self.session.auth = \ requests.auth.HTTPBasicAuth( self.rest_username, cryptor.decode(self.rest_password)) res = self.call_with_token(url, data, 'POST', 30) if res.status_code == 200: succeed = True result = res.json() self.session_id = cryptor.encode( result.get('sessionId')) access_session = 'Session %s' % result.get('token') self.session.headers[ RestHandler.AUTH_KEY] = cryptor.encode( access_session) else: LOG.error( "Login error. URL: %(url)s\n" "Reason: %(reason)s.", { "url": url, "reason": res.text }) if 'authentication failed' in res.text: raise exception.InvalidUsernameOrPassword() elif 'KART30005-E' in res.text: raise exception.StorageBackendException( six.text_type(res.text)) else: raise exception.BadResponse(res.text) else: LOG.error('Token Parameter error') return succeed except Exception as e: LOG.error("Get token error: %s", six.text_type(e)) raise e
def login(self): """Login Huawei storage array.""" device_id = None for item_url in self.san_address: url = item_url + "xx/sessions" data = { "username": self.rest_username, "password": cryptor.decode(self.rest_password), "scope": "0" } self.init_http_head() result = self.do_call(url, data, 'POST', calltimeout=consts.LOGIN_SOCKET_TIMEOUT, log_filter_flag=True) if (result['error']['code'] != 0) or ("data" not in result): LOG.error("Login error. URL: %(url)s\n" "Reason: %(reason)s.", { "url": item_url, "reason": result }) continue LOG.debug('Login success: %(url)s', {'url': item_url}) device_id = result['data']['deviceid'] self.device_id = device_id self.url = item_url + device_id self.session.headers['iBaseToken'] = result['data']['iBaseToken'] if (result['data']['accountstate'] in (consts.PWD_EXPIRED, consts.PWD_RESET)): self.logout() msg = _("Password has expired or has been reset, " "please change the password.") LOG.error(msg) raise exception.StorageBackendException(msg) break if device_id is None: msg = _("Failed to login with all rest URLs.") LOG.error(msg) raise exception.StorageBackendException(msg) return device_id
def build_alert_source(value): view = copy.deepcopy(value) view.pop("auth_key") view.pop("privacy_key") version = view['version'] if version.lower() == 'snmpv2c': view['community_string'] = cryptor.decode(view['community_string']) # Remove the key not belong to snmpv2c view.pop('username') view.pop('security_level') view.pop('auth_protocol') view.pop('privacy_protocol') view.pop('engine_id') view.pop('context_name') elif version.lower() == 'snmpv3': # Remove the key not belong to snmpv3 view.pop('community_string') return dict(view)
def init_rest_client(self): if self.session: self.session.close() self.session = requests.Session() self.session.headers.update({ 'Accept': 'application/json', "Content-Type": "application/json", "X-EMC-REST-CLIENT": "true" }) self.session.auth = requests.auth.HTTPBasicAuth( self.rest_username, cryptor.decode(self.rest_password)) if not self.verify: self.session.verify = False else: LOG.debug("Enable certificate verification, ca_path: {0}".format( self.verify)) self.session.verify = self.verify self.session.trust_env = False self.session.mount("https://", ssl_utils.HostNameIgnoreAdapter())
def login(self): try: data = { 'username': self.rest_username, 'password': cryptor.decode(self.rest_password) } self.init_http_head() token_res = self.do_call(RestHandler.REST_AUTH_URL, data, method='POST') if token_res.json().get('msg') == consts.LOGIN_PASSWORD_ERR: LOG.error( "Login error, Obtaining the token is abnormal. " "status_code:%s, URL: %s", token_res.status_code, RestHandler.REST_AUTH_URL) raise exception.InvalidUsernameOrPassword( 'Obtaining the token is abnormal') if token_res.status_code != consts.SUCCESS_STATUS_CODE or not \ token_res.json().get('api_token'): LOG.error( "Login error, Obtaining the token is abnormal. " "status_code:%s, URL: %s", token_res.status_code, RestHandler.REST_AUTH_URL) raise exception.StorageBackendException( 'Obtaining the token is abnormal') session_res = self.do_call(RestHandler.REST_SESSION_URL, token_res.json(), method='POST') if session_res.status_code != consts.SUCCESS_STATUS_CODE or not \ session_res.json().get('username'): LOG.error( "Login error, Obtaining the session is abnormal." "status_code:%s, URL: %s", session_res.status_code, RestHandler.REST_SESSION_URL) raise exception.StorageBackendException( 'Obtaining the session is abnormal.') except Exception as e: LOG.error("Login error: %s", six.text_type(e)) raise e finally: data = None token_res = None
def _get_redis_backend_url(): cipher_password = getattr(CONF.coordination, 'backend_password', None) if cipher_password is not None: # If password is needed, the password should be # set in config file with cipher text # And in this scenario, these are also needed for backend: # {backend_type}://[{user}]:{password}@{ip}:{port}. plaintext_password = cryptor.decode(cipher_password) # User could be null backend_url = '{backend_type}://{user}:{password}@{server}' \ .format(backend_type=CONF.coordination.backend_type, user=CONF.coordination.backend_user, password=plaintext_password, server=CONF.coordination.backend_server) else: backend_url = '{backend_type}://{server}' \ .format(backend_type=CONF.coordination.backend_type, server=CONF.coordination.backend_server) return backend_url
def logout(self): try: url = RestHandler.LOGOUT_URL if self.session_id is not None: url = '%s/%s/sessions/%s' % \ (RestHandler.COMM_URL, self.storage_device_id, cryptor.decode(self.session_id)) if self.san_address: self.call(url, method='DELETE') url = None self.session_id = None self.storage_device_id = None self.device_model = None self.serial_number = None self.session = None else: LOG.error('logout error:session id not found') except Exception as err: LOG.error('logout error:{}'.format(err)) raise exception.StorageBackendException( reason='Failed to Logout from restful')
def login(self): start = None if 'windows' == platform.system().lower(): # 启动程序 horcmstart.exe start = consts.WINDOWS_HORCM_START.format(self.IH) elif 'linux' == platform.system().lower(): start = consts.LINUX_HORCM_START.format(self.IH) success = NaviClient.execShell(start, consts.HUS, {}, True) if success != consts.HORCM_START_SUCCESSFULLY and success != consts.HORCM_START_ALREADY: LOG.error("{}{}{}".format(start, "启动失败", success)) raise exception.InvalidResults("{}{}{}".format( start, "启动失败", success)) # 拼接命令 navi_password = cryptor.decode(self.navi_password) cli = consts.LOGIN.format(self.navi_username, navi_password, consts.IH_CLI, self.IH) result = NaviClient.execShell(cli, consts.HUS, {}, True) # 分析返回结果 什么都没返回说明登录成功 if result is not None and result != '': LOG.error("登录失败:%s" % result) raise exception.InvalidResults("登录失败:%s" % result) loginToken = 1 return loginToken
def validate_connectivity(ctxt, alert_source): # Fill optional parameters with default values if not set in input if not alert_source.get('port'): alert_source['port'] = constants.DEFAULT_SNMP_CONNECT_PORT if not alert_source.get('context_name'): alert_source['context_name'] = None if not alert_source.get('retry_num'): alert_source['retry_num'] = constants.DEFAULT_SNMP_RETRY_NUM if not alert_source.get('expiration'): alert_source['expiration'] = constants.DEFAULT_SNMP_EXPIRATION_TIME if CONF.snmp_validation_enabled is False: return alert_source storage_id = alert_source.get('storage_id') access_info = db.access_info_get(ctxt, storage_id) access_info = dict(access_info) if access_info.get('model') not in constants.SNMP_SUPPORTED_MODELS: return alert_source cmd_gen = cmdgen.CommandGenerator() version = alert_source.get('version') # Connect to alert source through snmp get to check the configuration try: target = cmdgen.UdpTransportTarget( (alert_source['host'], alert_source['port']), timeout=alert_source['expiration'], retries=alert_source['retry_num']) target.setLocalAddress((CONF.my_ip, 0)) if version.lower() == 'snmpv3': # Register engine observer to get engineId, # Code reference from: http://snmplabs.com/pysnmp/ observer_context = {} cmd_gen.snmpEngine.observer.registerObserver( lambda e, p, v, c: c.update(securityEngineId=v[ 'securityEngineId']), 'rfc3412.prepareDataElements:internal', cbCtx=observer_context) auth_key = None if alert_source['auth_key']: auth_key = encodeutils.to_utf8( cryptor.decode(alert_source['auth_key'])) privacy_key = None if alert_source['privacy_key']: privacy_key = encodeutils.to_utf8( cryptor.decode(alert_source['privacy_key'])) auth_protocol = None privacy_protocol = None if alert_source['auth_protocol']: auth_protocol = constants.AUTH_PROTOCOL_MAP.get( alert_source['auth_protocol'].lower()) if alert_source['privacy_protocol']: privacy_protocol = constants.PRIVACY_PROTOCOL_MAP.get( alert_source['privacy_protocol'].lower()) engine_id = alert_source.get('engine_id') if engine_id: engine_id = OctetString.fromHexString(engine_id) error_indication, __, __, __ = cmd_gen.getCmd( cmdgen.UsmUserData(alert_source['username'], authKey=auth_key, privKey=privacy_key, authProtocol=auth_protocol, privProtocol=privacy_protocol, securityEngineId=engine_id), target, constants.SNMP_QUERY_OID, ) if 'securityEngineId' in observer_context: engine_id = observer_context.get('securityEngineId') alert_source['engine_id'] = binascii.hexlify( engine_id.asOctets()).decode() else: community_string = encodeutils.to_utf8( cryptor.decode(alert_source['community_string'])) error_indication, __, __, __ = cmd_gen.getCmd( cmdgen.CommunityData( community_string, contextName=alert_source['context_name']), target, constants.SNMP_QUERY_OID, ) cmd_gen.snmpEngine.transportDispatcher.closeDispatcher() if not error_indication: return alert_source # Prepare exception with error_indication msg = six.text_type(error_indication) except Exception as e: msg = six.text_type(e) # Since validation occur error, raise exception LOG.error("Configuration validation failed with alert source for " "reason: %s." % msg) raise exception.SNMPConnectionFailed(msg)