~zyga/checkbox/fix-1235426

« back to all changes in this revision

Viewing changes to providers/plainbox-provider-checkbox/bin/gateway_ping_test

  • Committer: Daniel Manrique
  • Author(s): Daniel Manrique
  • Date: 2014-06-11 12:16:24 UTC
  • mfrom: (3056.2.1 launchpad/1232774-ping)
  • Revision ID: daniel_manrique-20140611121624-asm1asibbyw5shgk
"    providers:checkbox: Minor refactoring of gateway_ping_test.
    
    Rewrote the way ping command is invoked and the output is processed to
    solve a few problems (LP: #1232774). [r=zkrynicki][bug=1232774][author=roadmr]"

Show diffs side-by-side

added added

removed removed

Lines of Context:
157
157
 
158
158
 
159
159
def ping(host, interface, count, deadline, verbose=False):
160
 
    command = "ping -c %s -w %s %s" % (count, deadline, host)
 
160
 
 
161
    command = ["ping", str(host),  "-c", str(count), "-w", str(deadline)]
161
162
    if interface:
162
 
        command = ("ping -I%s -c %s -w %s %s"
163
 
                   % (interface, count, deadline, host))
 
163
        command.append("-I{}".format(interface))
164
164
 
165
165
    reg = re.compile(r"(\d+) packets transmitted, (\d+) received, (\d+)% packet loss")
166
 
    ping_summary = None
 
166
    ping_summary = {'transmitted': 0, 'received': 0, 'pct_loss': 0}
167
167
 
168
 
    output = os.popen(command)
169
 
    for line in output.readlines():
 
168
    try:
 
169
        output = subprocess.check_output(command, universal_newlines=True)
 
170
    except FileNotFoundError as excp:
 
171
        # No ping command present; default exception message is
 
172
        # informative enough.
 
173
        print(excp)
 
174
    except subprocess.CalledProcessError as excp:
 
175
        # Ping returned fail exit code
 
176
        print("ERROR: ping result: {}".format(excp))
 
177
    else:
170
178
        if verbose:
171
 
            print(line.rstrip())
 
179
            print(output)
172
180
 
173
 
        received = re.findall(reg, line)
 
181
        received = re.findall(reg, output)
174
182
        if received:
175
183
            ping_summary = received[0]
176
184
 
177
 
    ping_summary={'transmitted': int(ping_summary[0]),
178
 
                  'received': int(ping_summary[1]),
179
 
                  'pct_loss': int(ping_summary[2])}
 
185
            ping_summary={'transmitted': int(ping_summary[0]),
 
186
                          'received': int(ping_summary[1]),
 
187
                          'pct_loss': int(ping_summary[2])}
180
188
    return ping_summary
181
189
 
182
190