예제 #1
0
파일: api.py 프로젝트: dimuha-rs/adcm
def add_host(proto, provider, fqdn, desc='', lock=False):
    check_proto_type(proto, 'host')
    check_license(proto.bundle)
    if proto.bundle != provider.prototype.bundle:
        msg = 'Host prototype bundle #{} does not match with host provider bundle #{}'
        err('FOREIGN_HOST',
            msg.format(proto.bundle.id, provider.prototype.bundle.id))
    spec, _, conf, attr = get_prototype_config(proto)
    event = Event()
    with transaction.atomic():
        obj_conf = init_object_config(spec, conf, attr)
        host = Host(prototype=proto,
                    provider=provider,
                    fqdn=fqdn,
                    config=obj_conf,
                    description=desc)
        host.save()
        if lock:
            host.stack = ['created']
            set_object_state(host, config.Job.LOCKED, event)
        process_file_type(host, spec, conf)
        cm.issue.save_issue(host)
    event.send_state()
    cm.status_api.post_event('create', 'host', host.id, 'provider',
                             str(provider.id))
    cm.status_api.load_service_map()
    return host
예제 #2
0
def start_task(action_id, selector, conf, attr, hc, hosts, verbose):   # pylint: disable=too-many-locals
    try:
        action = Action.objects.get(id=action_id)
    except Action.DoesNotExist:
        err('ACTION_NOT_FOUND')

    obj, cluster, provider = check_task(action, selector, conf)
    act_conf, spec = check_action_config(action, obj, conf, attr)
    host_map, delta = check_hostcomponentmap(cluster, action, hc)
    check_action_hosts(action, cluster, provider, hosts)
    old_hc = api.get_hc(cluster)

    if action.type not in ['task', 'job']:
        msg = f'unknown type "{action.type}" for action: {action}, {action.context}: {obj.name}'
        err('WRONG_ACTION_TYPE', msg)

    event = Event()
    task = prepare_task(
        action, obj, selector, act_conf, attr, spec, old_hc, delta, host_map, cluster, hosts,
        event, verbose
    )
    event.send_state()
    run_task(task, event)
    event.send_state()
    log_rotation()

    return task
예제 #3
0
 def _do_provider(self, task_vars, context):
     event = Event()
     res = self._wrap_call(
         set_provider_state,
         context['provider_id'],
         self._task.args["state"],
         event
     )
     event.send_state()
     res['state'] = self._task.args["state"]
     return res
예제 #4
0
def restart_task(task):
    event = Event()
    if task.status in (config.Job.CREATED, config.Job.RUNNING):
        err('TASK_ERROR', f'task #{task.id} is running')
    elif task.status == config.Job.SUCCESS:
        run_task(task, event)
        event.send_state()
    elif task.status in (config.Job.FAILED, config.Job.ABORTED):
        run_task(task, event, 'restart')
        event.send_state()
    else:
        err('TASK_ERROR', f'task #{task.id} has unexpected status: {task.status}')
예제 #5
0
def finish_task(task, job, status):
    action = Action.objects.get(id=task.action_id)
    obj = get_task_obj(action.prototype.type, task.object_id)
    state = get_state(action, job, status)
    event = Event()
    with transaction.atomic():
        DummyData.objects.filter(id=1).update(date=timezone.now())
        if state is not None:
            set_action_state(action, task, obj, state)
        unlock_objects(obj, event, job)
        restore_hc(task, action, status)
        set_task_status(task, status, event)
    event.send_state()
예제 #6
0
def run_ansible(job_id):
    log.debug("job_runner.py called as: %s", sys.argv)
    conf = read_config(job_id)
    playbook = conf['job']['playbook']
    out_file = open_file(config.RUN_DIR, 'ansible-stdout', job_id)
    err_file = open_file(config.RUN_DIR, 'ansible-stderr', job_id)
    post_log(job_id, 'stdout', 'ansible')
    post_log(job_id, 'stderr', 'ansible')
    event = Event()

    os.chdir(conf['env']['stack_dir'])
    cmd = [
        '/adcm/python/job_venv_wrapper.sh',
        get_venv(int(job_id)),
        'ansible-playbook',
        '--vault-password-file',
        f'{config.CODE_DIR}/ansible_secret.py',
        '-e',
        f'@{config.RUN_DIR}/{job_id}/config.json',
        '-i',
        f'{config.RUN_DIR}/{job_id}/inventory.json',
        playbook,
    ]
    if 'params' in conf['job']:
        if 'ansible_tags' in conf['job']['params']:
            cmd.append('--tags=' + conf['job']['params']['ansible_tags'])
    if 'verbose' in conf['job'] and conf['job']['verbose']:
        cmd.append('-vvvv')

    log.info("job run cmd: %s", ' '.join(cmd))
    proc = subprocess.Popen(cmd,
                            env=env_configuration(conf),
                            stdout=out_file,
                            stderr=err_file)
    cm.job.set_job_status(job_id, config.Job.RUNNING, event, proc.pid)
    event.send_state()
    log.info("run ansible job #%s, pid %s, playbook %s", job_id, proc.pid,
             playbook)
    ret = proc.wait()
    finish_check(job_id)
    ret = set_job_status(job_id, ret, proc.pid, event)
    event.send_state()

    out_file.close()
    err_file.close()

    log.info("finish ansible job #%s, pid %s, ret %s", job_id, proc.pid, ret)
    sys.exit(ret)
예제 #7
0
def init():
    log.info("Start initializing ADCM DB...")
    if not User.objects.filter(username='******').exists():
        User.objects.create_superuser('admin',
                                      '*****@*****.**',
                                      'admin',
                                      built_in=True)
    create_status_user()
    event = Event()
    abort_all(event)
    clear_temp_tables()
    event.send_state()
    load_adcm()
    create_dummy_data()
    drop_locks()
    recheck_issues()
    log.info("ADCM DB is initialized")
예제 #8
0
def init():
    log.info("Start initializing ADCM DB...")
    try:
        User.objects.get(username='******')
    except User.DoesNotExist:
        User.objects.create_superuser('admin', '*****@*****.**', 'admin')
    try:
        UserProfile.objects.get(login='******')
    except UserProfile.DoesNotExist:
        UserProfile.objects.create(login='******')
    create_status_user()
    event = Event()
    unlock_all(event)
    clear_temp_tables()
    event.send_state()
    load_adcm()
    create_dummy_data()
    log.info("ADCM DB is initialized")
예제 #9
0
    def run(self, terms, variables=None, **kwargs):  # pylint: disable=too-many-branches
        log.debug('run %s %s', terms, kwargs)
        ret = []
        event = Event()
        if len(terms) < 2:
            msg = 'not enough arguments to set state ({} of 2)'
            raise AnsibleError(msg.format(len(terms)))

        if terms[0] == 'service':
            if 'cluster' not in variables:
                raise AnsibleError('there is no cluster in hostvars')
            cluster = variables['cluster']
            if 'service_name' in kwargs:
                res = cm.api.set_service_state(cluster['id'],
                                               kwargs['service_name'],
                                               terms[1])
            elif 'job' in variables and 'service_id' in variables['job']:
                res = cm.api.set_service_state_by_id(
                    cluster['id'], variables['job']['service_id'], terms[1])
            else:
                msg = 'no service_id in job or service_name in params'
                raise AnsibleError(msg)
        elif terms[0] == 'cluster':
            if 'cluster' not in variables:
                raise AnsibleError('there is no cluster in hostvars')
            cluster = variables['cluster']
            res = cm.api.set_cluster_state(cluster['id'], terms[1])
        elif terms[0] == 'provider':
            if 'provider' not in variables:
                raise AnsibleError('there is no provider in hostvars')
            provider = variables['provider']
            res = cm.api.set_provider_state(provider['id'], terms[1], event)
        elif terms[0] == 'host':
            if 'adcm_hostid' not in variables:
                raise AnsibleError('there is no adcm_hostid in hostvars')
            res = cm.api.set_host_state(variables['adcm_hostid'], terms[1])
        else:
            raise AnsibleError('unknown object type: %s' % terms[0])
        event.send_state()
        ret.append(res)
        return ret