Пример #1
0
def update_domain_name(machines, new_domain):
    """updates domain name of machines"""

    if not machines:
        exit_with_error('[ERROR] You did not specify any machines.')

    results = query_machines(machines)
    if not results:
        exit_with_error(f'[INFO] No matching machines found.')

    try:
        # create domain name if needed
        all_domains = session().Domains.read()
        names = [d['name'] for d in all_domains]

        if new_domain not in names:
            print(f'[INFO] Domain {new_domain} does not exist, creating...')
            session().Domains.create(name=new_domain, authoritative=True)

    except MaaSError as e:
        exit_with_error(f'[ERROR] MaaS: {e}')

    # update machines, one by one
    for r in results:
        try:
            session().Machine.update(system_id=r.system_id, domain=new_domain)
            print(f'[{r.system_id}] [{r.hostname}] [OK] Set to {new_domain}')

        except MaaSError as e:
            exit_with_error(
                f'[{r.system_id}] [{r.hostname}] [ERROR] MaaS: {e}')

    print('Done. Refresh machine list with "mjt_refresh".')
Пример #2
0
def add_tags(new_tag, machines):
    """adds tags to machines"""

    if not machines:
        exit_with_error('[ERROR] You did not specify any machines.')

    results = query_machines(machines)
    if not results:
        exit_with_error(f'[INFO] No matching machines found.')

    try:
        # create tag name if needed
        all_tags = session().Tags.read()
        names = [t['name'] for t in all_tags]

        if new_tag not in names:
            print(f'[INFO] Tag {new_tag} does not exist, creating...')
            session().Tags.create(name=new_tag,
                                  description='Helper tag for nagios checks')

    except MaaSError as e:
        exit_with_error(f'[ERROR] MaaS: {e}')

    # updates machines, one by one
    for r in results:
        try:
            session().Tag.update_nodes(name=new_tag, system_id=r.system_id)
            print(f'[{r.system_id}] [{r.hostname}] [OK] Added tag {new_tag}')

        except MaaSError as e:
            exit_with_error(
                f'[{r.system_id}] [{r.hostname}] [ERROR] MaaS: {e}')

    print('Done. Refresh machine list with "mjt_refresh".')
Пример #3
0
def update_hardware_info(machine, new_cpus, new_ram):
    """updates cpus and ram of machines"""

    results = query_machines(machine)
    if not results:
        exit_with_error(f'[INFO] No matching machines found.')

    # update machines, one by one
    for r in results:
        try:
            update = {}
            if new_cpus is not None:
                update['cpu_count'] = new_cpus

            if new_ram is not None:
                update['memory'] = new_ram * 1024

            session().Machine.update(system_id=r.system_id, **update)
            print(f'[{r.system_id}] [{r.hostname}]'
                  f' [OK] Updated hardware information: {update}')

        except MaaSError as e:
            exit_with_error(
                f'[{r.system_id}] [{r.hostname}] [ERROR] MaaS: {e}')

    print('Done. Refresh machine list with "jmt_refresh".')
Пример #4
0
def delete_result_id(system_id, script_id):
    """deletes results of @script_id for @system_id"""

    try:
        session().NodeScriptResult.delete(
            system_id=system_id, id=script_id
        )
        print(f'[{system_id}] Deleted script {script_id}')

    except MaaSError as e:
        print(
            f'[{system_id}] Failed to delete script {script_id}: '
            f'{e.__class__.__name__}: {e}'
        )
Пример #5
0
def set_suppressed_id(system_id, script_id, suppressed):
    """updates @script_id for @system_id and sets `suppressed`
    property to @suppressed. Prints a helpful error message
    if that failed."""

    try:
        session().NodeScriptResult.update(
            system_id=system_id, id=script_id, suppressed=suppressed
        )
        print(
            f'[{system_id}] Set suppressed={suppressed} for script {script_id}'
        )

    except MaaSError as e:
        print(
            f'[{system_id}] Failed to set suppressed={suppressed}'
            f'for script {script_id}: {e.__class__.__name__}: {e}'
        )
Пример #6
0
def update_host_name(machine, new_hostname):
    """updates host name of machine"""

    results = query_machines([machine])
    if not results:
        exit_with_error(f'[INFO] No matching machines found.')

    # update machines, one by one
    r = results[0]
    try:
        session().Machine.update(system_id=r.system_id, hostname=new_hostname)
        print(f'[{r.system_id}] [{r.hostname}] [OK]'
              f' Updated hostname to {new_hostname}')

    except MaaSError as e:
        exit_with_error(f'[{r.system_id}] [{r.hostname}] [ERROR] MaaS: {e}')

    print('Done. Refresh machine list with "mjt_refresh".')
Пример #7
0
def refresh_db():
    """gets data from server and update cache"""
    print('Getting information from MaaS.')

    # Retrieves list of machines
    try:
        s = session()
        machines = s.Machines.read()
        powers = s.Machines.power_parameters()

    except MaaSError as e:
        exit_with_error(f'Could not GET machines: {e}')

    # Updates database info
    new_data = []
    for m in machines:
        try:
            system_id = m.get('system_id', 'UNKNOWN')
            m_power = powers[system_id]

            if is_virtual_machine(m_power):
                print(f'[{system_id}] [{m.get("hostname")}]'
                      f' [INFO] skipping, virtual machine')
                continue

            new_data.append(
                dict(power_address=m_power.get('power_address', ''),
                     power_user=m_power.get('power_user', ''),
                     power_pass=m_power.get('power_pass', ''),
                     fqdn=m['fqdn'],
                     domain=m['domain']['name'],
                     hostname=m['hostname'],
                     system_id=system_id,
                     ip_addresses=', '.join(m['ip_addresses']),
                     cpus=m['cpu_count'],
                     ram=m['memory'] // 1024,
                     tags=','.join(m['tag_names'])))

        except KeyError as e:
            print(f'[{system_id}] [ERROR] Missing information: {e}')

    # Adds new data to the database
    print(f'Updating the database: "{Config.sqlite_db}"')
    MaaSCache.insert(new_data).on_conflict_replace().execute()
    db.commit()

    print('Done.')
Пример #8
0
def get_machine(system_id):
    """asks MaaS for information and print it out"""

    try:
        m = session().Machine.read(system_id=system_id)
    except MaaSError as e:
        exit_with_error(f'[{system_id}] [ERROR] {e}')

    print(json.dumps({
        'system_id': system_id,
        'ip_addresses': ','.join(m['ip_addresses']),
        'tags': ','.join(m['tag_names']),
        'hostname': m['hostname'],
        'domain': m['domain']['name'],
        'fqdn': m['fqdn'],
        'status': m['status_name']
    }, indent=2))
Пример #9
0
def get_script_results(machine, skip):
    """returns all script group results, along with result status"""

    if isinstance(machine, str):
        query = [machine]
    else:
        query = machine

    machines = query_machines(query)
    if not machines:
        exit_with_error(f'UNKNOWN: No matching machine: {machine}', code=3)

    api = session()

    results = {}
    for m in machines:
        scripts = api.NodeScriptResults.read(system_id=m.system_id)
        for s in scripts:
            if s['type_name'] in skip or s['status_name'] in skip:
                continue

            if m.system_id not in results:
                results[m.system_id] = {}

            suppressed = [r for r in s['results'] if r['suppressed']]
            ids = ','.join([str(r['id']) for r in s['results']])
            results[m.system_id].update({
                s['id']: {
                    'type': s['type_name'],
                    'status': s['status_name'],
                    'total': len(s['results']),
                    'suppressed': len(suppressed),
                    'individual_ids': ids
                }
            })

    return results