# Copyright 2020 Dell Inc. or its subsidiaries. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
---

# This file used to generate a report of reachable and unreachable host of hpc cluster
# This file can be executed only if provisioned_hosts.yml is created inside the path omnia/control_plane/roles/collect_node_info/files/provisioned_hosts.yml

# Command to execute: ansible-playbook provision_report.yml -i ../roles/collect_node_info/files/provisioned_hosts.yml

- name: Fetch provision_password
  hosts: localhost
  connection: local
  gather_facts: no
  roles:
    - fetch_password

- name: Find reachable hosts using ping
  hosts: all
  gather_facts: false
  ignore_unreachable: true
  ignore_errors: true
  tasks:
    - name: Check for reachable nodes
      command: ping -c1 {{ inventory_hostname }}
      delegate_to: localhost
      register: ping_result
      ignore_errors: yes
      changed_when: false

    - name: Refresh ssh keys
      command: ssh-keygen -R {{ inventory_hostname }}
      delegate_to: localhost
      changed_when: false

    - name: Group reachable hosts
      group_by:
        key: "reachable"
      when: "'100% packet loss' not in ping_result.stdout"

- name: Find reachable hosts using ssh
  hosts: reachable
  gather_facts: False
  ignore_unreachable: true
  remote_user: "root"
  vars:
    ansible_password: "{{ hostvars['127.0.0.1']['cobbler_password'] }}"
    ansible_become_pass: "{{ hostvars['127.0.0.1']['cobbler_password'] }}"
    ansible_ssh_common_args: '-o StrictHostKeyChecking=no'
  tasks:
    - name: Check ssh status
      command: hostname
      register: ssh_status
      ignore_errors: yes

    - name: Group unreachable ssh hosts
      group_by:
        key: "unreachable_ssh"
      when: ssh_status.unreachable is defined and ssh_status.unreachable == true

    - name: Group reachable ssh hosts
      group_by:
        key: "reachable_ssh"
      when: (ssh_status.unreachable is defined and ssh_status.unreachable == false) or (ssh_status.rc is defined and ssh_status.rc == 0)

- name: Display hosts list
  hosts: localhost
  connection: local
  gather_facts: false
  roles:
    - hpc_cluster_report