Exemple #1
0
    def call(self, url, data=None, method=None):
        """Send requests to server.
        If fail, try another RestURL.
        Increase the judgment of token invalidation
        """
        try:
            res = self.rest_client.do_call(url,
                                           data,
                                           method,
                                           calltimeout=consts.SOCKET_TIMEOUT)
            # Judge whether the access failure is caused by
            # the token invalidation.
            # If the token fails, it will be retrieved again,
            # and the token will be accessed again
            if res is not None:
                # 403  The client request has an invalid session key.
                #      The request came from a different IP address
                # 409  Session key is being used.
                if (res.status_code == consts.ERROR_SESSION_INVALID_CODE
                        or res.status_code
                        == consts.ERROR_SESSION_IS_BEING_USED_CODE):
                    LOG.error("Failed to get token=={0}=={1}".format(
                        res.status_code, res.text))
                    LOG.error("Failed to get token,relogin,Get token again")
                    # if method is logout,return immediately
                    if method == 'DELETE' and RestHandler.\
                            REST_LOGOUT_URL in url:
                        return res
                    self.rest_client.rest_auth_token = None
                    access_session = self.login()
                    # if get token,Revisit url
                    if access_session is not None:
                        res = self.rest_client. \
                            do_call(url, data, method,
                                    calltimeout=consts.SOCKET_TIMEOUT)
                    else:
                        LOG.error('Login res is None')
                elif res.status_code == 503:
                    raise exception.InvalidResults(res.text)
            else:
                LOG.error('Rest exec failed')

            return res
        except exception.DelfinException as e:
            err_msg = "Call failed: %s" % (six.text_type(e))
            LOG.error(err_msg)
            raise e
        except Exception as e:
            err_msg = "Get RestHandler.call failed: %s" % (six.text_type(e))
            LOG.error(err_msg)
            raise exception.InvalidResults(err_msg)
Exemple #2
0
 def fix_alert(self, alert):
     command_line = 'cheventlog -fix %s' % alert
     result = self.exec_ssh_command(command_line)
     if result:
         if self.ALERT_NOT_FOUND_CODE not in result:
             raise exception.InvalidResults(six.text_type(result))
         LOG.warning("Alert %s doesn't exist.", alert)
Exemple #3
0
def check_storage_consistency(context, storage_id, storage_new):
    """Check storage response returned by driver whether it matches the
    storage stored in database.

    :param context: The context of delfin.
    :type context: delfin.context.RequestContext
    :param storage_id: The uuid of storage in database.
    :type storage_id: string
    :param storage_new: The storage response returned by driver.
    :type storage_new: dict
    """
    if not storage_new:
        raise exception.StorageBackendNotFound()

    if not storage_new.get('serial_number'):
        msg = _("Serial number should be provided by storage.")
        raise exception.InvalidResults(msg)

    storage_present = db.storage_get(context, storage_id)
    if storage_new['serial_number'] != storage_present['serial_number']:
        msg = (
            _("Serial number %s does not match "
              "the existing storage serial number %s.") %
            (storage_new['serial_number'], storage_present['serial_number']))
        raise exception.StorageSerialNumberMismatch(msg)
    def call(self,
             url,
             data=None,
             method=None,
             calltimeout=consts.SOCKET_TIMEOUT):
        try:
            res = self.call_with_token(url, data, method, calltimeout)
            if (res.status_code == consts.ERROR_SESSION_INVALID_CODE
                    or res.status_code
                    == consts.ERROR_SESSION_IS_BEING_USED_CODE):
                LOG.error(
                    "Failed to get token=={0}=={1},get token again".format(
                        res.status_code, res.text))
                # if method is logout,return immediately
                if method == 'DELETE' and RestHandler. \
                        LOGOUT_URL in url:
                    return res
                if self.get_token():
                    res = self.call_with_token(url, data, method, calltimeout)
                else:
                    LOG.error('Login error,get access_session failed')
            elif res.status_code == 503:
                raise exception.InvalidResults(res.text)

            return res

        except Exception as e:
            err_msg = "Get RestHandler.call failed: %s" % (six.text_type(e))
            LOG.error(err_msg)
            raise e
Exemple #5
0
    def list_qtrees(self, storage_id):
        try:
            qt_list = []
            qt_info = self.exec_ssh_command(
                netapp_constants.QTREE_SHOW_DETAIL_COMMAND)
            qt_arr = qt_info.split(netapp_constants.QTREE_SPLIT_STR)
            qt_map = {}
            for qt in qt_arr[1:]:
                self.handle_detail(qt, qt_map, split=':')
                q = {
                    'name': qt_map['QtreeName'],
                    'storage_id': storage_id,
                    'native_qtree_id': qt_map['Actual(Non-Junction)QtreePath'],
                    'native_filesystem_id': qt_map['VolumeName'],
                    'security_mode': qt_map['SecurityStyle'],
                }
                qt_list.append(q)

            return qt_list
        except exception.DelfinException as err:
            err_msg = "Failed to get storage qtrees from " \
                      "netapp_fas fas: %s" % (six.text_type(err))
            LOG.error(err_msg)
            raise err

        except Exception as err:
            err_msg = "Failed to get storage qtrees from " \
                      "netapp_fas fas: %s" % (six.text_type(err))
            LOG.error(err_msg)
            raise exception.InvalidResults(err_msg)
Exemple #6
0
    def parse_alert(context, alert):
        try:
            alert_model = dict()
            alert_model['alert_id'] = alert.get(HitachiVspDriver.REFCODE_OID)
            alert_model['alert_name'] = alert.get(HitachiVspDriver.DESC_OID)
            severity = HitachiVspDriver.TRAP_ALERT_LEVEL_MAP.get(
                alert.get(HitachiVspDriver.OID_SEVERITY),
                constants.Severity.INFORMATIONAL)
            alert_model['severity'] = severity
            alert_model['category'] = constants.Category.FAULT
            alert_model['type'] = constants.EventType.EQUIPMENT_ALARM
            aler_time = '%s%s' % (alert.get(HitachiVspDriver.TRAP_DATE_OID),
                                  alert.get(HitachiVspDriver.TRAP_TIME_OID))
            pattern = '%Y/%m/%d%H:%M:%S'
            occur_time = time.strptime(aler_time, pattern)
            alert_model['occur_time'] = int(
                time.mktime(occur_time) * HitachiVspDriver.SECONDS_TO_MS)
            alert_model['description'] = alert.get(HitachiVspDriver.DESC_OID)
            alert_model['resource_type'] = constants.DEFAULT_RESOURCE_TYPE
            alert_model['location'] = alert.get(
                HitachiVspDriver.TRAP_NICKNAME_OID)
            alert_model['match_key'] = hashlib.md5(
                alert.get(HitachiVspDriver.DESC_OID).encode()).hexdigest()

            return alert_model
        except Exception as e:
            LOG.error(e)
            msg = ("Failed to build alert model as some attributes missing in"
                   " alert message:%s") % (six.text_type(e))
            raise exception.InvalidResults(msg)
Exemple #7
0
    def list_quotas(self, context):
        try:
            # Get list of OceanStor quotas details
            quotas_list = []
            filesystems = self.client.get_all_filesystems()
            for fs in filesystems:
                fs_id = fs["ID"]
                quotas = self.client.get_all_filesystem_quotas(fs_id)
                if quotas:
                    qs = self._list_quotas(quotas, fs_id, None)
                    quotas_list.extend(qs)

            qtrees = self.client.get_all_qtrees(filesystems)
            for qt in qtrees:
                qt_id = qt["ID"]
                quotas = self.client.get_all_qtree_quotas(qt_id)
                if quotas:
                    qs = self._list_quotas(quotas, None, qt_id)
                    quotas_list.extend(qs)

            return quotas_list

        except exception.DelfinException as err:
            err_msg = "Failed to get quotas from OceanStor: %s" %\
                      (six.text_type(err))
            LOG.error(err_msg)
            raise err

        except Exception as err:
            err_msg = "Failed to get quotas from OceanStor: %s" %\
                      (six.text_type(err))
            LOG.error(err_msg)
            raise exception.InvalidResults(err_msg)
Exemple #8
0
 def cli_domain_to_dict(self, resource_info):
     obj_list = []
     obj_model = {}
     try:
         obj_infos = resource_info.split('\n')
         node_value = ''
         for obj_info in obj_infos:
             str_line = obj_info.strip()
             # Use "IP Address" to determine whether it is a new object
             if str_line and str_line.startswith('IP Address:'):
                 obj_list = self.add_model_to_list(obj_model, obj_list)
                 obj_model = {}
             if str_line:
                 if 'Master' in str_line:
                     obj_model['master'] = 'True'
                     str_line = str_line.replace('(Master)', '')
                 str_info = self.split_str_by_colon(str_line)
                 if str_line and str_line.startswith('Node:'):
                     node_value = str_info[1]
                     continue
                 if str_line and str_line.startswith('IP Address:'):
                     obj_model['node'] = node_value
                 obj_model = self.str_info_to_model(str_info, obj_model)
         # If the last object is not added to the LIST,
         # perform the join operation
         obj_list = self.add_model_to_list(obj_model, obj_list)
     except Exception as e:
         err_msg = "arrange domain info error: %s", six.text_type(e)
         LOG.error(err_msg)
         raise exception.InvalidResults(err_msg)
     return obj_list
Exemple #9
0
    def list_shares(self, storage_id):
        try:
            shares_list = []
            qtree_list = self.list_qtrees(None)
            protocol_info = self.ssh_do_exec(
                constant.SHARE_AGREEMENT_SHOW_COMMAND)
            protocol_map = {}
            protocol_arr = self.get_table_data(protocol_info)
            for protocol in protocol_arr:
                agr_arr = protocol.split()
                if len(agr_arr) > 1:
                    protocol_map[agr_arr[0]] = agr_arr[1]
            vserver_info = self.ssh_do_exec(constant.VSERVER_SHOW_COMMAND)
            vserver_array = self.get_table_data(vserver_info)
            for vserver in vserver_array:
                vserver_name = vserver.split()
                if len(vserver_name) > 1:
                    shares_list += self.get_cifs_shares(
                        storage_id, vserver_name[0], qtree_list, protocol_map)
            shares_list += self.get_nfs_shares(storage_id, qtree_list,
                                               protocol_map)
            return shares_list
        except exception.DelfinException as err:
            err_msg = "Failed to get storage shares from " \
                      "netapp cmode: %s" % (six.text_type(err))
            LOG.error(err_msg)
            raise err

        except Exception as err:
            err_msg = "Failed to get storage shares from " \
                      "netapp cmode: %s" % (six.text_type(err))
            LOG.error(err_msg)
            raise exception.InvalidResults(err_msg)
    def process_alert_info(self, alert):
        """Fills alert model using driver manager interface."""
        ctxt = context.get_admin_context()
        storage = db.storage_get(ctxt, alert['storage_id'])
        alert_model = {}

        try:
            alert_model = self.driver_manager.parse_alert(
                ctxt, alert['storage_id'], alert)
            # Fill storage specific info
            if alert_model:
                storage = self.get_storage_from_parsed_alert(
                    ctxt, storage, alert_model)
                alert_util.fill_storage_attributes(alert_model, storage)
        except exception.IncompleteTrapInformation as e:
            LOG.warning(e)
            threading.Thread(target=self.sync_storage_alert,
                             args=(ctxt, alert['storage_id'])).start()
        except exception.AlertSourceNotFound:
            LOG.info("Could not identify alert source from parsed alert. "
                     "Skipping the dispatch of alert")
            return
        except Exception as e:
            LOG.error(e)
            raise exception.InvalidResults(
                "Failed to fill the alert model from driver.")

        # Export to base exporter which handles dispatch for all exporters
        if alert_model:
            LOG.info("Dispatching one SNMP Trap to {} with sn {}".format(
                alert_model['storage_id'], alert_model['serial_number']))
            self.exporter_manager.dispatch(ctxt, [alert_model])
Exemple #11
0
 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
Exemple #12
0
 def parse_alert(alert):
     alert_model = dict()
     try:
         alert_dict = alert.split(' ')
         for alert_json in alert_dict:
             alert_detail = alert_json.split('=')[1]
             if consts.OID_SEVERITY in alert_json:
                 severity = consts.TRAP_ALERT_MAP.get(
                     alert_detail, constants.Severity.INFORMATIONAL)
                 alert_model['severity'] = severity
             elif consts.OID_EVENT_ID in alert_json:
                 alert_model['alert_name'] = alert_detail.replace('\"', '')
             elif consts.OID_EVENT_TYPE in alert_json:
                 alert_desc = alert_detail.split('.')[2].lower().replace(
                     '_', ' ')
                 alert_model['description'] = alert_desc
                 alert_model['location'] = alert_desc
             elif consts.OID_ERR_ID in alert_json:
                 alert_model['alert_id'] = str(
                     alert_detail.replace('\"', ''))
             alert_model['category'] = constants.Category.FAULT
             alert_model['type'] = constants.EventType.EQUIPMENT_ALARM
             now = time.time()
             alert_model['occur_time'] = \
                 int(round(now * consts.DEFAULT_ALERTS_TIME_CONVERSION))
         return alert_model
     except Exception as e:
         LOG.error(e)
         msg = "Failed to build alert model: %s." % (six.text_type(e))
         raise exception.InvalidResults(msg)
Exemple #13
0
 def list_masking_views(self, storage_id):
     list_masking_views_list = []
     try:
         storage_view = self.get_rest_info(consts.REST_SCALEIO_VOLUMES)
         for map_json in (storage_view or []):
             view_name = map_json.get('name')
             volume_id = map_json.get('id')
             map_sdc_list = map_json.get('mappedSdcInfo')
             if map_sdc_list:
                 for map_sdc in map_sdc_list:
                     sdc_id = map_sdc.get('sdcId')
                     view_map = {
                         "name": view_name + sdc_id + volume_id,
                         "description": view_name,
                         "storage_id": storage_id,
                         "native_masking_view_id":
                         view_name + sdc_id + volume_id,
                         'native_volume_id': volume_id,
                         'native_storage_host_id': sdc_id
                     }
                     list_masking_views_list.append(view_map)
         return list_masking_views_list
     except exception.DelfinException as err:
         err_msg = "Get Storage Views Error: %s" % err.msg
         LOG.error(err_msg)
         raise err
     except Exception as e:
         LOG.error("Get Storage Views Error: %s", six.text_type(e))
         raise exception.InvalidResults(e)
Exemple #14
0
 def list_storage_hosts(self, storage_id):
     host_list = []
     try:
         storage_hosts = self.get_rest_info(consts.REST_SCALIO_HOSTS)
         for host_json in (storage_hosts or []):
             status = host_json.get('mdmConnectionState')
             if 'Connected' == status:
                 status = constants.HostStatus.NORMAL
             elif 'Disconnected' == status:
                 status = constants.HostStatus.OFFLINE
             ip_address = host_json.get('sdcIp')
             soft_version = host_json.get('softwareVersionInfo')
             host_dict = {
                 "name": host_json.get('sdcGuid'),
                 "description": ip_address + soft_version,
                 "storage_id": storage_id,
                 "native_storage_host_id": host_json.get('id'),
                 "os_type": host_json.get('osType'),
                 "status": status,
                 "ip_address": ip_address
             }
             host_list.append(host_dict)
         return host_list
     except exception.DelfinException as err:
         err_msg = "Get Storage hosts error: %s" % err.msg
         LOG.error(err_msg)
         raise err
     except Exception as e:
         LOG.error("Get Storage hosts error: %s", six.text_type(e))
         raise exception.InvalidResults(e)
Exemple #15
0
 def list_disks(self, storage_id):
     disks_list = []
     try:
         storage_disks_json = self.get_rest_info(consts.REST_SCALEIO_DISKS)
         for json_disk in (storage_disks_json or []):
             device_status = json_disk.get('deviceState')
             capacity = json_disk.get('maxCapacityInKb')
             status = constants.DiskStatus.NORMAL
             if device_status != 'Normal':
                 status = constants.DiskStatus.OFFLINE
             disk_map = {
                 'native_disk_id': json_disk.get('id'),
                 'name': json_disk.get('name'),
                 'status': status,
                 'storage_id': storage_id,
                 'native_disk_group_id': json_disk.get('sdsId'),
                 'serial_number': json_disk.get('id'),
                 'capacity': int(capacity) * units.Ki,
                 'health_score': status
             }
             disks_list.append(disk_map)
         return disks_list
     except exception.DelfinException as err:
         err_msg = "Get Storage disk error: %s" % err.msg
         LOG.error(err_msg)
         raise err
     except Exception as e:
         LOG.error("Get Storage disk error: %s", six.text_type(e))
         raise exception.InvalidResults(e)
Exemple #16
0
 def cli_cpu_to_dict(self, resource_info):
     obj_model = {}
     try:
         obj_list = []
         obj_infos = resource_info.split('\n')
         for obj_info in obj_infos:
             str_line = obj_info.strip()
             if str_line:
                 if 'CPU Module' in str_line:
                     str_line = '%s:True' % str_line
                 str_info = self.split_str_by_colon(str_line)
                 obj_model = self.str_info_to_model(str_info, obj_model)
             else:
                 obj_list = self.add_model_to_list(obj_model, obj_list)
                 obj_model = {}
         for cpu_module in obj_list:
             if cpu_module.get('cpu_module'):
                 obj_model[
                     cpu_module.get('emc_serial_number')] = cpu_module.get(
                     'assembly_name')
     except Exception as e:
         err_msg = "arrange cpu info error: %s", six.text_type(e)
         LOG.error(err_msg)
         raise exception.InvalidResults(err_msg)
     return obj_model
Exemple #17
0
 def cli_disk_to_list(self, resource_info):
     obj_list = []
     obj_model = {}
     try:
         obj_infos = resource_info.split('\n')
         for obj_info in obj_infos:
             str_line = obj_info.strip()
             if str_line:
                 if str_line.startswith('Bus '):
                     disk_name = 'disk_name:%s' % str_line
                     str_info = self.split_str_by_colon(disk_name)
                     obj_model = self.str_info_to_model(str_info, obj_model)
                     str_line = "disk id:%s" % (str_line.replace(' ', ''))
                 if ':' not in str_line:
                     continue
                 str_info = self.split_str_by_colon(str_line)
                 obj_model = self.str_info_to_model(str_info, obj_model)
             else:
                 obj_list = self.add_model_to_list(obj_model, obj_list)
                 obj_model = {}
         # If the last object is not added to the LIST,
         # perform the join operation
         obj_list = self.add_model_to_list(obj_model, obj_list)
     except Exception as e:
         err_msg = "cli resource to list error: %s", six.text_type(e)
         LOG.error(err_msg)
         raise exception.InvalidResults(err_msg)
     return obj_list
Exemple #18
0
    def parse_alert(self, context, alert):
        """Parse alert data got from alert manager and fill the alert model."""
        # Check for mandatory alert attributes
        for attr in self._mandatory_alert_attributes:
            if not alert.get(attr):
                msg = "Mandatory information %s missing in alert message. " \
                      % attr
                raise exception.InvalidInput(msg)

        try:
            alert_model = dict()
            # These information are sourced from device registration info
            alert_model['alert_id'] = alert.get('messageCode')
            alert_model['alert_name'] = alert.get('messageCode')
            alert_model['severity'] = self.SEVERITY_MAP.get(
                alert.get('severity'), constants.Severity.NOT_SPECIFIED)
            alert_model['category'] = self.CATEGORY_MAP.get(
                alert.get('state'), constants.Category.NOT_SPECIFIED)
            alert_model['type'] = constants.EventType.EQUIPMENT_ALARM
            alert_model['sequence_number'] = alert.get('id')
            alert_model['occur_time'] = self.get_time_stamp(
                alert.get('timeOccurred'))
            alert_model['description'] = alert.get('details')
            alert_model['resource_type'] = constants.DEFAULT_RESOURCE_TYPE
            alert_model['location'] = alert.get('component')

            if alert.get('state') == 'autofixed':
                alert_model['clear_category'] = constants.ClearType.AUTOMATIC
            return alert_model
        except Exception as e:
            LOG.error(e)
            msg = (_("Failed to build alert model as some attributes missing "
                     "in alert message."))
            raise exception.InvalidResults(msg)
Exemple #19
0
 def cli_lun_to_list(self, resource_info):
     obj_list = []
     obj_model = {}
     try:
         obj_infos = resource_info.split('\n')
         for obj_info in obj_infos:
             str_line = obj_info.strip()
             if str_line and str_line.startswith(consts.LUN_ID_KEY):
                 obj_list = self.add_model_to_list(obj_model, obj_list)
                 obj_model = {}
             if str_line:
                 if str_line.startswith(consts.LUN_ID_KEY):
                     str_line = str_line.replace(consts.LUN_ID_KEY,
                                                 'LOGICAL UNIT NUMBER:')
                 if str_line.startswith(consts.LUN_NAME_KEY):
                     str_line = str_line.replace(consts.LUN_NAME_KEY,
                                                 'Name:')
                 if ':' not in str_line:
                     continue
                 str_info = self.split_str_by_colon(str_line)
                 obj_model = self.str_info_to_model(str_info, obj_model)
         obj_list = self.add_model_to_list(obj_model, obj_list)
     except Exception as e:
         err_msg = "arrange lun info error: %s", six.text_type(e)
         LOG.error(err_msg)
         raise exception.InvalidResults(err_msg)
     return obj_list
Exemple #20
0
 def list_controllers(self, context):
     try:
         controller_list = []
         controller_info = self.rest_handler.get_all_controllers()
         if controller_info is not None:
             pool_entries = controller_info.get('entries')
             for pool in pool_entries:
                 content = pool.get('content')
                 if not content:
                     continue
                 health_value = content.get('health', {}).get('value')
                 status = UnityStorDriver.CONTROLLER_STATUS_MAP.get(
                     health_value,
                     constants.ControllerStatus.FAULT
                 )
                 controller_result = {
                     'name': content.get('name'),
                     'storage_id': self.storage_id,
                     'native_controller_id': content.get('id'),
                     'status': status,
                     'location': content.get('slotNumber'),
                     'memory_size':
                         int(content.get('memorySize')) * units.Mi
                 }
                 controller_list.append(controller_result)
         return controller_list
     except Exception as err:
         err_msg = "Failed to get controller attributes from Unity: %s" %\
                   (six.text_type(err))
         LOG.error(err_msg)
         raise exception.InvalidResults(err_msg)
    def parse_alert(context, alert):
        """Parse alert data and fill the alert model."""
        # Check for mandatory alert attributes
        alert = oid_mapper.OidMapper.map_oids(alert)
        LOG.info("Get alert from storage: %s", alert)

        for attr in AlertHandler._mandatory_alert_attributes:
            if not alert.get(attr):
                msg = "Mandatory information %s missing in alert message. " \
                      % attr
                raise exception.InvalidInput(msg)

        try:
            alert_model = dict()
            # These information are sourced from device registration info
            alert_model['alert_id'] = alert['hwIsmReportingAlarmAlarmID']
            alert_model['alert_name'] = alert['hwIsmReportingAlarmFaultTitle']
            alert_model['severity'] = AlertHandler.SEVERITY_MAP.get(
                alert['hwIsmReportingAlarmFaultLevel'],
                constants.Severity.NOT_SPECIFIED)
            alert_model['category'] = AlertHandler.CATEGORY_MAP.get(
                alert['hwIsmReportingAlarmFaultCategory'],
                constants.Category.NOT_SPECIFIED)
            alert_model['type'] = AlertHandler.TYPE_MAP.get(
                alert['hwIsmReportingAlarmFaultType'],
                constants.EventType.NOT_SPECIFIED)
            alert_model['sequence_number'] \
                = alert['hwIsmReportingAlarmSerialNo']
            occur_time = datetime.strptime(
                alert['hwIsmReportingAlarmFaultTime'],
                AlertHandler.TIME_PATTERN)
            alert_model['occur_time'] = int(occur_time.timestamp() * 1000)

            description = alert['hwIsmReportingAlarmAdditionInfo']
            if AlertHandler._is_hex(description):
                description = bytes.fromhex(description[2:]).decode('ascii')
            alert_model['description'] = description

            recovery_advice = alert['hwIsmReportingAlarmRestoreAdvice']
            if AlertHandler._is_hex(recovery_advice):
                recovery_advice = bytes.fromhex(
                    recovery_advice[2:]).decode('ascii')

            alert_model['recovery_advice'] = recovery_advice

            alert_model['resource_type'] = constants.DEFAULT_RESOURCE_TYPE
            alert_model['location'] = 'Node code=' \
                                      + alert['hwIsmReportingAlarmNodeCode']

            if alert.get('hwIsmReportingAlarmLocationInfo'):
                alert_model['location'] \
                    = alert_model['location'] + ',' + alert[
                    'hwIsmReportingAlarmLocationInfo']

            return alert_model
        except Exception as e:
            LOG.error(e)
            msg = (_("Failed to build alert model as some attributes missing "
                     "in alert message."))
            raise exception.InvalidResults(msg)
Exemple #22
0
    def exec(command_str, storage_model, exception_map, stdin_value=None):
        try:
            p = Popen(command_str, stdin=PIPE, stdout=PIPE, stderr=PIPE,
                      shell=False)
        except FileNotFoundError as e:
            err_msg = storage_model + \
                " cli tool not found: %s" % (six.text_type(e))
            LOG.error(err_msg)
            raise exception.ComponentNotFound(storage_model + " cli")
        except Exception as e:
            err_msg = storage_model + \
                " cli exec error: %s" % (six.text_type(e))
            LOG.error(err_msg)
            raise exception.InvalidResults(err_msg)

        if stdin_value:
            out, err = p.communicate(
                input=bytes(stdin_value, encoding='utf-8'))
        else:
            out = p.stdout.read()
        if isinstance(out, bytes):
            out = out.decode("utf-8")
        result = out.strip()
        if result:
            # Determine whether an exception occurs according
            # to the returned information
            for exception_key in exception_map.keys():
                if exception_key in result:
                    LOG.error(storage_model + ' exec failed: %s' % result)
                    raise exception_map.get(exception_key)(result)

        return result
Exemple #23
0
 def parse_alert(alert):
     try:
         alert_info = alert.get(NetAppHandler.OID_TRAP_DATA)
         alert_arr = alert_info.split(":")
         if len(alert_arr) > 1:
             alert_name = alert_arr[0]
             description = alert_arr[1]
             if netapp_constants.SEVERITY_MAP.get(alert_name):
                 severity = netapp_constants.SEVERITY_MAP.get(alert_name)
                 a = {
                     'alert_id': '',
                     'alert_name': alert_name,
                     'severity': severity,
                     'category': constants.Category.EVENT,
                     'type': constants.EventType.EQUIPMENT_ALARM,
                     'occur_time': int(time.time()),
                     'description': description,
                     'sequence_number': '',
                     'resource_type': constants.DEFAULT_RESOURCE_TYPE,
                     'location': ''
                 }
                 return a
     except exception.DelfinException as e:
         err_msg = "Failed to parse alert from " \
                   "netapp_fas fas: %s" % (six.text_type(e.msg))
         LOG.error(err_msg)
         raise e
     except Exception as err:
         err_msg = "Failed to parse alert from " \
                   "netapp_fas fas: %s" % (six.text_type(err))
         LOG.error(err_msg)
         raise exception.InvalidResults(err_msg)
Exemple #24
0
 def parse_alert(alert):
     try:
         alert_model = dict()
         alert_name = SSHHandler.handle_split(
             alert.get(SSHHandler.OID_ERR_ID), ':', 1)
         error_info = SSHHandler.handle_split(
             alert.get(SSHHandler.OID_ERR_ID), ':', 0)
         alert_id = SSHHandler.handle_split(error_info, '=', 1)
         severity = SSHHandler.TRAP_SEVERITY_MAP.get(
             alert.get(SSHHandler.OID_SEVERITY),
             constants.Severity.INFORMATIONAL)
         alert_model['alert_id'] = str(alert_id)
         alert_model['alert_name'] = alert_name
         alert_model['severity'] = severity
         alert_model['category'] = constants.Category.FAULT
         alert_model['type'] = constants.EventType.EQUIPMENT_ALARM
         alert_model['sequence_number'] = SSHHandler. \
             handle_split(alert.get(SSHHandler.OID_SEQ_NUMBER), '=', 1)
         timestamp = SSHHandler. \
             handle_split(alert.get(SSHHandler.OID_LAST_TIME), '=', 1)
         time_type = '%a %b %d %H:%M:%S %Y'
         occur_time = int(time.mktime(time.strptime(timestamp, time_type)))
         alert_model['occur_time'] = int(occur_time *
                                         SSHHandler.SECONDS_TO_MS)
         alert_model['description'] = alert_name
         alert_model['resource_type'] = SSHHandler.handle_split(
             alert.get(SSHHandler.OID_OBJ_TYPE), '=', 1)
         alert_model['location'] = SSHHandler.handle_split(
             alert.get(SSHHandler.OID_OBJ_NAME), '=', 1)
         return alert_model
     except Exception as e:
         LOG.error(e)
         msg = ("Failed to build alert model as some attributes missing "
                "in alert message:%s.") % (six.text_type(e))
         raise exception.InvalidResults(msg)
Exemple #25
0
 def parse_alert(context, alert):
     try:
         alert_model = dict()
         alert_model['alert_id'] = alert.get(consts.PARSE_ALERT_ALERT_ID)
         alert_model['severity'] = consts.PARSE_ALERT_SEVERITY_MAP.get(
             alert.get(consts.PARSE_ALERT_SEVERITY),
             constants.Severity.NOT_SPECIFIED)
         alert_model['category'] = constants.Category.FAULT
         alert_model['occur_time'] = utils.utcnow_ms()
         alert_model['description'] = '({}:{}): {}'.format(
             alert.get(consts.PARSE_ALERT_STORAGE_NAME),
             alert.get(consts.PARSE_ALERT_CONTROLLER_NAME),
             alert.get(consts.PARSE_ALERT_DESCRIPTION))
         alert_model['location'] = alert.get(
             consts.PARSE_ALERT_CONTROLLER_NAME)
         alert_model['type'] = constants.EventType.EQUIPMENT_ALARM
         alert_model['resource_type'] = constants.DEFAULT_RESOURCE_TYPE
         alert_model['alert_name'] = alert.get(
             consts.PARSE_ALERT_ALERT_NAME)
         alert_model['sequence_number'] = alert.get(
             consts.PARSE_ALERT_ALERT_ID)
         alert_model['match_key'] = hashlib.md5(
             str(alert.get(
                 consts.PARSE_ALERT_ALERT_ID)).encode()).hexdigest()
         return alert_model
     except Exception as e:
         LOG.error(e)
         msg = (_("Failed to build alert model as some attributes missing"))
         raise exception.InvalidResults(msg)
Exemple #26
0
 def cli_res_to_list(self, resource_info):
     obj_list = []
     obj_model = {}
     try:
         obj_infos = resource_info.split('\n')
         for obj_info in obj_infos:
             str_line = obj_info.strip()
             if str_line:
                 if consts.DISK_ID_KEY in str_line:
                     str_line = str_line.replace(consts.DISK_ID_KEY,
                                                 "disk id:")
                 if consts.LUN_ID_KEY in str_line:
                     str_line = str_line.replace(consts.LUN_ID_KEY,
                                                 "lun id:")
                 if ':' not in str_line:
                     continue
                 str_info = self.split_str_by_colon(str_line)
                 obj_model = self.str_info_to_model(str_info, obj_model)
             else:
                 obj_list = self.add_model_to_list(obj_model, obj_list)
                 obj_model = {}
         # If the last object is not added to the LIST,
         # perform the join operation
         obj_list = self.add_model_to_list(obj_model, obj_list)
     except Exception as e:
         err_msg = "cli resource to list error: %s", six.text_type(e)
         LOG.error(err_msg)
         raise exception.InvalidResults(err_msg)
     return obj_list
Exemple #27
0
    def parse_alert(self, context, alert):
        """Parse alert data got from alert manager and fill the alert model."""

        try:
            alert_model = {}
            # These information are sourced from device registration info
            alert_model['me_dn'] = alert['storage_id']
            alert_model['me_name'] = alert['storage_name']
            alert_model['manufacturer'] = alert['vendor']
            alert_model['product_name'] = alert['model']

            # Fill default values for alert attributes
            alert_model['category'] = alert['hwIsmReportingAlarmFaultCategory']
            alert_model['location'] = alert['hwIsmReportingAlarmLocationInfo']
            alert_model['event_type'] = alert['hwIsmReportingAlarmFaultType']
            alert_model['severity'] = alert['hwIsmReportingAlarmFaultLevel']
            alert_model['probable_cause'] \
                = alert['hwIsmReportingAlarmAdditionInfo']
            alert_model['me_category'] = self.default_me_category
            alert_model['occur_time'] = alert['hwIsmReportingAlarmFaultTime']
            alert_model['alarm_id'] = alert['hwIsmReportingAlarmAlarmID']
            alert_model['alarm_name'] = alert['hwIsmReportingAlarmFaultTitle']
            alert_model['device_alert_sn'] = \
                alert['hwIsmReportingAlarmSerialNo']
            alert_model['clear_type'] = ""
            alert_model['match_key'] = ""
            alert_model['native_me_dn'] = ""
            return alert_model
        except Exception as e:
            LOG.error(e)
            msg = (_("Failed to build alert model as some attributes missing "
                     "in alert message."))
            raise exception.InvalidResults(msg)
Exemple #28
0
 def cli_raid_to_list(self, resource_info):
     obj_list = []
     obj_model = {}
     try:
         obj_infos = resource_info.split('\n')
         for obj_info in obj_infos:
             str_line = obj_info.strip()
             # Use 'RaidGroup ID' to determine whether it is
             # a new object
             if str_line and str_line.startswith('RaidGroup ID:'):
                 obj_list = self.add_model_to_list(obj_model, obj_list)
                 obj_model = {}
             if str_line:
                 if ':' not in str_line:
                     continue
                 str_info = self.split_str_by_colon(str_line)
                 obj_model = self.str_info_to_model(str_info, obj_model)
         # If the last object is not added to the LIST,
         # perform the join operation
         obj_list = self.add_model_to_list(obj_model, obj_list)
     except Exception as e:
         err_msg = "arrange raid info error: %s", six.text_type(e)
         LOG.error(err_msg)
         raise exception.InvalidResults(err_msg)
     return obj_list
Exemple #29
0
    def parse_queried_alerts(self, alert_model_list, alert_list, query_para):
        alerts = alert_list.get('data', {}).get('events')
        if alerts:
            for alert in alerts:
                try:
                    occur_time = int(time.mktime(time.strptime(
                        alert.get('time'),
                        self.TIME_PATTERN))) * AlertHandler.SECONDS_TO_MS
                    if not alert_util.is_alert_in_time_range(
                            query_para, occur_time):
                        continue

                    alert_model = {}
                    alert_model['alert_id'] = alert.get('type')
                    alert_model['alert_name'] = alert.get('description')
                    alert_model['severity'] = self.ALERT_LEVEL_MAP.get(
                        alert.get('severity'),
                        constants.Severity.INFORMATIONAL)
                    alert_model['description'] = alert.get('description')
                    alert_model['category'] = constants.Category.FAULT
                    alert_model['type'] = constants.EventType.EQUIPMENT_ALARM
                    alert_model['sequence_number'] = alert.get('id')
                    alert_model['occur_time'] = occur_time
                    alert_model['resource_type'] = \
                        constants.DEFAULT_RESOURCE_TYPE
                    alert_model_list.append(alert_model)
                except Exception as e:
                    LOG.error(e)
                    err_msg = "Failed to build alert model as some" \
                              " attributes missing in queried alerts: %s"\
                              % (six.text_type(e))
                    raise exception.InvalidResults(err_msg)
Exemple #30
0
 def cli_io_config_to_dict(self, resource_info):
     obj_model = {}
     try:
         obj_list = []
         obj_infos = resource_info.split('\n')
         for obj_info in obj_infos:
             str_line = obj_info.strip()
             if str_line:
                 if ':' in str_line:
                     str_info = self.split_str_by_colon(str_line)
                     obj_model = self.str_info_to_model(str_info, obj_model)
             else:
                 obj_list = self.add_model_to_list(obj_model, obj_list)
                 obj_model = {}
         for config in obj_list:
             if config.get('i/o_module_slot'):
                 key = '%s_%s' % (
                     config.get('sp_id'), config.get('i/o_module_slot'))
                 obj_model[key] = config.get('i/o_module_type').replace(
                     ' Channel', '')
     except Exception as e:
         err_msg = "arrange io port config info error: %s", six.text_type(e)
         LOG.error(err_msg)
         raise exception.InvalidResults(err_msg)
     return obj_model