Beispiel #1
0
 def start_vm(self):
     try:
         self.node.api_request('system.vm.vm.start_vm', config=self.id)
     except Exception as e:
         raise VultureSystemConfigError(
             "on node '{}'.\nRequest failure.".format(self.node.name))
Beispiel #2
0
def config_edit(request, api=False, update=False):
    config_model = Cluster.get_global_config()

    if hasattr(request, "JSON") and api:
        if update:
            request.JSON = {**config_model.to_dict(), **request.JSON}
        request_data = request.JSON
    else:
        request_data = request.POST

    # Verify if attribute has changed HERE, config_model will be modified after (at form.is_valid())
    has_customer_changed = request_data.get(
        'customer_name') != config_model.customer_name
    has_portal_cookie_name_changed = request_data.get(
        'portal_cookie_name') != config_model.portal_cookie_name
    ssh_authorized_key_changed = request_data.get(
        'ssh_authorized_key') != config_model.ssh_authorized_key
    logs_ttl_changed = request_data.get('logs_ttl') != config_model.logs_ttl

    form = ConfigForm(request_data or None,
                      instance=config_model,
                      error_class=DivErrorList)

    def render_form(**kwargs):
        save_error = kwargs.get('save_error')
        if api:
            if form.errors:
                return JsonResponse(form.errors.get_json_data(), status=400)
            if save_error:
                return JsonResponse({'error': save_error[0]}, status=500)
        return render(request, 'config/config.html', {'form': form, **kwargs})

    if request.method in ("POST", "PUT", "PATCH") and form.is_valid():
        config = form.save(commit=False)
        config.save()
        """ Write .ssh/authorized_keys if any change detected """
        if ssh_authorized_key_changed:
            params = [
                "/usr/home/vlt-adm/.ssh/authorized_keys",
                request_data.get('ssh_authorized_key'), 'vlt-adm:wheel', '600'
            ]
            for node in Node.objects.all():
                try:
                    node.api_request('system.config.models.write_conf',
                                     config=params)
                except Exception as e:
                    raise VultureSystemConfigError(
                        "on node '{}'.\nRequest failure.".format(node.name))
        """ If customer name has changed, rewrite rsyslog templates """
        error = ""
        if has_customer_changed:
            api_res = Cluster.api_request(
                "services.rsyslogd.rsyslog.configure_node")
            if not api_res.get('status'):
                error = api_res.get('message')
        if has_portal_cookie_name_changed:
            api_res = Cluster.api_request(
                "services.haproxy.haproxy.configure_node")
            if not api_res.get('status'):
                error = api_res.get('message')
        if logs_ttl_changed:
            res, mess = config_model.set_logs_ttl()
            if not res:
                return render_form(save_error=mess)
        if error:
            return render_form(save_error=error)
        if api:
            return build_response_config("system.config.api", [])

        return HttpResponseRedirect('/system/config/')

    # If request PATCH or PUT & form not valid - return error
    if api:
        logger.error("Config api form error : {}".format(
            form.errors.get_json_data()))
        return JsonResponse(form.errors.get_json_data(), status=400)

    return render_form()
Beispiel #3
0
def write_conf(logger, args):
    """ Dedicated method used to write a file on disk """
    # parse arguments because we can be called by asynchronous api
    if isinstance(args, str):
        file_path, file_content, owner, perm = literal_eval(args)
    else:
        file_path, file_content, owner, perm = args

    # Write temporary file info /tmp dir,
    #  because everybody can write onto
    temp_dir = "/var/tmp/"
    """ Create a temporary named file in {prefix} path """
    tmpfile = mktemp(prefix=temp_dir)
    logger.debug("Config::write_conf: Writing into {}".format(tmpfile))

    command = ""
    try:
        """ Try to open the tmp file - it might not raise.... """
        with open(tmpfile, "w", encoding="utf8") as f:
            f.write(str(file_content))
        """ Sudo move the file from tmp to file_path """
        logger.debug("Moving file from '{}' to '{}'".format(
            tmpfile, file_path))
        command = ['/usr/local/bin/sudo', '/bin/mv', tmpfile, file_path]
        check_output(command, stderr=PIPE)
        """ Sudo apply owner on file_path """
        logger.debug("Applying owner '{}' on file '{}'".format(
            owner, file_path))
        command = ['/usr/local/bin/sudo', '/usr/sbin/chown', owner, file_path]
        check_output(command, stderr=PIPE)
        """ Sudo apply permissions on file_path """
        logger.debug("Applying permissions '{}' on file '{}'".format(
            perm, file_path))
        command = ['/usr/local/bin/sudo', '/bin/chmod', perm, file_path]
        check_output(command, stderr=PIPE)

        logger.info("File '{}' successfully written.".format(file_path))

    except FileNotFoundError as e:
        logger.error("Failed to open file {}: {}".format(file_path, str(e)))
        raise VultureSystemConfigError(
            "The path '{}' or '{}' does not seem to exist.".format(
                temp_dir, "/".join(file_path.split('/')[:-1])))

    except PermissionError as e:
        logger.error("Failed to create/write file {}:".format(file_path))
        logger.exception(e)
        raise VultureSystemConfigError(
            "The path '{}' does not have correct permissions. \n "
            "Cannot create/write the file '{}'.".format(temp_dir, tmpfile))
    except CalledProcessError as e:
        logger.error("Failed to execute command {}: {}".format(
            command, e.stderr))
        logger.exception(e)

        # Catch sudoers failure
        if "sudo: no tty present and no askpass program specified" in e.stderr.decode(
                'utf8'):
            raise VultureSystemConfigError(
                "The file '/usr/local/etc/sudoers.d/vulture_sudoers' is not correct, "
                "cannot execute command",
                traceback=e.stderr.decode('utf8'))
        if "No such file or directory" in e.stderr.decode('utf8'):
            raise VultureSystemConfigError(
                "Directory '{}' does not seems to exists.".format('/'.join(
                    file_path.split('/')[:-1])),
                traceback=e.stderr.decode('utf8'))

        raise VultureSystemConfigError(
            "Bad permissions on directory '{}'.".format(temp_dir),
            traceback=(e.stdout or e.stderr).decode('utf8'))
    # Do NOT remove THIS ! Used to handle "service vultured stop"
    except ServiceExit:
        raise

    except Exception as e:
        logger.error("No referenced error in write_conf method : ")
        logger.exception(e)
        raise VultureSystemConfigError(
            "Unknown error occurred. \n"
            "Please see traceback for more informations.")
Beispiel #4
0
 def delete_snapshot(self):
     try:
         self.node.api_request('system.zfs.zfs.delete_snapshot', config=self.id)
     except Exception as e:
         raise VultureSystemConfigError("on node '{}'.\nRequest failure.".format(self.node.name))