summaryrefslogtreecommitdiff
path: root/validation/test/av_home/av_home.py
blob: 10e30e3eff55e29d512df67ca921cf62de5ada25 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
# -*- coding: utf-8 -*-

"""Module allowing to generate P2P report in field test."""

import re, os, sys
import ConfigParser
import av_home_attr
import av_mme
import shlex
import subprocess

def master_script():
    print ("Executing master script")
    test_init ()
    set_test_desc ()
    print ("Executing ping on slave PC ("+ av_home_attr.addr +")...")
    av_mme.ping_peer ()
    print ("Sending MME for environment discovery to " + av_home_attr.plug_mac +
    " through " + av_home_attr.iface + " ...")
    av_mme.get_network_env("master")
    raw_input ("Press enter when slave script has been launched")
    print ("Executing upload iperf test on " + av_home_attr.addr + " ...")
    iperf_client_run ()
    server = iperf_server_spawn ()
    raw_input ("Press enter when slave script has finished upload iperf")
    iperf_server_stop (server)
    av_mme.get_stats ("master")
    prepare_points ("master")
    get_general_result ("master")
    prepare_archive ("master")

def slave_script():
    print ("Executing slave script")
    test_init ()
    print ("Executing ping on master PC ("+ av_home_attr.addr +")...")
    av_mme.ping_peer ()
    print ("Sending MME for environment discovery to " + av_home_attr.plug_mac +
    " through " + av_home_attr.iface + " ...")
    av_mme.get_network_env("slave")
    print ("Starting iperf server...")
    server = iperf_server_spawn ()
    raw_input ("Press enter when master script has finished upload iperf test")
    iperf_server_stop (server)
    print ("Executing upload iperf test...")
    iperf_client_run ()
    av_mme.get_stats ("slave")
    prepare_points ("slave")
    get_general_result ("slave")
    prepare_archive ("slave")

def report():
    prepare_plot ()
    generate_report ()

def config_get_item (config, section, key):
    """Get the value of the key in the section from the config parser"""
    try:
        return config.get (section, key)
    except:
        return None

def parse_config(file):
    config = ConfigParser.RawConfigParser ()
    config.read (file)
    av_home_attr.plug_mac = config_get_item (config, 'Test', 'plug_mac')
    av_home_attr.peer_mac = config_get_item (config, 'Test', 'peer_mac')
    av_home_attr.source_mac = config_get_item (config, 'Test', 'source_mac')
    av_home_attr.iface = config_get_item (config, 'Test', 'iface')
    av_home_attr.addr = config_get_item (config, 'Test', 'addr')
    av_home_attr.output_dir = config_get_item (config, 'Test', 'output_dir')
    av_home_attr.scammer_path = config_get_item (config, 'Test', 'scammer_path')
    av_home_attr.author = config_get_item (config, 'Report', 'author')

def set_opts(options, prefix):
    if options.plug_mac:
        av_home_attr.plug_mac = options.plug_mac
    if options.peer_mac:
        av_home_attr.peer_mac = options.peer_mac
    if options.source_mac:
        av_home_attr.source_mac = options.source_mac
    if options.addr:
        av_home_attr.addr = options.addr
    if options.output_dir:
        av_home_attr.output_dir = options.output_dir
    if options.iface:
        av_home_attr.iface = options.iface
    if options.scammer_path:
        av_home_attr.scammer_path = options.scammer_path
    if prefix:
        av_home_attr.prefix = prefix
    else:
        av_home_attr.prefix = "."

def check_params():
    errorstr = ""
    error = 0
    mac_re = re.compile (r"([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$")
    if not re.match (mac_re, av_home_attr.plug_mac) \
            or not re.match (mac_re, av_home_attr.peer_mac) \
            or not re.match (mac_re, av_home_attr.source_mac):
                print "MAC address invalid"
                sys.exit (1)
    if not re.match (r"((((25[0-5])|(2[0-4][0-9])|(1?[0-9]{1,2})).){3})((25[0-5])|(2[0-4][0-9])|(1?[0-9]{1,2}))$",
            av_home_attr.addr):
        print "IP address invalid"
        sys.exit (1)
    if not av_home_attr.scammer_path:
        print "You must set the path to scammer"
        sys.exit (1)

def test_init():
    if not av_home_attr.output_dir:
        av_home_attr.output_dir = "test_home-default"
    else:
        av_home_attr.output_dir = "test_home-%s" % av_home_attr.output_dir
    av_home_attr.output_dir = os.path.join (av_home_attr.prefix,
            av_home_attr.output_dir)
    if not os.path.exists(av_home_attr.output_dir):
        os.mkdir (av_home_attr.output_dir)
    else:
        print "Test directory already exists, choose another name"
        sys.exit (1)

def iperf_server_spawn ():
    args = shlex.split ("iperf -s -u -i 1")
    with open (os.path.join (av_home_attr.output_dir, "server_log"), "w") as f:
        server = subprocess.Popen(args, stdout=f)
    return server

def iperf_server_stop (server):
    server.terminate ()

def iperf_client_run ():
    args = shlex.split ("iperf -c " + av_home_attr.addr + " -t 60 -u -b 100m -i 1")
    with open (os.path.join (av_home_attr.output_dir, "client_log"), "w") as f:
        client = subprocess.Popen(args, stdout=f)
    client.wait ()

def prepare_points (mode):
    # Get min and max value from server logs
    try:
        f = open (os.path.join (av_home_attr.output_dir, "server_log"), "r")
    except IOError:
        return
    lines = f.readlines ()
    minimum = 0
    maximum = 0
    id = []
    id_re = re.compile (r"^\[ *([1-9][0-9]*)\] .* connected .*$")
    for l in lines:
        result = id_re.match (l)
        if result:
            id.append (result.group(1))
    f.close ()
    f = open (os.path.join (av_home_attr.output_dir, "%s_plot" % mode), "w")
    for i in id:
        res = []
        pattern = r"^\[ *%s\] *[0-9]+\.0- *[0-9]+\.0.*([0-9]+\.?[0-9]*) [KM]Bytes *([0-9]+\.?[0-9]*).*" % i
        val_re = re.compile (pattern)
        for l in lines:
            result = val_re.match (l)
            if result:
                value = float (result.group (2))
                if not maximum:
                    maximum = value
                if not minimum:
                    minimum = value
                if value < minimum:
                    minimum = value
                if value > maximum:
                    maximum = value
                res.append (value)
        s = str (minimum) + ";" + str (maximum)
        for v in res:
            s += ";" + str(v)
        print >> f, s
    f.close ()
    # Prepare tonemap points
    try:
        f = open (os.path.join (av_home_attr.output_dir, "tonemap"), "r")
    except IOError:
        return
    lines = f.readlines ()[2:]
    s = ""
    for l in lines:
        for c in l:
            if ord (c) <= ord('7') and ord (c) >= ord ('0'):
                s += c
    f.close ()
    f = open (os.path.join (av_home_attr.output_dir, "tonemap-%s_plot" % mode), "w")
    print >> f, s,
    f.close ()

def get_general_result (mode):
    # Get average up and down throughput
    try:
        f = open (os.path.join (av_home_attr.output_dir, "server_log"), "r")
    except IOError:
        return
    lines = f.readlines ()
    result_re = re.compile (r"^.* 0\.0-[0-9]+\.[0-9].* ([0-9]+.*) Mbits/sec")
    avg = ""
    for l in lines:
        result = result_re.match (l)
        if result:
            avg = result.group (1)
            break
    if not avg:
        print "Some error occured during the download test, check peer plug for assert traces."
    else:
        print "Average download throughput: %s Mbps" % avg
    f.close ()
    try:
        f = open (os.path.join (av_home_attr.output_dir, "client_log"), "r")
    except IOError:
        return
    lines = f.readlines ()
    server_re = re.compile(r".*Server Report.*")
    avg = ""
    server = 0
    for l in lines:
        result = result_re.match (l)
        if not server:
            server = server_re.match (l)
        if result and server:
            avg = result.groups (1)
            break
    if not avg:
        print "Some error occured during the upload test, check plug for assert traces."
    else:
        print "Average upload throughput: %s Mbps" % avg
    f.close ()
    # Get tonemap stats
    f = open (os.path.join (av_home_attr.prefix, "tonemask"), "r")
    line = f.readlines ()[0]
    available_carrier = 0
    for c in line:
        if c == '0':
            available_carrier += 1
    f.close ()
    try:
        f = open (os.path.join (av_home_attr.output_dir, "tonemap-%s_plot" % mode), "r")
    except IOError:
        return
    line = f.readlines ()[0]
    f.close ()
    mod_list = [0, 0, 0, 0, 0, 0, 0, 0]
    bit_list = [0, 1, 2, 3, 4, 6, 8, 10]
    bit_value = 0
    for c in line:
        mod_list[int(c)] += 1
        bit_value += bit_list[int(c)]
    nb_carrier = sum (mod_list[1:])
    mod = { 1: "BPSK",
            2: "QPSK",
            3: "8-QAM",
            4: "16-QAM",
            5: "64-QAM",
            6: "256-QAM",
            7: "1024-QAM" }
    print "Using %d carriers on %d (%d%%)" % (nb_carrier, available_carrier, (nb_carrier * 100) / available_carrier)
    avg_str =  "%f bits per symbol" % (float(bit_value) / float(available_carrier))
    try:
        f = open (os.path.join (av_home_attr.output_dir, "tonemap"), "r")
    except IOError:
        return
    fec = int (f.readlines ()[0])
    if fec == 1:
        fec_str = "FEC 16/21"
    else:
        fec_str = "FEC 1/2"
    f.close ()
    f = open (os.path.join (av_home_attr.output_dir, "tonemap-%s_plot" % mode), "a")
    print >>f, ";%s - %s" % (avg_str, fec_str),
    f.close ()
    for i in mod:
        print "With %s modulation: %d (%d%%)" % (mod[i], mod_list[i], (mod_list[i] * 100) / nb_carrier)

def prepare_archive (mode):
    os.chdir (av_home_attr.prefix)
    # Create the archive
    args = shlex.split ("tar cf test-%s.tar soft_version-%s" % (mode, mode))
    p = subprocess.Popen (args, shell=False)
    p.wait ()
    directories = os.listdir (".")
    dir_re = re.compile (r"^test_home-.*$")
    for d in directories:
        if dir_re.match (d):
            args = shlex.split ("tar rf test-%s.tar %s" % (mode, d))
            p = subprocess.Popen (args, shell=False)
            p.wait ()
    args = shlex.split ("bzip2 -zf test-%s.tar" % mode)
    p = subprocess.Popen (args, shell=False)
    p.wait ()

def prepare_plot ():
    directories = os.listdir(os.path.join (av_home_attr.prefix, "."))
    dir_re = re.compile (r"^test_home-.*$")
    for d in directories:
        if re.match (dir_re, d):
            do_plot ("rx", d)
            do_plot ("tx", d)

def do_plot (direction, directory):
    import pylab
    try:
        if direction == "rx":
            f = open (os.path.join (av_home_attr.prefix,
                directory,
                "master_plot"),
                "r")
        else:
            f = open (os.path.join (av_home_attr.prefix,
                directory,
                "slave_plot"),
                "r")
    except IOError:
        return
    lines = f.readlines ()
    maximum = 0
    minimum = 0
    for l in lines:
        # Get minimum and maximum value from server logs
        values = l.split (';')
        local_maximum = (int (float (values[1])) * 4) / 3
        if local_maximum > maximum:
            maximum = local_maximum
        local_minimum = (int (float (values[0])) * 2) / 3
        if local_minimum < minimum:
            minimum = local_minimum
        x = [ j for j in xrange (len(values) - 2)]
        y = [ values[j + 2] for j in xrange (len(values) - 2)]
        pylab.plot (x,y)
    pylab.ylim ([minimum,maximum])
    pylab.ylabel("Throughput in Mbps")
    pylab.xlabel("Time in seconds")
    if direction == "rx":
        pylab.title("Download throughput for %s" % av_home_attr.plug_mac)
    else:
        pylab.title("Upload throughput for %s" % av_home_attr.plug_mac)
    pylab.gcf().savefig (os.path.join (av_home_attr.prefix, directory, "master-%s.png" % direction))
    pylab.clf()
    f.close ()
    try:
        if direction == "rx":
            f = open (os.path.join (av_home_attr.prefix,
                directory,
                "tonemap-slave_plot"),
                "r")
        else:
            f = open (os.path.join (av_home_attr.prefix,
                directory,
                "tonemap-master_plot"),
                "r")
    except IOError:
        return
    lines = f.readlines ()[0]
    x = [ j for j in xrange (1536)]
    y = [ lines[j] for j in xrange (1536)]
    avg = lines[1537:]
    pylab.plot (x, y)
    f.close ()
    f = open (os.path.join(av_home_attr.prefix, "tonemask"), "r")
    lines = f.readlines ()[0]
    z = [ lines[j] for j in xrange (1536)]
    pylab.plot (x, z, color='grey', alpha=0.5)
    good = []
    wrong = []
    unused = []
    for i in xrange (len(y)):
        if (y[i]>=z[i] and z[i] == '0'):
            good.append (True)
            wrong.append (False)
            unused.append (False)
        if z[i] != '0' and y[i] != '0':
            wrong.append (True)
            good.append (False)
            unused.append (False)
        if y[i] == '0' and z[i] != '0':
            wrong.append (False)
            good.append (False)
            unused.append (True)
    pylab.fill_between (x, y, z, where=good, color='blue')
    pylab.fill_between (x, y, z, where=wrong, color='red')
    pylab.fill_between (x, y, z, where=unused, color='grey', alpha=0.5)
    pylab.ylim ([0,8])
    pylab.ylabel("Modulation")
    pylab.xlabel("Carriers")
    pylab.title("Default tonemap - %s - %s" %
            (direction, avg))
    pylab.gcf().savefig (os.path.join (av_home_attr.prefix, directory, "tonemap-%s.png" % direction))
    pylab.clf()

def get_test_data ():
    tpl = """{name}

::

    {desc}

Discover list
-------------
{discovery}

Network info
------------
{avln}

Attenuation list
----------------
{attenuation}

Tonemaps and throughput
-----------------------
{graph}
"""
    result = ""
    # Get all test results
    directories = os.listdir(os.path.join (av_home_attr.prefix, "."))
    dir_re = re.compile (r"^test_home-(.*)$")
    for d in sorted(directories):
        if dir_re.match (d):
            name = get_name (dir_re.match (d).group (1))
            desc = get_test_desc (d)
            discovery = get_field (d, "discovery")
            avln = get_field (d, "avln")
            attenuation = get_field (d, "attenuation")
            graph = get_graph (d)
            result += tpl.format (name = name,
                    desc = desc,
                    discovery = discovery,
                    avln = avln,
                    attenuation = attenuation,
                    graph = graph)
    return result

def get_name (name):
    result = "Test %s:" % name
    underline = ""
    for i in xrange (len(result)):
        underline += "="
    return result + "\n" + underline

def get_field (d, file):
    try:
        f = open (os.path.join (av_home_attr.prefix, d, "%s-master" % file), "r")
        value = f.read ()
        f.close ()
        f = open (os.path.join (av_home_attr.prefix, d, "%s-slave" % file), "r")
        value += f.read ()
        f.close ()
    except IOError:
        return "Data missing ..."
    return value

def get_graph (d):
    tpl = """
Upload:

{upload}

{tx}

Download:

{download}

{rx}

"""
    images = [ "master-tx.png",
            "master-rx.png",
            "tonemap-tx.png",
            "tonemap-rx.png" ]
    paths = {}
    for img in images:
        try:
            f = open ("%s/%s" % (d, img), "r")
            f.close ()
            paths[img] = ".. image:: %s/%s" % (d, img)
        except IOError:
            paths[img] = "Data missing ..."

    return tpl.format (upload = paths["master-tx.png"],
            download = paths["master-rx.png"],
            tx = paths["tonemap-tx.png"],
            rx = paths["tonemap-rx.png"])

def generate_report ():
    f = open (os.path.join (av_home_attr.prefix, "template.rst"), "r")
    tpl = f.read ()
    tpl = tpl.format (author = av_home_attr.author,
            master = av_home_attr.plug_mac,
            slave = av_home_attr.peer_mac,
            soft = get_field (".", "soft_version"),
            tests = get_test_data ())
    print tpl
    f.close ()

def set_test_desc ():
    f = open (os.path.join (av_home_attr.output_dir, "DESC"), "w")
    print >>f, raw_input ("Enter test description:")
    f.close ()

def get_test_desc (d):
    f = open (os.path.join (av_home_attr.prefix, d, "DESC"), "r")
    value = f.read ()
    f.close ()
    return value