tzh
2024-08-22 c7d0944258c7d0943aa7b2211498fd612971ce27
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
# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
 
import logging
import csv
import cStringIO
import random
import re
import collections
 
from autotest_lib.client.common_lib.cros import path_utils
 
class ResourceMonitorRawResult(object):
    """Encapsulates raw resource_monitor results."""
 
    def __init__(self, raw_results_filename):
        self._raw_results_filename = raw_results_filename
 
 
    def get_parsed_results(self):
        """Constructs parsed results from the raw ones.
 
        @return ResourceMonitorParsedResult object
 
        """
        return ResourceMonitorParsedResult(self.raw_results_filename)
 
 
    @property
    def raw_results_filename(self):
        """@return string filename storing the raw top command output."""
        return self._raw_results_filename
 
 
class IncorrectTopFormat(Exception):
    """Thrown if top output format is not as expected"""
    pass
 
 
def _extract_value_before_single_keyword(line, keyword):
    """Extract word occurring immediately before the specified keyword.
 
    @param line string the line in which to search for the keyword.
    @param keyword string the keyword to look for. Can be a regexp.
    @return string the word just before the keyword.
 
    """
    pattern = ".*?(\S+) " + keyword
    matches = re.match(pattern, line)
    if matches is None or len(matches.groups()) != 1:
        raise IncorrectTopFormat
 
    return matches.group(1)
 
 
def _extract_values_before_keywords(line, *args):
    """Extract the words occuring immediately before each specified
        keyword in args.
 
    @param line string the string to look for the keywords.
    @param args variable number of string args the keywords to look for.
    @return string list the words occuring just before each keyword.
 
    """
    line_nocomma = re.sub(",", " ", line)
    line_singlespace = re.sub("\s+", " ", line_nocomma)
 
    return [_extract_value_before_single_keyword(
            line_singlespace, arg) for arg in args]
 
 
def _find_top_output_identifying_pattern(line):
    """Return true iff the line looks like the first line of top output.
 
    @param line string to look for the pattern
    @return boolean
 
    """
    pattern ="\s*top\s*-.*up.*users.*"
    matches = re.match(pattern, line)
    return matches is not None
 
 
class ResourceMonitorParsedResult(object):
    """Encapsulates logic to parse and represent top command results."""
 
    _columns = ["Time", "UserCPU", "SysCPU", "NCPU", "Idle",
            "IOWait", "IRQ", "SoftIRQ", "Steal",
            "MemUnits", "UsedMem", "FreeMem",
            "SwapUnits", "UsedSwap", "FreeSwap"]
    UtilValues = collections.namedtuple('UtilValues', ' '.join(_columns))
 
    def __init__(self, raw_results_filename):
        """Construct a ResourceMonitorResult.
 
        @param raw_results_filename string filename of raw batch top output.
 
        """
        self._raw_results_filename = raw_results_filename
        self.parse_resource_monitor_results()
 
 
    def parse_resource_monitor_results(self):
        """Extract utilization metrics from output file."""
        self._utils_over_time = []
 
        with open(self._raw_results_filename, "r") as results_file:
            while True:
                curr_line = '\n'
                while curr_line != '' and \
                        not _find_top_output_identifying_pattern(curr_line):
                    curr_line = results_file.readline()
                if curr_line == '':
                    break
                try:
                    time, = _extract_values_before_keywords(curr_line, "up")
 
                    # Ignore one line.
                    _ = results_file.readline()
 
                    # Get the cpu usage.
                    curr_line = results_file.readline()
                    (cpu_user, cpu_sys, cpu_nice, cpu_idle, io_wait, irq, sirq,
                            steal) = _extract_values_before_keywords(curr_line,
                            "us", "sy", "ni", "id", "wa", "hi", "si", "st")
 
                    # Get memory usage.
                    curr_line = results_file.readline()
                    (mem_units, mem_free,
                            mem_used) = _extract_values_before_keywords(
                            curr_line, "Mem", "free", "used")
 
                    # Get swap usage.
                    curr_line = results_file.readline()
                    (swap_units, swap_free,
                            swap_used) = _extract_values_before_keywords(
                            curr_line, "Swap", "free", "used")
 
                    curr_util_values = ResourceMonitorParsedResult.UtilValues(
                            Time=time, UserCPU=cpu_user,
                            SysCPU=cpu_sys, NCPU=cpu_nice, Idle=cpu_idle,
                            IOWait=io_wait, IRQ=irq, SoftIRQ=sirq, Steal=steal,
                            MemUnits=mem_units, UsedMem=mem_used,
                            FreeMem=mem_free,
                            SwapUnits=swap_units, UsedSwap=swap_used,
                            FreeSwap=swap_free)
                    self._utils_over_time.append(curr_util_values)
                except IncorrectTopFormat:
                    logging.error(
                            "Top output format incorrect. Aborting parse.")
                    return
 
 
    def __repr__(self):
        output_stringfile = cStringIO.StringIO()
        self.save_to_file(output_stringfile)
        return output_stringfile.getvalue()
 
 
    def save_to_file(self, file):
        """Save parsed top results to file
 
        @param file file object to write to
 
        """
        if len(self._utils_over_time) < 1:
            logging.warning("Tried to save parsed results, but they were "
                    "empty. Skipping the save.")
            return
        csvwriter = csv.writer(file, delimiter=',')
        csvwriter.writerow(self._utils_over_time[0]._fields)
        for row in self._utils_over_time:
            csvwriter.writerow(row)
 
 
    def save_to_filename(self, filename):
        """Save parsed top results to filename
 
        @param filename string filepath to write to
 
        """
        out_file = open(filename, "wb")
        self.save_to_file(out_file)
        out_file.close()
 
 
class ResourceMonitorConfig(object):
    """Defines a single top run."""
 
    DEFAULT_MONITOR_PERIOD = 3
 
    def __init__(self, monitor_period=DEFAULT_MONITOR_PERIOD,
            rawresult_output_filename=None):
        """Construct a ResourceMonitorConfig.
 
        @param monitor_period float seconds between successive top refreshes.
        @param rawresult_output_filename string filename to output the raw top
                                                results to
 
        """
        if monitor_period < 0.1:
            logging.info('Monitor period must be at least 0.1s.'
                    ' Given: %r. Defaulting to 0.1s', monitor_period)
            monitor_period = 0.1
 
        self._monitor_period = monitor_period
        self._server_outfile = rawresult_output_filename
 
 
class ResourceMonitor(object):
    """Delegate to run top on a client.
 
    Usage example (call from a test):
    rmc = resource_monitor.ResourceMonitorConfig(monitor_period=1,
            rawresult_output_filename=os.path.join(self.resultsdir,
                                                    'topout.txt'))
    with resource_monitor.ResourceMonitor(self.context.client.host, rmc) as rm:
        rm.start()
        <operation_to_monitor>
        rm_raw_res = rm.stop()
        rm_res = rm_raw_res.get_parsed_results()
        rm_res.save_to_filename(
                os.path.join(self.resultsdir, 'resource_mon.csv'))
 
    """
 
    def __init__(self, client_host, config):
        """Construct a ResourceMonitor.
 
        @param client_host: SSHHost object representing a remote ssh host
 
        """
        self._client_host = client_host
        self._config = config
        self._command_top = path_utils.must_be_installed(
                'top', host=self._client_host)
        self._top_pid = None
 
 
    def __enter__(self):
        return self
 
 
    def __exit__(self, exc_type, exc_value, traceback):
        if self._top_pid is not None:
            self._client_host.run('kill %s && rm %s' %
                    (self._top_pid, self._client_outfile), ignore_status=True)
        return True
 
 
    def start(self):
        """Run top and save results to a temp file on the client."""
        if self._top_pid is not None:
            logging.debug("Tried to start monitoring before stopping. "
                    "Ignoring request.")
            return
 
        # Decide where to write top's output to (on the client).
        random_suffix = random.random()
        self._client_outfile = '/tmp/topcap-%r' % random_suffix
 
        # Run top on the client.
        top_command = '%s -b -d%d > %s' % (self._command_top,
                self._config._monitor_period, self._client_outfile)
        logging.info('Running top.')
        self._top_pid = self._client_host.run_background(top_command)
        logging.info('Top running with pid %s', self._top_pid)
 
 
    def stop(self):
        """Stop running top and return the results.
 
        @return ResourceMonitorRawResult object
 
        """
        logging.debug("Stopping monitor")
        if self._top_pid is None:
            logging.debug("Tried to stop monitoring before starting. "
                    "Ignoring request.")
            return
 
        # Stop top on the client.
        self._client_host.run('kill %s' % self._top_pid, ignore_status=True)
 
        # Get the top output file from the client onto the server.
        if self._config._server_outfile is None:
            self._config._server_outfile = self._client_outfile
        self._client_host.get_file(
                self._client_outfile, self._config._server_outfile)
 
        # Delete the top output file from client.
        self._client_host.run('rm %s' % self._client_outfile,
                ignore_status=True)
 
        self._top_pid = None
        logging.info("Saved resource monitor results at %s",
                self._config._server_outfile)
        return ResourceMonitorRawResult(self._config._server_outfile)