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