stats.py 9.25 KB
Newer Older
André Anjos's avatar
André Anjos committed
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
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :

###############################################################################
#                                                                             #
# Copyright (c) 2016 Idiap Research Institute, http://www.idiap.ch/           #
# Contact: beat.support@idiap.ch                                              #
#                                                                             #
# This file is part of the beat.core module of the BEAT platform.             #
#                                                                             #
# Commercial License Usage                                                    #
# Licensees holding valid commercial BEAT licenses may use this file in       #
# accordance with the terms contained in a written agreement between you      #
# and Idiap. For further information contact tto@idiap.ch                     #
#                                                                             #
# Alternatively, this file may be used under the terms of the GNU Affero      #
# Public License version 3 as published by the Free Software and appearing    #
# in the file LICENSE.AGPL included in the packaging of this file.            #
# The BEAT platform is distributed in the hope that it will be useful, but    #
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY  #
# or FITNESS FOR A PARTICULAR PURPOSE.                                        #
#                                                                             #
# You should have received a copy of the GNU Affero Public License along      #
# with the BEAT platform. If not, see http://www.gnu.org/licenses/.           #
#                                                                             #
###############################################################################


'''A class that can read, validate and update statistical information'''

import os
import time
import copy

import simplejson

from . import schema
from . import prototypes

class Statistics(object):
  """Statistics define resource usage for algorithmic code runs


  Parameters:

    data (object, optional): The piece of data representing the
      statistics the be read, it must validate against our pre-defined
      execution schema. If the input is ``None`` or empty, then start a new
      statistics from scratch.


  Attributes:

    errors (list of str): A list containing errors found while loading this
      statistics information.

    data (dict): The original data for these statistics

  """

  def __init__(self, data=None):

    self.errors = []

    if data:
      self._load(data) #also runs validation
    else:
      self._data, self.errors = prototypes.load('statistics') #also validates

  def _load(self, data):
    """Loads the statistics

    Parameters:

      data (object, str, file): The piece of data to load. The input can be a
        valid python object that represents a JSON structure, a file, from
        which the JSON contents will be read out or a string. See
        :py:func:`schema.validate` for more details.

    """

    # reset
    self._data = None
    self.errors = []

    if not isinstance(data, dict): #user has passed a file pointer
      if not os.path.exists(data):
        self.errors.append('File not found: %s' % data)
        return

    # this runs basic validation, including JSON loading if required
    self._data, self.errors = schema.validate('statistics', data)
    if self.errors: return #don't proceed with the rest of validation


  @property
  def schema_version(self):
    """Returns the schema version"""
    return self.data.get('schema_version', 1)


  @property
  def cpu(self):
    """Returns only CPU information"""
    return self._data['cpu']

  @cpu.setter
  def cpu(self, data):
    """Sets the CPU information"""

    for key in ('user', 'system', 'total'):
        self._data['cpu'][key] = data[key]

    for key in ('voluntary', 'involuntary'):
      self._data['cpu']['context_switches'][key] = data['context_switches'][key]


  @property
  def memory(self):
    """Returns only memory information"""
    return self._data['memory']


  @memory.setter
  def memory(self, data):
    """Sets only the memory information"""

    for key in ('rss',): self._data['memory'][key] = data[key]


  @property
  def data(self):
    """Returns only I/O information"""
    return self._data['data']


  @data.setter
  def data(self, data):
    """Sets only the I/O information"""

    for key in ('volume', 'blocks', 'time'):
      self._data['data'][key]['read'] = data[key]['read']
      self._data['data'][key]['write'] = data[key]['write']

    self._data['data']['files'] = list(data['files'])
    self._data['network'] = data['network']


  @property
  def valid(self):
    """A boolean that indicates if this executor is valid or not"""

    return not bool(self.errors)


  def __add__(self, other):
    """Adds two statistics data blocks"""

    retval = Statistics(copy.deepcopy(self._data))
    retval += other
    return retval


  def __iadd__(self, other):
    """Self-add statistics from another block"""

    if not isinstance(other, Statistics): return NotImplemented

    for key in ('user', 'system', 'total'):
        self._data['cpu'][key] += other._data['cpu'][key]

    for key in ('voluntary', 'involuntary'):
      self._data['cpu']['context_switches'][key] += \
              other._data['cpu']['context_switches'][key]

    for key in ('rss', ): #gets the maximum between the two
      self._data['memory'][key] = max(other._data['memory'][key],
          self._data['memory'][key])

    for key in ('volume', 'blocks', 'time'):
      self._data['data'][key]['read'] += other._data['data'][key]['read']
      self._data['data'][key]['write'] += other._data['data'][key]['write']

    self._data['data']['files'] += other._data['data']['files']

    self._data['data']['network']['wait_time'] += \
            other._data['data']['network']['wait_time']

    return self


  def __str__(self):

    return self.as_json(2)


  def as_json(self, indent=None):

    return simplejson.dumps(self._data, indent=indent)


  def as_dict(self):

      return self._data


  def write(self, f):
    """Writes contents to a file-like object"""

    if hasattr(f, 'write'): f.write(str(self))
    else:
      with open(f, 'wt') as fobj: fobj.write(str(self))


def io_statistics(data_sources, input_list, data_sinks, output_list, data, analyzer=False):
  """Summarize current I/O statistics looking at data sources and sinks

  Returns:

    dict: A dictionary summarizing current I/O statistics, read from our
      sinks, sources, inputs and outputs.
  """

  # data reading
  bytes_read = 0
  blocks_read = 0
  read_time = 0.0

  for source in data_sources:
    size, duration = source.statistics()
    bytes_read += size
    read_time += duration

  for inpt in input_list:
    blocks_read += inpt.nb_data_blocks_read

  # data writing
  bytes_written = 0
  blocks_written = 0
  write_time = 0.0

  for sink in data_sinks:
    size, duration = sink.statistics()
    bytes_written += size
    write_time += duration

  files = []
  for outpt in output_list:
    blocks_written += outpt.nb_data_blocks_written
    #if self.analysis:
    if analyzer: #'outputs' in self.data: #it is a normal block (not analyzer)
      hash = data['result']['hash']
    else:
      hash = data['outputs'][outpt.name]['hash']
    files.append(dict(
        hash=hash,
        size=float(outpt.data_sink.statistics()[0]),
        blocks=outpt.nb_data_blocks_written,
        ))

  return dict(
          volume = dict(read=bytes_read, write=bytes_written),
          blocks = dict(read=blocks_read, write=blocks_written),
          time = dict(read=read_time, write=write_time),
          files = files,
          )


269
def cpu_statistics(start, end):
André Anjos's avatar
André Anjos committed
270
271
272
273
274
275
276
277
278
279
280
281
  """Summarizes current CPU usage

  This method should be used when the currently set algorithm is the only one
  executed through the whole process. It is done for collecting resource
  statistics on separate processing environments.

  Returns:

    dict: A dictionary summarizing current CPU usage

  """

282
283
284
285
286
  if start is not None:
    user_cpu = end['cpu_usage']['total_usage'] - \
        start['cpu_usage']['total_usage']
    total_cpu = end['system_cpu_usage'] - start['system_cpu_usage']

André Anjos's avatar
André Anjos committed
287
  else:
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
    user_cpu = end['cpu_usage']['total_usage']
    total_cpu = end['system_cpu_usage']

  user_cpu /= 1000000000. #in seconds
  total_cpu /= 1000000000. #in seconds
  processors = len(end['cpu_usage']['percpu_usage']) if \
      end['cpu_usage']['percpu_usage'] is not None else 1

  return {
          'user': user_cpu,
          'system': 0.,
          'total': total_cpu,
          'percent': 100.*processors*user_cpu/total_cpu if total_cpu else 0.,
          'processors': processors,
         }
André Anjos's avatar
André Anjos committed
303
304


305
def memory_statistics(data):
André Anjos's avatar
André Anjos committed
306
307
308
309
310
311
312
313
314
315
316
317
  """Summarizes current memory usage

  This method should be used when the currently set algorithm is the only one
  executed through the whole process. It is done for collecting resource
  statistics on separate processing environments.

  Returns:

    dict: A dictionary summarizing current memory usage

  """

318
319
  limit = float(data['limit'])
  memory = float(data['max_usage'])
André Anjos's avatar
André Anjos committed
320

321
322
323
324
325
  return {
          'rss': memory,
          'limit': limit,
          'percent': 100.*memory/limit if limit else 0.,
         }