Merge "contexts/node: default to pod.yaml"
[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         ssh_port = host.get("ssh_port", ssh.DEFAULT_PORT)
52         ip = host.get('ip', None)
53         key_filename = host.get('key_filename', '~/.ssh/id_rsa')
54
55         LOG.info("user:%s, host:%s", user, ip)
56         self.client = ssh.SSH(user, ip, key_filename=key_filename,
57                               port=ssh_port)
58         self.client.wait(timeout=600)
59
60         self.setup_done = True
61
62     def _execute_command(self, cmd):
63         """Execute a command on server."""
64         LOG.info("Executing: %s" % cmd)
65         status, stdout, stderr = self.client.execute(cmd)
66         if status:
67             raise RuntimeError("Failed executing command: ",
68                                cmd, stderr)
69         return stdout
70
71     def _filtrate_result(self, result):
72         fields = []
73         free = {}
74         ite = 0
75         average = {'total': 0, 'used': 0, 'free': 0, 'cached': 0, 'shared': 0,
76                    'buffers': 0}
77         maximum = {'total': 0, 'used': 0, 'free': 0, 'cached': 0, 'shared': 0,
78                    'buffers': 0}
79
80         for row in result.split('\n'):
81             line = row.split()
82
83             if line and line[0] == 'total':
84                 # header fields
85                 fields = line[:]
86             elif line and line[0] == 'Mem:':
87                 memory = 'memory' + str(ite)
88                 ite += 1
89                 values = line[1:]
90                 if values and len(values) == len(fields):
91                     free[memory] = dict(zip(fields, values))
92
93         for entry in free:
94             for item in average:
95                 average[item] += int(free[entry][item])
96
97             for item in maximum:
98                 if int(free[entry][item]) > maximum[item]:
99                     maximum[item] = int(free[entry][item])
100
101         for item in average:
102             average[item] = average[item] / len(free)
103
104         return {'free': free, 'average': average, 'max': maximum}
105
106     def _get_mem_usage(self):
107         """Get memory usage using free."""
108         options = self.scenario_cfg['options']
109         interval = options.get("interval", 1)
110         count = options.get("count", 1)
111
112         cmd = "free -s %s -c %s" % (interval, count)
113
114         result = self._execute_command(cmd)
115         filtrated_result = self._filtrate_result(result)
116
117         return filtrated_result
118
119     def run(self, result):
120         """Read processor statistics."""
121         if not self.setup_done:
122             self.setup()
123
124         result.update(self._get_mem_usage())