|
| 1 | +#!/usr/bin/python |
| 2 | + |
| 3 | +# Copyright: (c) 2025, StackHPC |
| 4 | +# Apache 2 License |
| 5 | + |
| 6 | +from ansible.module_utils.basic import AnsibleModule |
| 7 | + |
| 8 | +ANSIBLE_METADATA = { |
| 9 | + "metadata_version": "0.1", |
| 10 | + "status": ["preview"], |
| 11 | + "supported_by": "community", |
| 12 | +} |
| 13 | + |
| 14 | +DOCUMENTATION = """ |
| 15 | +--- |
| 16 | +module: sacct_cluster |
| 17 | +short_description: Manages clusters in the accounting database |
| 18 | +version_added: "2.9" |
| 19 | +description: |
| 20 | + - "Adds/removes a cluster from the accounting database" |
| 21 | +options: |
| 22 | + name: |
| 23 | + description: |
| 24 | + - Name of the cluster |
| 25 | + required: true |
| 26 | + type: str |
| 27 | + state: |
| 28 | + description: |
| 29 | + - If C(present), cluster will be added if it does't already exist |
| 30 | + - If C(absent), cluster will be removed if it exists |
| 31 | + type: str |
| 32 | + required: true |
| 33 | + choices: [ absent, present] |
| 34 | +
|
| 35 | +requirements: |
| 36 | + - "python >= 3.6" |
| 37 | +author: |
| 38 | + - Will Szumski, StackHPC |
| 39 | +""" |
| 40 | + |
| 41 | +EXAMPLES = """ |
| 42 | +""" |
| 43 | + |
| 44 | +import collections |
| 45 | + |
| 46 | +def run_module(): |
| 47 | + module_args = dict({}) |
| 48 | + |
| 49 | + module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) |
| 50 | + |
| 51 | + try: |
| 52 | + rc ,stdout, stderr = module.run_command("nvidia-smi --query-gpu=name --format=noheader", check_rc=False, handle_exceptions=False) |
| 53 | + except FileNotFoundError: # nvidia-smi not installed |
| 54 | + rc = None |
| 55 | + |
| 56 | + # nvidia-smi return codes: https://docs.nvidia.com/deploy/nvidia-smi/index.html |
| 57 | + gpus = {} |
| 58 | + result = {'changed': False, 'gpus': gpus, 'gres':''} |
| 59 | + if rc == 0: |
| 60 | + # stdout line e.g. 'NVIDIA H200' for each GPU |
| 61 | + lines = [line for line in stdout.splitlines() if line != ''] # defensive: currently no blank lines |
| 62 | + models = [line.split()[1] for line in lines] |
| 63 | + gpus.update(collections.Counter(models)) |
| 64 | + elif rc == 9: |
| 65 | + # nvidia-smi installed but driver not running |
| 66 | + pass |
| 67 | + elif rc == None: |
| 68 | + # nvidia-smi not installed |
| 69 | + pass |
| 70 | + else: |
| 71 | + result.update({'stdout': stdout, 'rc': rc, 'stderr':stderr}) |
| 72 | + module.fail_json(**result) |
| 73 | + |
| 74 | + if len(gpus) > 0: |
| 75 | + gres_parts = [] |
| 76 | + for model, count in gpus.items(): |
| 77 | + gres_parts.append(f"gpu:{model}:{count}") |
| 78 | + result.update({'gres': ','.join(gres_parts)}) |
| 79 | + |
| 80 | + module.exit_json(**result) |
| 81 | + |
| 82 | + |
| 83 | +def main(): |
| 84 | + run_module() |
| 85 | + |
| 86 | + |
| 87 | +if __name__ == "__main__": |
| 88 | + main() |
0 commit comments