github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/acceptancetests/repository/charms/network-health/actions/ping.py (about)

     1  #!/usr/bin/python3
     2  import subprocess
     3  import os
     4  import sys
     5  import json
     6  from ast import literal_eval
     7  
     8  sys.path.insert(0, os.path.join(os.environ['CHARM_DIR'], 'lib'))
     9  
    10  from charmhelpers.core import (
    11      hookenv,
    12      host,
    13  )
    14  
    15  from charmhelpers.core.hookenv import (
    16      action_get,
    17      action_set,
    18  )
    19  
    20  
    21  def main():
    22      targets = hookenv.action_get('targets')
    23      hookenv.log("Got: {}".format(targets))
    24      # Undo the formatting passed into the action so juju didn't puke
    25      targets = targets.replace('=', ':')
    26      targets = targets.replace('(', '{')
    27      targets = targets.replace(')', '}')
    28      hookenv.log('Parsed to: {}'.format(targets))
    29      targets = json.loads(targets)
    30      results = {}
    31      # Get unit names from targets dict and ping their public address
    32      for target, ip in targets.items():
    33          results[target] = ping_check(ip)
    34      action_set({'results': results})
    35  
    36  
    37  def ping_check(target):
    38      # If ping returns anything but success, return False
    39      try:
    40          subprocess.check_output("ping -c 1 " + target, shell=True)
    41      except subprocess.CalledProcessError as e:
    42          hookenv.log('Ping to target {} failed for exception {}'.format(target,
    43                                                                         e))
    44          return False
    45  
    46      return True
    47  
    48  
    49  if __name__ == "__main__":
    50      main()