bafd8961763b40402dd68e74a95ccf31e8ae73ff
[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 import logging
13 import yardstick.ssh as ssh
14
15 from yardstick.benchmark.scenarios import base
16
17 LOG = logging.getLogger(__name__)
18
19
20 class MEMLoad(base.Scenario):
21     """Collect memory statistics and system load.
22
23     This scenario reads memory usage statistics on a Linux host.
24
25     memory usage statistics are read using the utility 'free'.
26
27     Parameters
28         interval - Time interval to measure memory usage.
29         Continuously display the result delay interval seconds apart.
30         type:       [int]
31         unit:       seconds
32         default:    1
33
34         count - specifies a # of measurments for each test
35         type:       [int]
36         unit:       N/A
37         default:    1
38     """
39     __scenario_type__ = "MEMORYload"
40
41     def __init__(self, scenario_cfg, context_cfg):
42         """Scenario construction."""
43         self.scenario_cfg = scenario_cfg
44         self.context_cfg = context_cfg
45         self.setup_done = False
46
47     def setup(self):
48         """Scenario setup."""
49         host = self.context_cfg['host']
50         user = host.get('user', 'ubuntu')
51         ip = host.get('ip', None)
52         key_filename = host.get('key_filename', '~/.ssh/id_rsa')
53
54         LOG.info("user:%s, host:%s", user, ip)
55         self.client = ssh.SSH(user, ip, key_filename=key_filename)
56         self.client.wait(timeout=600)
57
58         self.setup_done = True
59
60     def _execute_command(self, cmd):
61         """Execute a command on server."""
62         LOG.info("Executing: %s" % cmd)
63         status, stdout, stderr = self.client.execute(cmd)
64         if status:
65             raise RuntimeError("Failed executing command: ",
66                                cmd, stderr)
67         return stdout
68
69     def _filtrate_result(self, result):
70         fields = []
71         free = {}
72         ite = 0
73         average = {'total': 0, 'used': 0, 'free': 0, 'cached': 0, 'shared': 0,
74                    'buffers': 0}
75         maximum = {'total': 0, 'used': 0, 'free': 0, 'cached': 0, 'shared': 0,
76                    'buffers': 0}
77
78         for row in result.split('\n'):
79             line = row.split()
80
81             if line and line[0] == 'total':
82                 # header fields
83                 fields = line[:]
84             elif line and line[0] == 'Mem:':
85                 memory = 'memory' + str(ite)
86                 ite += 1
87                 values = line[1:]
88                 if values and len(values) == len(fields):
89                     free[memory] = dict(zip(fields, values))
90
91         for entry in free:
92             for item in average:
93                 average[item] += int(free[entry][item])
94
95             for item in maximum:
96                 if int(free[entry][item]) > maximum[item]:
97                     maximum[item] = int(free[entry][item])
98
99         for item in average:
100             average[item] = average[item] / len(free)
101
102         return {'free': free, 'average': average, 'max': maximum}
103
104     def _get_mem_usage(self):
105         """Get memory usage using free."""
106         options = self.scenario_cfg['options']
107         interval = options.get("interval", 1)
108         count = options.get("count", 1)
109
110         cmd = "free -s %s -c %s" % (interval, count)
111
112         result = self._execute_command(cmd)
113         filtrated_result = self._filtrate_result(result)
114
115         return filtrated_result
116
117     def run(self, result):
118         """Read processor statistics."""
119         if not self.setup_done:
120             self.setup()
121
122         result.update(self._get_mem_usage())