Home | History | Annotate | Download | only in metrics
      1 #!/usr/bin/env python
      2 #
      3 #   Copyright 2017 - The Android Open Source Project
      4 #
      5 #   Licensed under the Apache License, Version 2.0 (the "License");
      6 #   you may not use this file except in compliance with the License.
      7 #   You may obtain a copy of the License at
      8 #
      9 #       http://www.apache.org/licenses/LICENSE-2.0
     10 #
     11 #   Unless required by applicable law or agreed to in writing, software
     12 #   distributed under the License is distributed on an "AS IS" BASIS,
     13 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14 #   See the License for the specific language governing permissions and
     15 #   limitations under the License.
     16 
     17 from metrics.metric import Metric
     18 from utils import job
     19 from utils import shell
     20 
     21 
     22 class NetworkMetric(Metric):
     23     """Determines if test server is connected to network by passed in ip's.
     24 
     25     The dev servers pinged is determined by the cli arguments.
     26     """
     27     DEFAULT_IPS = ['8.8.8.8', '8.8.4.4']
     28     HOSTNAME_COMMAND = 'hostname | cut -d- -f1'
     29     PING_COMMAND = 'ping -c 1 -W 1 {}'
     30     CONNECTED = 'connected'
     31 
     32     def __init__(self, ip_list=None, shell=shell.ShellCommand(job)):
     33         Metric.__init__(self, shell=shell)
     34         self.ip_list = ip_list
     35 
     36     def get_prefix_hostname(self):
     37         """Gets the hostname prefix of the test station.
     38 
     39         Example, on android-test-server-14, it would return, android
     40 
     41         Returns:
     42             The prefix of the hostname.
     43         """
     44         return self._shell.run('hostname | cut -d- -f1').stdout
     45 
     46     def check_connected(self, ips=None):
     47         """Determines if a network connection can be established to a dev server
     48 
     49         Args:
     50             ips: The list of ip's to ping.
     51         Returns:
     52             A dictionary of ip addresses as keys, and whether they're connected
     53             as values.
     54         """
     55         if not ips:
     56             ips = self.DEFAULT_IPS
     57 
     58         ip_dict = {}
     59         for ip in ips:
     60             # -c 1, ping once, -W 1, set timeout 1 second.
     61             stat = self._shell.run(
     62                 self.PING_COMMAND.format(ip), ignore_status=True).exit_status
     63             ip_dict[ip] = stat == 0
     64         return ip_dict
     65 
     66     def gather_metric(self):
     67         is_connected = self.check_connected(self.ip_list)
     68         return {self.CONNECTED: is_connected}
     69