示例#1
0
async def update_plugin(request: web.Request) -> web.Response:
    """ update plugin

    :Example:
        curl -X PUT http://localhost:8081/fledge/plugins/south/sinusoid/update
        curl -X PUT http://localhost:8081/fledge/plugins/north/http_north/update
    """
    _type = request.match_info.get('type', None)
    name = request.match_info.get('name', None)
    try:
        # TODO: FOGL-3063, FOGL-3064
        _type = _type.lower()
        if _type not in ['north', 'south']:
            raise ValueError("Invalid plugin type. Must be 'north' or 'south'")

        # Check requested plugin name is installed or not
        installed_plugins = PluginDiscovery.get_plugins_installed(_type, False)
        installed_plugin_name = [
            p_name["name"] for p_name in installed_plugins
        ]
        if name not in installed_plugin_name:
            raise KeyError(
                "{} plugin is not yet installed. So update is not possible.".
                format(name))

        # Tracked plugins from asset tracker
        tracked_plugins = await _get_plugin_and_sch_name_from_asset_tracker(
            _type)
        sch_list = []
        for p in tracked_plugins:
            if name == p['plugin']:
                sch_info = await _get_sch_id_and_enabled_by_name(p['service'])
                if sch_info[0]['enabled'] == 't':
                    status, reason = await server.Server.scheduler.disable_schedule(
                        uuid.UUID(sch_info[0]['id']))
                    if status:
                        _logger.warning(
                            "{} {} instance is disabled as {} plugin is updating.."
                            .format(p['service'], _type, p['plugin']))
                        sch_list.append(sch_info[0]['id'])

        # Plugin update is running as a background task
        loop = request.loop
        request._type = _type
        request._name = name
        request._sch_list = sch_list
        loop.call_later(1, do_update, request)
    except KeyError as ex:
        raise web.HTTPNotFound(reason=ex)
    except ValueError as ex:
        raise web.HTTPBadRequest(reason=ex)
    except Exception as ex:
        raise web.HTTPInternalServerError(reason=ex)

    return web.json_response({
        "message":
        "{} plugin update in process. Wait for few minutes to complete.".
        format(name)
    })
示例#2
0
文件: service.py 项目: lclfans/fledge
async def update_service(request: web.Request) -> web.Response:
    """ update service

    :Example:
        curl -sX PUT http://localhost:8081/fledge/service/notification/notification/update
    """
    _type = request.match_info.get('type', None)
    name = request.match_info.get('name', None)
    try:
        _type = _type.lower()
        if _type != 'notification':
            raise ValueError("Invalid service type. Must be 'notification'")

        # Check requested service name is installed or not
        installed_services = get_service_installed()
        if name not in installed_services:
            raise KeyError(
                "{} service is not installed yet. Hence update is not possible."
                .format(name))

        storage_client = connect.get_storage_async()
        # TODO: process_name ends with "_c" suffix
        payload = PayloadBuilder().SELECT(
            "id", "enabled",
            "schedule_name").WHERE(['process_name', '=',
                                    '{}_c'.format(_type)]).payload()
        result = await storage_client.query_tbl_with_payload(
            'schedules', payload)
        sch_info = result['rows']
        sch_list = []
        if sch_info and sch_info[0]['enabled'] == 't':
            status, reason = await server.Server.scheduler.disable_schedule(
                uuid.UUID(sch_info[0]['id']))
            if status:
                _logger.warning(
                    "Schedule is disabled for {}, as {} service of type {} is being updated..."
                    .format(sch_info[0]['schedule_name'], name, _type))
                # TODO: SCHCH Audit log entry
                sch_list.append(sch_info[0]['id'])

        # service update is running as a background task
        loop = request.loop
        request._type = _type
        request._name = name
        request._sch_list = sch_list
        loop.call_later(1, do_update, request)
    except KeyError as ex:
        raise web.HTTPNotFound(reason=str(ex))
    except ValueError as ex:
        raise web.HTTPBadRequest(reason=str(ex))
    except Exception as ex:
        raise web.HTTPInternalServerError(reason=str(ex))

    return web.json_response({
        "message":
        "{} service update in process. Wait for few minutes to complete.".
        format(name)
    })
示例#3
0
async def update_plugin(request: web.Request) -> web.Response:
    """ update plugin

    :Example:
        curl -sX PUT http://localhost:8081/fledge/plugins/south/sinusoid/update
        curl -sX PUT http://localhost:8081/fledge/plugins/north/http_north/update
        curl -sX PUT http://localhost:8081/fledge/plugins/filter/metadata/update
        curl -sX PUT http://localhost:8081/fledge/plugins/notificationDelivery/asset/update
        curl -sX PUT http://localhost:8081/fledge/plugins/notificationRule/OutOfBound/update
    """
    _type = request.match_info.get('type', None)
    name = request.match_info.get('name', None)
    try:
        _type = _type.lower(
        ) if not str(_type).startswith('notification') else _type
        if _type not in [
                'north', 'south', 'filter', 'notificationDelivery',
                'notificationRule'
        ]:
            raise ValueError(
                "Invalid plugin type. Must be 'north', 'south', 'filter', 'notificationDelivery' "
                "or 'notificationRule'")

        # Check requested plugin name is installed or not
        installed_plugins = PluginDiscovery.get_plugins_installed(_type, False)
        installed_plugin_name = [
            p_name["name"] for p_name in installed_plugins
        ]
        if name not in installed_plugin_name:
            raise KeyError(
                "{} plugin is not yet installed. So update is not possible.".
                format(name))

        sch_list = []
        notification_list = []
        if _type in ['notificationDelivery', 'notificationRule']:
            # Check Notification service is enabled or not
            payload = PayloadBuilder().SELECT(
                "id", "enabled",
                "schedule_name").WHERE(['process_name', '=',
                                        'notification_c']).payload()
            storage_client = connect.get_storage_async()
            result = await storage_client.query_tbl_with_payload(
                'schedules', payload)
            sch_info = result['rows']
            if sch_info and sch_info[0]['enabled'] == 't':
                # Find notification instances which are used by requested plugin name
                # If its config item 'enable' is true then update to false
                config_mgr = ConfigurationManager(storage_client)
                all_notifications = await config_mgr._read_all_child_category_names(
                    "Notifications")
                for notification in all_notifications:
                    notification_config = await config_mgr._read_category_val(
                        notification['child'])
                    notification_name = notification_config['name']['value']
                    channel = notification_config['channel']['value']
                    rule = notification_config['rule']['value']
                    is_enabled = True if notification_config['enable'][
                        'value'] == 'true' else False
                    if (channel == name and is_enabled) or (rule == name
                                                            and is_enabled):
                        _logger.warning(
                            "Disabling {} notification instance, as {} {} plugin is updating..."
                            .format(notification_name, name, _type))
                        await config_mgr.set_category_item_value_entry(
                            notification_name, "enable", "false")
                        notification_list.append(notification_name)
            _type = "notify" if _type == 'notificationDelivery' else "rule"
        else:
            # Tracked plugins from asset tracker
            tracked_plugins = await _get_plugin_and_sch_name_from_asset_tracker(
                _type)
            filters_used_by = []
            if _type == 'filter':
                # In case of filter, for asset_tracker table we are inserting filter category_name in plugin column
                # instead of filter plugin name by Design
                # Hence below query is required to get actual plugin name from filters table
                storage_client = connect.get_storage_async()
                payload = PayloadBuilder().SELECT("name").WHERE(
                    ['plugin', '=', name]).payload()
                result = await storage_client.query_tbl_with_payload(
                    'filters', payload)
                filters_used_by = [r['name'] for r in result['rows']]
            for p in tracked_plugins:
                if (name == p['plugin'] and not _type == 'filter') or (
                        p['plugin'] in filters_used_by and _type == 'filter'):
                    sch_info = await _get_sch_id_and_enabled_by_name(
                        p['service'])
                    if sch_info[0]['enabled'] == 't':
                        status, reason = await server.Server.scheduler.disable_schedule(
                            uuid.UUID(sch_info[0]['id']))
                        if status:
                            _logger.warning(
                                "Disabling {} {} instance, as {} plugin is updating..."
                                .format(p['service'], _type, name))
                            sch_list.append(sch_info[0]['id'])

        # Plugin update is running as a background task
        loop = request.loop
        request._type = _type
        request._name = name
        request._sch_list = sch_list
        request._notification_list = notification_list
        loop.call_later(1, do_update, request)
    except KeyError as ex:
        raise web.HTTPNotFound(reason=str(ex))
    except ValueError as ex:
        raise web.HTTPBadRequest(reason=str(ex))
    except Exception as ex:
        raise web.HTTPInternalServerError(reason=str(ex))

    return web.json_response({
        "message":
        "{} plugin update in process. Wait for few minutes to complete.".
        format(name)
    })