Ejemplo n.º 1
0
def update_repo_sources_and_plugin(_type: str, name: str) -> tuple:
    # Below check is needed for python plugins
    # For Example: installed_plugin_dir=wind_turbine; package_name=wind-turbine
    name = name.replace("_", "-")

    # For endpoint curl -X GET http://localhost:8081/fledge/plugins/available we used
    # sudo apt list command internal so package name always returns in lowercase,
    # irrespective of package name defined in the configured repo.
    name = "fledge-{}-{}".format(_type, name.lower())
    _platform = platform.platform()
    stdout_file_path = common.create_log_file(action="update",
                                              plugin_name=name)
    pkg_mgt = 'apt'
    cmd = "sudo {} -y update > {} 2>&1".format(pkg_mgt, stdout_file_path)
    if 'centos' in _platform or 'redhat' in _platform:
        pkg_mgt = 'yum'
        cmd = "sudo {} check-update > {} 2>&1".format(pkg_mgt,
                                                      stdout_file_path)
    ret_code = os.system(cmd)
    # sudo apt/yum -y install only happens when update is without any error
    if ret_code == 0:
        cmd = "sudo {} -y install {} >> {} 2>&1".format(
            pkg_mgt, name, stdout_file_path)
        ret_code = os.system(cmd)

    # relative log file link
    link = "log/" + stdout_file_path.split("/")[-1]
    return ret_code, link
Ejemplo n.º 2
0
async def install_package_from_repo(name: str, pkg_mgt: str, version: str) -> tuple:
    stdout_file_path = common.create_log_file(action="install", plugin_name=name)
    link = "log/" + stdout_file_path.split("/")[-1]
    msg = "installed"
    cat = await check_upgrade_on_install()
    upgrade_install_cat_item = cat["upgradeOnInstall"]
    max_upgrade_cat_item = cat['maxUpdate']
    if 'value' in upgrade_install_cat_item:
        if upgrade_install_cat_item['value'] == "true":
            pkg_cache_mgr = server.Server._package_cache_manager
            last_accessed_time = pkg_cache_mgr['upgrade']['last_accessed_time']
            now = datetime.now()
            then = last_accessed_time if last_accessed_time else now
            duration_in_sec = (now - then).total_seconds()
            # If max upgrade per day is set to 1, then an upgrade can not occurs until 24 hours after the last accessed upgrade.
            # If set to 2 then this drops to 12 hours between upgrades, 3 would result in 8 hours between calls and so on.
            if duration_in_sec > (24 / int(max_upgrade_cat_item['value'])) * 60 * 60 or not last_accessed_time:
                _LOGGER.info("Attempting upgrade on {}".format(now))
                cmd = "sudo {} -y upgrade".format(pkg_mgt) if pkg_mgt == 'apt' else "sudo {} -y update".format(pkg_mgt)
                ret_code = os.system(cmd + " > {} 2>&1".format(stdout_file_path))
                if ret_code != 0:
                    raise PackageError(link)
                pkg_cache_mgr['upgrade']['last_accessed_time'] = now
            else:
                _LOGGER.warning("Maximum upgrade exceeds the limit for the day")
            msg = "updated"
    cmd = "sudo {} -y install {}".format(pkg_mgt, name)
    if version:
        cmd = "sudo {} -y install {}={}".format(pkg_mgt, name, version)

    ret_code = os.system(cmd + " >> {} 2>&1".format(stdout_file_path))
    return ret_code, link, msg
Ejemplo n.º 3
0
def do_update(request):
    _logger.info("{} service update started...".format(request._name))
    name = "fledge-service-{}".format(request._name.lower())
    _platform = platform.platform()
    stdout_file_path = common.create_log_file("update", name)
    pkg_mgt = 'apt'
    cmd = "sudo {} -y update > {} 2>&1".format(pkg_mgt, stdout_file_path)
    if 'centos' in _platform or 'redhat' in _platform:
        pkg_mgt = 'yum'
        cmd = "sudo {} check-update > {} 2>&1".format(pkg_mgt,
                                                      stdout_file_path)
    ret_code = os.system(cmd)
    # sudo apt/yum -y install only happens when update is without any error
    if ret_code == 0:
        cmd = "sudo {} -y install {} >> {} 2>&1".format(
            pkg_mgt, name, stdout_file_path)
        ret_code = os.system(cmd)

    # relative log file link
    link = "log/" + stdout_file_path.split("/")[-1]
    if ret_code != 0:
        _logger.error("{} service update failed. Logs available at {}".format(
            request._name, link))
    else:
        _logger.info(
            "{} service update completed. Logs available at {}".format(
                request._name, link))
        # PKGUP audit log entry
        storage_client = connect.get_storage_async()
        audit = AuditLogger(storage_client)
        audit_detail = {'packageName': name}
        asyncio.ensure_future(audit.information('PKGUP', audit_detail))

    # Restart the service which was disabled before update
    for s in request._sch_list:
        asyncio.ensure_future(
            server.Server.scheduler.enable_schedule(uuid.UUID(s)))
Ejemplo n.º 4
0
def purge_plugin(plugin_type: str, name: str) -> tuple:

    from fledge.services.core.server import Server

    _logger.info("{} plugin removal started...".format(name))
    is_package = True
    stdout_file_path = ''
    original_name = name
    # Special case handling - installed directory name Vs package name
    # For example: Plugins like http_south Vs http-south
    name = name.replace('_', '-').lower()
    plugin_name = 'fledge-{}-{}'.format(plugin_type, name)

    get_platform = platform.platform()
    pkg_cache_mgr = Server._package_cache_manager
    try:
        if 'centos' in get_platform or 'redhat' in get_platform:
            rpm_list = os.popen('rpm -qa | grep fledge*').read()
            _logger.debug("rpm list : {}".format(rpm_list))
            if len(rpm_list):
                f = rpm_list.find(plugin_name)
                if f == -1:
                    raise KeyError
            else:
                raise KeyError
            stdout_file_path = common.create_log_file(action='remove', plugin_name=plugin_name)
            link = "log/" + stdout_file_path.split("/")[-1]
            cmd = "sudo yum -y remove {} > {} 2>&1".format(plugin_name, stdout_file_path)
        else:
            dpkg_list = os.popen('dpkg --list fledge* 2>/dev/null')
            ls_output = dpkg_list.read()
            _logger.debug("dpkg list output: {}".format(ls_output))
            if len(ls_output):
                f = ls_output.find(plugin_name)
                if f == -1:
                    raise KeyError
            else:
                raise KeyError
            stdout_file_path = common.create_log_file(action='remove', plugin_name=plugin_name)
            link = "log/" + stdout_file_path.split("/")[-1]
            cmd = "sudo apt -y purge {} > {} 2>&1".format(plugin_name, stdout_file_path)

        code = os.system(cmd)
        if code:
            raise PackageError(link)
        else:
            common._get_available_packages.cache_clear()
            pkg_cache_mgr['list']['last_accessed_time'] = ""
    except KeyError:
        # This case is for non-package installation - python plugin path will be tried first and then C
        _logger.info("Trying removal of manually installed plugin...")
        is_package = False
        if plugin_type in ['notify', 'rule']:
            plugin_type = 'notificationDelivery' if plugin_type == 'notify' else 'notificationRule'
        try:
            path = PYTHON_PLUGIN_PATH+'{}/{}'.format(plugin_type, original_name)
            if not os.path.isdir(path):
                path = C_PLUGINS_PATH + '{}/{}'.format(plugin_type, original_name)
            rm_cmd = 'rm -rv {}'.format(path)
            if os.path.exists("{}/bin".format(_FLEDGE_ROOT)) and os.path.exists("{}/bin/fledge".format(_FLEDGE_ROOT)):
                rm_cmd = 'sudo rm -rv {}'.format(path)
            code = os.system(rm_cmd)
            if code != 0:
                raise OSError("While deleting, invalid plugin path found for {}".format(original_name))
        except Exception as ex:
            code = 1
            _logger.error("Error in removing plugin: {}".format(str(ex)))
    return code, stdout_file_path, is_package