Add support for Python 3
[yardstick.git] / yardstick / benchmark / scenarios / compute / memload.py
1 ##############################################################################
2 # Copyright (c) 2016 Huawei Technologies Co.,Ltd and others.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9
10 """Memory load and statistics."""
11
12 from __future__ import absolute_import
13 import logging
14 import yardstick.ssh as ssh
15
16 from yardstick.benchmark.scenarios import base
17 from six.moves import zip
18
19 LOG = logging.getLogger(__name__)
20
21
22 class MEMLoad(base.Scenario):
23     """Collect memory statistics and system load.
24
25     This scenario reads memory usage statistics on a Linux host.
26
27     memory usage statistics are read using the utility 'free'.
28
29     Parameters
30         interval - Time interval to measure memory usage.
31         Continuously display the result delay interval seconds apart.
32         type:       [int]
33         unit:       seconds
34         default:    1
35
36         count - specifies a # of measurments for each test
37         type:       [int]
38         unit:       N/A
39         default:    1
40     """
41     __scenario_type__ = "MEMORYload"
42
43     def __init__(self, scenario_cfg, context_cfg):
44         """Scenario construction."""
45         self.scenario_cfg = scenario_cfg
46         self.context_cfg = context_cfg
47         self.setup_done = False
48
49     def setup(self):
50         """Scenario setup."""
51         host = self.context_cfg['host']
52         user = host.get('user', 'ubuntu')
53         ssh_port = host.get("ssh_port", ssh.DEFAULT_PORT)
54         ip = host.get('ip', None)
55         key_filename = host.get('key_filename', '~/.ssh/id_rsa')
56
57         LOG.info("user:%s, host:%s", user, ip)
58         self.client = ssh.SSH(user, ip, key_filename=key_filename,
59                               port=ssh_port)
60         self.client.wait(timeout=600)
61
62         self.setup_done = True
63
64     def _execute_command(self, cmd):
65         """Execute a command on server."""
66         LOG.info("Executing: %s", cmd)
67         status, stdout, stderr = self.client.execute(cmd)
68         if status:
69             raise RuntimeError("Failed executing command: ",
70                                cmd, stderr)
71         return stdout
72
73     def _filtrate_result(self, result):
74         fields = []
75         free = {}
76         ite = 0
77         average = {'total': 0, 'used': 0, 'free': 0, 'cached': 0, 'shared': 0,
78                    'buffers': 0}
79         maximum = {'total': 0, 'used': 0, 'free': 0, 'cached': 0, 'shared': 0,
80                    'buffers': 0}
81
82         for row in result.split('\n'):
83             line = row.split()
84
85             if line and line[0] == 'total':
86                 # header fields
87                 fields = line[:]
88             elif line and line[0] == 'Mem:':
89                 memory = 'memory' + str(ite)
90                 ite += 1
91                 values = line[1:]
92                 if values and len(values) == len(fields):
93                     free[memory] = dict(list(zip(fields, values)))
94
95         for entry in free:
96             for item in average:
97                 average[item] += int(free[entry][item])
98
99             for item in maximum:
100                 if int(free[entry][item]) > maximum[item]:
101                     maximum[item] = int(free[entry][item])
102
103         for item in average:
104             average[item] = average[item] / len(free)
105
106         return {'free': free, 'average': average, 'max': maximum}
107
108     def _get_mem_usage(self):
109         """Get memory usage using free."""
110         options = self.scenario_cfg['options']
111         interval = options.get("interval", 1)
112         count = options.get("count", 1)
113
114         cmd = "free -s %s -c %s" % (interval, count)
115
116         result = self._execute_command(cmd)
117         filtrated_result = self._filtrate_result(result)
118
119         return filtrated_result
120
121     def run(self, result):
122         """Read processor statistics."""
123         if not self.setup_done:
124             self.setup()
125
126         result.update(self._get_mem_usage())