summaryrefslogtreecommitdiff
path: root/swift/cli/ring_builder_analyzer.py
blob: c38564338989436c89ec885f00ba5ccf2115c0e4 (plain)
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# Copyright (c) 2015 Samuel Merritt <sam@swiftstack.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
This is a tool for analyzing how well the ring builder performs its job
in a particular scenario. It is intended to help developers quantify any
improvements or regressions in the ring builder; it is probably not useful
to others.

The ring builder analyzer takes a scenario file containing some initial
parameters for a ring builder plus a certain number of rounds. In each
round, some modifications are made to the builder, e.g. add a device, remove
a device, change a device's weight. Then, the builder is repeatedly
rebalanced until it settles down. Data about that round is printed, and the
next round begins.

Scenarios are specified in JSON. Example scenario for a gradual device
addition::

    {
        "part_power": 12,
        "replicas": 3,
        "overload": 0.1,
        "random_seed": 203488,

        "rounds": [
            [
                ["add", "r1z2-10.20.30.40:6200/sda", 8000],
                ["add", "r1z2-10.20.30.40:6200/sdb", 8000],
                ["add", "r1z2-10.20.30.40:6200/sdc", 8000],
                ["add", "r1z2-10.20.30.40:6200/sdd", 8000],

                ["add", "r1z2-10.20.30.41:6200/sda", 8000],
                ["add", "r1z2-10.20.30.41:6200/sdb", 8000],
                ["add", "r1z2-10.20.30.41:6200/sdc", 8000],
                ["add", "r1z2-10.20.30.41:6200/sdd", 8000],

                ["add", "r1z2-10.20.30.43:6200/sda", 8000],
                ["add", "r1z2-10.20.30.43:6200/sdb", 8000],
                ["add", "r1z2-10.20.30.43:6200/sdc", 8000],
                ["add", "r1z2-10.20.30.43:6200/sdd", 8000],

                ["add", "r1z2-10.20.30.44:6200/sda", 8000],
                ["add", "r1z2-10.20.30.44:6200/sdb", 8000],
                ["add", "r1z2-10.20.30.44:6200/sdc", 8000]
            ], [
                ["add", "r1z2-10.20.30.44:6200/sdd", 1000]
            ], [
                ["set_weight", 15, 2000]
            ], [
                ["remove", 3],
                ["set_weight", 15, 3000]
            ], [
                ["set_weight", 15, 4000]
            ], [
                ["set_weight", 15, 5000]
            ], [
                ["set_weight", 15, 6000]
            ], [
                ["set_weight", 15, 7000]
            ], [
                ["set_weight", 15, 8000]
            ]]
    }

"""

import argparse
import json
import sys

from swift.common.ring import builder
from swift.common.ring.utils import parse_add_value


ARG_PARSER = argparse.ArgumentParser(
    description='Put the ring builder through its paces')
ARG_PARSER.add_argument(
    '--check', '-c', action='store_true',
    help="Just check the scenario, don't execute it.")
ARG_PARSER.add_argument(
    'scenario_path',
    help="Path to the scenario file")


class ParseCommandError(ValueError):

    def __init__(self, name, round_index, command_index, msg):
        msg = "Invalid %s (round %s, command %s): %s" % (
            name, round_index, command_index, msg)
        super(ParseCommandError, self).__init__(msg)


def _parse_weight(round_index, command_index, weight_str):
    try:
        weight = float(weight_str)
    except ValueError as err:
        raise ParseCommandError('weight', round_index, command_index, err)
    if weight < 0:
        raise ParseCommandError('weight', round_index, command_index,
                                'cannot be negative')
    return weight


def _parse_add_command(round_index, command_index, command):
    if len(command) != 3:
        raise ParseCommandError(
            'add command', round_index, command_index,
            'expected array of length 3, but got %r' % command)

    dev_str = command[1]
    weight_str = command[2]

    try:
        dev = parse_add_value(dev_str)
    except ValueError as err:
        raise ParseCommandError('device specifier', round_index,
                                command_index, err)

    dev['weight'] = _parse_weight(round_index, command_index, weight_str)

    if dev['region'] is None:
        dev['region'] = 1

    default_key_map = {
        'replication_ip': 'ip',
        'replication_port': 'port',
    }
    for empty_key, default_key in default_key_map.items():
        if dev[empty_key] is None:
            dev[empty_key] = dev[default_key]

    return ['add', dev]


def _parse_remove_command(round_index, command_index, command):
    if len(command) != 2:
        raise ParseCommandError('remove commnd', round_index, command_index,
                                "expected array of length 2, but got %r" %
                                (command,))

    dev_str = command[1]

    try:
        dev_id = int(dev_str)
    except ValueError as err:
        raise ParseCommandError('device ID in remove',
                                round_index, command_index, err)

    return ['remove', dev_id]


def _parse_set_weight_command(round_index, command_index, command):
    if len(command) != 3:
        raise ParseCommandError('remove command', round_index, command_index,
                                "expected array of length 3, but got %r" %
                                (command,))

    dev_str = command[1]
    weight_str = command[2]

    try:
        dev_id = int(dev_str)
    except ValueError as err:
        raise ParseCommandError('device ID in set_weight',
                                round_index, command_index, err)

    weight = _parse_weight(round_index, command_index, weight_str)
    return ['set_weight', dev_id, weight]


def _parse_save_command(round_index, command_index, command):
    if len(command) != 2:
        raise ParseCommandError(
            command, round_index, command_index,
            "expected array of length 2 but got %r" % (command,))
    return ['save', command[1]]


def parse_scenario(scenario_data):
    """
    Takes a serialized scenario and turns it into a data structure suitable
    for feeding to run_scenario().

    :returns: scenario
    :raises ValueError: on invalid scenario
    """

    parsed_scenario = {}

    try:
        raw_scenario = json.loads(scenario_data)
    except ValueError as err:
        raise ValueError("Invalid JSON in scenario file: %s" % err)

    if not isinstance(raw_scenario, dict):
        raise ValueError("Scenario must be a JSON object, not array or string")

    if 'part_power' not in raw_scenario:
        raise ValueError("part_power missing")
    try:
        parsed_scenario['part_power'] = int(raw_scenario['part_power'])
    except ValueError as err:
        raise ValueError("part_power not an integer: %s" % err)
    if not 1 <= parsed_scenario['part_power'] <= 32:
        raise ValueError("part_power must be between 1 and 32, but was %d"
                         % raw_scenario['part_power'])

    if 'replicas' not in raw_scenario:
        raise ValueError("replicas missing")
    try:
        parsed_scenario['replicas'] = float(raw_scenario['replicas'])
    except ValueError as err:
        raise ValueError("replicas not a float: %s" % err)
    if parsed_scenario['replicas'] < 1:
        raise ValueError("replicas must be at least 1, but is %f"
                         % parsed_scenario['replicas'])

    if 'overload' not in raw_scenario:
        raise ValueError("overload missing")
    try:
        parsed_scenario['overload'] = float(raw_scenario['overload'])
    except ValueError as err:
        raise ValueError("overload not a float: %s" % err)
    if parsed_scenario['overload'] < 0:
        raise ValueError("overload must be non-negative, but is %f"
                         % parsed_scenario['overload'])

    if 'random_seed' not in raw_scenario:
        raise ValueError("random_seed missing")
    try:
        parsed_scenario['random_seed'] = int(raw_scenario['random_seed'])
    except ValueError as err:
        raise ValueError("replicas not an integer: %s" % err)

    if 'rounds' not in raw_scenario:
        raise ValueError("rounds missing")
    if not isinstance(raw_scenario['rounds'], list):
        raise ValueError("rounds must be an array")

    parser_for_command = {
        'add': _parse_add_command,
        'remove': _parse_remove_command,
        'set_weight': _parse_set_weight_command,
        'save': _parse_save_command,
    }

    parsed_scenario['rounds'] = []
    for round_index, raw_round in enumerate(raw_scenario['rounds']):
        if not isinstance(raw_round, list):
            raise ValueError("round %d not an array" % round_index)

        parsed_round = []
        for command_index, command in enumerate(raw_round):
            if command[0] not in parser_for_command:
                raise ValueError(
                    "Unknown command (round %d, command %d): "
                    "'%s' should be one of %s" %
                    (round_index, command_index, command[0],
                     parser_for_command.keys()))
            parsed_round.append(
                parser_for_command[command[0]](
                    round_index, command_index, command))
        parsed_scenario['rounds'].append(parsed_round)
    return parsed_scenario


def run_scenario(scenario):
    """
    Takes a parsed scenario (like from parse_scenario()) and runs it.
    """
    seed = scenario['random_seed']

    rb = builder.RingBuilder(scenario['part_power'], scenario['replicas'], 1)
    rb.set_overload(scenario['overload'])

    command_map = {
        'add': rb.add_dev,
        'remove': rb.remove_dev,
        'set_weight': rb.set_dev_weight,
        'save': rb.save,
    }

    for round_index, commands in enumerate(scenario['rounds']):
        print("Round %d" % (round_index + 1))

        for command in commands:
            key = command.pop(0)
            try:
                command_f = command_map[key]
            except KeyError:
                raise ValueError("unknown command %r" % key)
            command_f(*command)

        rebalance_number = 1
        parts_moved, old_balance, removed_devs = rb.rebalance(seed=seed)
        rb.pretend_min_part_hours_passed()
        print("\tRebalance 1: moved %d parts, balance is %.6f, %d removed "
              "devs" % (parts_moved, old_balance, removed_devs))

        while True:
            rebalance_number += 1
            parts_moved, new_balance, removed_devs = rb.rebalance(seed=seed)
            rb.pretend_min_part_hours_passed()
            print("\tRebalance %d: moved %d parts, balance is %.6f, "
                  "%d removed devs" % (rebalance_number, parts_moved,
                                       new_balance, removed_devs))
            if parts_moved == 0 and removed_devs == 0:
                break
            if abs(new_balance - old_balance) < 1 and not (
                    old_balance == builder.MAX_BALANCE and
                    new_balance == builder.MAX_BALANCE):
                break
            old_balance = new_balance


def main(argv=None):
    args = ARG_PARSER.parse_args(argv)

    try:
        with open(args.scenario_path) as sfh:
            scenario_data = sfh.read()
    except OSError as err:
        sys.stderr.write("Error opening scenario %s: %s\n" %
                         (args.scenario_path, err))
        return 1

    try:
        scenario = parse_scenario(scenario_data)
    except ValueError as err:
        sys.stderr.write("Invalid scenario %s: %s\n" %
                         (args.scenario_path, err))
        return 1

    if not args.check:
        run_scenario(scenario)
    return 0