Upvote Or Duan answer as mine is based on his answer:
Resource
class Ping(Resource):
def get(self, site_id):
site_hostname = mast_utils.list_sites(site_id)['results'][0]['hostname']
printers = mast_utils.list_printers(site_id)['results']['channels']
response = network_utils.parellelize(network_utils.ping, site_hostname, printers)
return response
api.add_resource(Ping, '/ping/<string:site_id>/')
network_utils.py
def ping(hostname):
command = ['ping', '-q', hostname,
'-w', '1',
'-W', '1',
'-i', '0.2'
]
response = shell.execute(command)
return output_parser.ping(response['results'])
def collect(task, response, **kwargs):
hostname = kwargs['hostname']
response[hostname] = task(**kwargs)
def parellelize(task, site_id, printers, **kwargs):
response = {}
kw = kwargs.copy()
kw.update({'hostname': site_id})
collect(task, response, **kw)
printers_response = {}
threads = []
for printer in printers:
hostname = printer['hostname']
kw = kwargs.copy()
kw.update({'hostname': hostname})
threads.append(
threading.Thread(
target=collect,
args=(task, printers_response),
kwargs=kw
)
)
for thread in threads:
thread.start()
thread.join()
response[site_id].update(printers_response)
return response
test_network_utils.py
class NetwrokUtilsTestCase(unittest.TestCase):
def test_ping_is_null_when_host_unreachable(self):
hostname = 'unreachable'
response = network_utils.ping(hostname)
self.assertDictEqual(response, {
'avg': None,
'max': None,
'mdev': None,
'min': None
})
def test_ping_reply_time_when_reachable(self):
hostname = '127.0.0.1'
response = network_utils.ping(hostname)
self.assertGreater(response['avg'], 0)
def test_ping_with_only_a_site(self):
site_hostname = 'localhost'
printers = []
response = {}
response = network_utils.parellelize(network_utils.ping, site_hostname, printers)
self.assertGreater(response[site_hostname]['avg'], 0)
def test_ping_with_printers(self):
site_hostname = 'localhost'
printers = [
{'hostname': '127.0.0.1', 'port': 22},
{'hostname': '0.0.0.0', 'port': 22},
]
response = network_utils.parellelize(network_utils.ping, site_hostname, printers)
self.assertGreater(response[site_hostname]['avg'], 0)
self.assertGreater(response[site_hostname]['127.0.0.1']['avg'], 0)