Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
S2-group
GitHub Repository: S2-group/android-runner
Path: blob/master/tests/unit/fixtures/Android1.py
908 views
1
import csv
2
import os
3
import os.path as op
4
import threading
5
import time
6
import timeit
7
from collections import OrderedDict
8
9
from .Profiler import Profiler
10
from functools import reduce
11
12
13
class ConfigError(Exception):
14
pass
15
16
17
class Android1(Profiler):
18
def __init__(self, config, paths):
19
super(Android1, self).__init__(config, paths)
20
self.output_dir = ''
21
self.paths = paths
22
self.profile = False
23
available_data_points = ['cpu', 'mem']
24
self.interval = float(self.is_integer(config.get('sample_interval', 0))) / 1000
25
self.data_points = config['data_points']
26
invalid_data_points = [dp for dp in config['data_points'] if dp not in set(available_data_points)]
27
if invalid_data_points:
28
self.logger.warning('Invalid data points in config: {}'.format(invalid_data_points))
29
self.data_points = [dp for dp in config['data_points'] if dp in set(available_data_points)]
30
self.data = [['datetime'] + self.data_points]
31
32
@staticmethod
33
def get_cpu_usage(device):
34
"""Get CPU usage in percentage"""
35
# return device.shell('dumpsys cpuinfo | grep TOTAL | cut -d" " -f1').strip()[:-1]
36
shell_result = device.shell('dumpsys cpuinfo | grep TOTAL')
37
shell_splitted = shell_result.split('%')[0]
38
if '-' in shell_splitted:
39
print(shell_result)
40
print(shell_splitted)
41
return shell_splitted
42
# return device.shell('dumpsys cpuinfo | grep TOTAL').split('%')[0]
43
44
@staticmethod
45
def get_mem_usage(device, app):
46
"""Get memory usage in KB for app, if app is None system usage is used"""
47
if not app:
48
# return device.shell('dumpsys meminfo | grep Used | cut -d" " -f5').strip()[1:-1]
49
# return device.shell('dumpsys meminfo | grep Used').split()[2].strip()[1:-1].replace(",", ".")
50
return device.shell('dumpsys meminfo | grep Used').translate(None, '(kB,K').split()[2]
51
else:
52
result = device.shell('dumpsys meminfo {} | grep TOTAL'.format(app))
53
if 'No process found' in result:
54
raise Exception('Android Profiler: {}'.format(result))
55
return ' '.join(result.strip().split()).split()[1]
56
57
def start_profiling(self, device, **kwargs):
58
self.profile = True
59
app = kwargs.get('app', None)
60
self.get_data(device, app)
61
62
def get_data(self, device, app):
63
"""Runs the profiling methods every self.interval seconds in a separate thread"""
64
start = timeit.default_timer()
65
device_time = device.shell('date -u')
66
row = [device_time]
67
if 'cpu' in self.data_points:
68
row.append(self.get_cpu_usage(device))
69
if 'mem' in self.data_points:
70
row.append(self.get_mem_usage(device, app))
71
self.data.append(row)
72
end = timeit.default_timer()
73
# timer results could be negative
74
interval = max(float(0), self.interval - max(0, int(end - start)))
75
if self.profile:
76
threading.Timer(interval, self.get_data, args=(device, app)).start()
77
78
def stop_profiling(self, device, **kwargs):
79
self.profile = False
80
81
def collect_results(self, device, path=None):
82
filename = '{}_{}.csv'.format(device.id, time.strftime('%Y.%m.%d_%H%M%S'))
83
with open(op.join(self.output_dir, filename), 'w+') as f:
84
writer = csv.writer(f)
85
for row in self.data:
86
writer.writerow(row)
87
88
def set_output(self, output_dir):
89
self.output_dir = output_dir
90
91
def dependencies(self):
92
return ['android1.test.dependency']
93
94
def load(self, device):
95
return
96
97
def unload(self, device):
98
return
99
100
def aggregate_subject(self):
101
filename = os.path.join(self.output_dir, 'Aggregated.csv')
102
subject_rows = list()
103
subject_rows.append(self.aggregate_android_subject(self.output_dir))
104
self.write_to_file(filename, subject_rows)
105
106
def aggregate_end(self, data_dir, output_file):
107
rows = self.aggregate_final(data_dir)
108
self.write_to_file(output_file, rows)
109
110
@staticmethod
111
def aggregate_android_subject(logs_dir):
112
def add_row(accum, new):
113
row = {k: v + float(new[k]) for k, v in list(accum.items()) if k not in ['Component', 'count']}
114
count = accum['count'] + 1
115
return dict(row, **{'count': count})
116
117
runs = []
118
for run_file in [f for f in os.listdir(logs_dir) if os.path.isfile(os.path.join(logs_dir, f))]:
119
with open(os.path.join(logs_dir, run_file), 'rb') as run:
120
reader = csv.DictReader(run)
121
init = dict({fn: 0 for fn in reader.fieldnames if fn != 'datetime'}, **{'count': 0})
122
run_total = reduce(add_row, reader, init)
123
runs.append({k: v / run_total['count'] for k, v in list(run_total.items()) if k != 'count'})
124
runs_total = reduce(lambda x, y: {k: v + y[k] for k, v in list(x.items())}, runs)
125
return OrderedDict(
126
sorted(list({'android_' + k: v / len(runs) for k, v in list(runs_total.items())}.items()), key=lambda x: x[0]))
127
128
def aggregate_final(self, data_dir):
129
rows = []
130
for device in self.list_subdir(data_dir):
131
row = OrderedDict({'device': device})
132
device_dir = os.path.join(data_dir, device)
133
for subject in self.list_subdir(device_dir):
134
row.update({'subject': subject})
135
subject_dir = os.path.join(device_dir, subject)
136
if os.path.isdir(os.path.join(subject_dir, 'android')):
137
row.update(self.aggregate_android_final(os.path.join(subject_dir, 'android')))
138
rows.append(row.copy())
139
else:
140
for browser in self.list_subdir(subject_dir):
141
row.update({'browser': browser})
142
browser_dir = os.path.join(subject_dir, browser)
143
if os.path.isdir(os.path.join(browser_dir, 'android')):
144
row.update(self.aggregate_android_final(os.path.join(browser_dir, 'android')))
145
rows.append(row.copy())
146
return rows
147
148
@staticmethod
149
def aggregate_android_final(logs_dir):
150
for aggregated_file in [f for f in os.listdir(logs_dir) if os.path.isfile(os.path.join(logs_dir, f))]:
151
if aggregated_file == "Aggregated.csv":
152
with open(os.path.join(logs_dir, aggregated_file), 'rb') as aggregated:
153
reader = csv.DictReader(aggregated)
154
row_dict = OrderedDict()
155
for row in reader:
156
for f in reader.fieldnames:
157
row_dict.update({f: row[f]})
158
return OrderedDict(row_dict)
159
160
@staticmethod
161
def list_subdir(a_dir):
162
"""List immediate subdirectories of a_dir"""
163
# https://stackoverflow.com/a/800201
164
return [name for name in os.listdir(a_dir)
165
if os.path.isdir(os.path.join(a_dir, name))]
166
167
@staticmethod
168
def write_to_file(filename, rows):
169
with open(filename, 'w') as f:
170
writer = csv.DictWriter(f, list(rows[0].keys()))
171
writer.writeheader()
172
writer.writerows(rows)
173
174
@staticmethod
175
def is_integer(number, minimum=0):
176
if not isinstance(number, int):
177
raise ConfigError('%s is not an integer' % number)
178
if number < minimum:
179
raise ConfigError('%s should be equal or larger than %i' % (number, minimum))
180
return number
181
182