From f0da81b17593f5b321996b71f177b5618e1b3c09 Mon Sep 17 00:00:00 2001
From: Alain Takoudjou <alain.takoudjou@nexedi.com>
Date: Fri, 31 Jul 2015 18:07:56 +0200
Subject: [PATCH] Add task to ping one or multiple hosts

---
 playbook/roles/vm-bootstrap/files/ping        | 35 +++++++++++++++++++
 .../roles/vm-bootstrap/tasks/hostname.yml     | 11 +++++-
 2 files changed, 45 insertions(+), 1 deletion(-)
 create mode 100644 playbook/roles/vm-bootstrap/files/ping

diff --git a/playbook/roles/vm-bootstrap/files/ping b/playbook/roles/vm-bootstrap/files/ping
new file mode 100644
index 0000000..f3a59e4
--- /dev/null
+++ b/playbook/roles/vm-bootstrap/files/ping
@@ -0,0 +1,35 @@
+#!/usr/bin/python
+
+import os
+import sys
+from subprocess import Popen, PIPE
+
+def check_ping(host_list):
+  for host in host_list:
+    process = Popen("ping -c 1 %s" % host, shell=True, stdout=PIPE)
+    result = process.communicate()[0]
+  
+    if process.returncode == 0:
+      continue
+    raise Exception('PING fail: host at %s didn\'t send response.\n%s' % (
+                      host, result))
+
+def ping_cluster(hpath):
+  if os.path.exists(hpath):
+    for content in open(hpath, 'r').readlines():
+      if content:
+        items = content.strip().split(' ')
+        check_ping(items)
+      
+if __name__ == "__main__":
+
+  if len(sys.argv) < 3:
+    print "Use: %s TYPE [HOST LIST] OR [HOST-FILE]" % sys.argv[0]
+    print "ex: %s host google.com slapos.org; %s cluster /tmp/hosts" % (
+                                        sys.argv[0], sys.argv[0])
+    exit(1)
+  if sys.argv[1] == 'host':
+    check_ping(sys.argv[2:])
+  elif sys.argv[1] == 'cluster':
+    ping_cluster(sys.argv[2])
+
diff --git a/playbook/roles/vm-bootstrap/tasks/hostname.yml b/playbook/roles/vm-bootstrap/tasks/hostname.yml
index fec0312..3d79438 100644
--- a/playbook/roles/vm-bootstrap/tasks/hostname.yml
+++ b/playbook/roles/vm-bootstrap/tasks/hostname.yml
@@ -46,7 +46,7 @@
 
   - name: stat /tmp/hosts
     stat: path=/tmp/hosts
-    register: hostname_file
+    register: hosts_file
 
   - name: Format hosts
     script: format_hosts /tmp/hosts tl.teralab-datascience.fr 
@@ -57,3 +57,12 @@
 
   - name: adding entry from workspace
     lineinfile: dest=/etc/resolv.conf line="nameserver 10.200.218.1"
+
+  - name: ping current host
+    script: ping host {{ lookup('file', '/etc/opt/ipv4') }} {{ lookup('file', '/etc/opt/hostname') }}
+    when: hostname_file.stat.exists == True
+
+  - name: ping cluster hosts
+    script: ping cluster /tmp/hosts
+    when: hosts_file.stat.exists == True
+    ignore_errors: True
-- 
2.30.9