1 # Copyright (c) 2016 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
6 # http://www.apache.org/licenses/LICENSE-2.0
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
14 """Drop rate search algorithms"""
16 from abc import ABCMeta, abstractmethod
17 from enum import Enum, unique
21 class SearchDirection(Enum):
22 """Direction of linear search."""
29 class SearchResults(Enum):
30 """Result of the drop rate search."""
39 """Type of rate units."""
42 PACKETS_PER_SECOND = 2
47 class LossAcceptanceType(Enum):
48 """Type of the loss acceptance criteria."""
55 class SearchResultType(Enum):
56 """Type of search result evaluation."""
62 class DropRateSearch(object):
63 """Abstract class with search algorithm implementation."""
65 __metaclass__ = ABCMeta
68 # duration of traffic run (binary, linear)
70 # initial start rate (binary, linear)
71 self._rate_start = 100
72 # step of the linear search, unit: RateType (self._rate_type)
73 self._rate_linear_step = 10
74 # last rate of the binary search, unit: RateType (self._rate_type)
75 self._last_binary_rate = 0
76 # linear search direction, permitted values: SearchDirection
77 self._search_linear_direction = SearchDirection.TOP_DOWN
78 # upper limit of search, unit: RateType (self._rate_type)
80 # lower limit of search, unit: RateType (self._rate_type)
82 # permitted values: RateType
83 self._rate_type = RateType.PERCENTAGE
84 # accepted loss during search, units: LossAcceptanceType
85 self._loss_acceptance = 0
86 # permitted values: LossAcceptanceType
87 self._loss_acceptance_type = LossAcceptanceType.FRAMES
88 # size of frames to send
89 self._frame_size = "64"
90 # binary convergence criterium type is self._rate_type
91 self._binary_convergence_threshold = 5000
92 # numbers of traffic runs during one rate step
93 self._max_attempts = 1
94 # type of search result evaluation, unit: SearchResultType
95 self._search_result_type = SearchResultType.BEST_OF_N
98 self._search_result = None
99 self._search_result_rate = None
102 def measure_loss(self, rate, frame_size, loss_acceptance,
103 loss_acceptance_type, traffic_type):
104 """Send traffic from TG and measure count of dropped frames.
106 :param rate: Offered traffic load.
107 :param frame_size: Size of frame.
108 :param loss_acceptance: Permitted drop ratio or frames count.
109 :param loss_acceptance_type: Type of permitted loss.
110 :param traffic_type: Traffic profile ([2,3]-node-L[2,3], ...).
112 :type frame_size: str
113 :type loss_acceptance: float
114 :type loss_acceptance_type: LossAcceptanceType
115 :type traffic_type: str
116 :return: Drop threshold exceeded? (True/False)
121 def set_search_rate_boundaries(self, max_rate, min_rate):
122 """Set search boundaries: min,max.
124 :param max_rate: Upper value of search boundaries.
125 :param min_rate: Lower value of search boundaries.
126 :type max_rate: float
127 :type min_rate: float
130 if float(min_rate) <= 0:
131 raise ValueError("min_rate must be higher than 0")
132 elif float(min_rate) > float(max_rate):
133 raise ValueError("min_rate must be lower than max_rate")
135 self._rate_max = float(max_rate)
136 self._rate_min = float(min_rate)
138 def set_search_linear_step(self, step_rate):
139 """Set step size for linear search.
141 :param step_rate: Linear search step size.
142 :type step_rate: float
145 self._rate_linear_step = float(step_rate)
147 def set_search_rate_type_percentage(self):
148 """Set rate type to percentage of linerate.
152 self._set_search_rate_type(RateType.PERCENTAGE)
154 def set_search_rate_type_bps(self):
155 """Set rate type to bits per second.
159 self._set_search_rate_type(RateType.BITS_PER_SECOND)
161 def set_search_rate_type_pps(self):
162 """Set rate type to packets per second.
166 self._set_search_rate_type(RateType.PACKETS_PER_SECOND)
168 def _set_search_rate_type(self, rate_type):
169 """Set rate type to one of RateType-s.
171 :param rate_type: Type of rate to set.
172 :type rate_type: RateType
175 if rate_type not in RateType:
176 raise Exception("rate_type unknown: {}".format(rate_type))
178 self._rate_type = rate_type
180 def set_search_frame_size(self, frame_size):
181 """Set size of frames to send.
183 :param frame_size: Size of frames.
184 :type frame_size: str
187 self._frame_size = frame_size
189 def set_duration(self, duration):
190 """Set the duration of single traffic run.
192 :param duration: Number of seconds for traffic to run.
196 self._duration = int(duration)
198 def get_duration(self):
199 """Return configured duration of single traffic run.
201 :return: Number of seconds for traffic to run.
204 return self._duration
206 def set_binary_convergence_threshold(self, convergence):
207 """Set convergence for binary search.
209 :param convergence: Treshold value number.
210 :type convergence: float
213 self._binary_convergence_threshold = float(convergence)
215 def get_binary_convergence_threshold(self):
216 """Get convergence for binary search.
218 :return: Treshold value number.
221 return self._binary_convergence_threshold
223 def get_rate_type_str(self):
224 """Return rate type representation.
226 :return: String representation of rate type.
229 if self._rate_type == RateType.PERCENTAGE:
231 elif self._rate_type == RateType.BITS_PER_SECOND:
233 elif self._rate_type == RateType.PACKETS_PER_SECOND:
236 raise ValueError("RateType unknown")
238 def set_max_attempts(self, max_attempts):
239 """Set maximum number of traffic runs during one rate step.
241 :param max_attempts: Number of traffic runs.
242 :type max_attempts: int
245 if int(max_attempts) > 0:
246 self._max_attempts = int(max_attempts)
248 raise ValueError("Max attempt must by greater then zero")
250 def get_max_attempts(self):
251 """Return maximum number of traffic runs during one rate step.
253 :return: Number of traffic runs.
256 return self._max_attempts
258 def set_search_result_type_best_of_n(self):
259 """Set type of search result evaluation to Best of N.
263 self._set_search_result_type(SearchResultType.BEST_OF_N)
265 def set_search_result_type_worst_of_n(self):
266 """Set type of search result evaluation to Worst of N.
270 self._set_search_result_type(SearchResultType.WORST_OF_N)
272 def _set_search_result_type(self, search_type):
273 """Set type of search result evaluation to one of SearchResultType.
275 :param search_type: Type of search result evaluation to set.
276 :type search_type: SearchResultType
279 if search_type not in SearchResultType:
280 raise ValueError("search_type unknown: {}".format(search_type))
282 self._search_result_type = search_type
285 def _get_best_of_n(res_list):
286 """Return best result of N traffic runs.
288 :param res_list: List of return values from all runs at one rate step.
290 :return: True if at least one run is True, False otherwise.
293 # Return True if any element of the iterable is True.
297 def _get_worst_of_n(res_list):
298 """Return worst result of N traffic runs.
300 :param res_list: List of return values from all runs at one rate step.
302 :return: False if at least one run is False, True otherwise.
305 # Return False if not all elements of the iterable are True.
306 return not all(res_list)
308 def _get_res_based_on_search_type(self, res_list):
309 """Return result of search based on search evaluation type.
311 :param res_list: List of return values from all runs at one rate step.
313 :return: Boolean based on search result type.
316 if self._search_result_type == SearchResultType.BEST_OF_N:
317 return self._get_best_of_n(res_list)
318 elif self._search_result_type == SearchResultType.WORST_OF_N:
319 return self._get_worst_of_n(res_list)
321 raise ValueError("Unknown search result type")
323 def linear_search(self, start_rate, traffic_type):
324 """Linear search of rate with loss below acceptance criteria.
326 :param start_rate: Initial rate.
327 :param traffic_type: Traffic profile.
328 :type start_rate: float
329 :type traffic_type: str
333 if not self._rate_min <= float(start_rate) <= self._rate_max:
334 raise ValueError("Start rate is not in min,max range")
336 rate = float(start_rate)
337 # the last but one step
343 for dummy in range(self._max_attempts):
344 res.append(self.measure_loss(rate, self._frame_size,
345 self._loss_acceptance,
346 self._loss_acceptance_type,
349 res = self._get_res_based_on_search_type(res)
351 if self._search_linear_direction == SearchDirection.BOTTOM_UP:
352 # loss occurred and it was above acceptance criteria
354 # if this is first run then we didn't find drop rate
355 if prev_rate is None:
356 self._search_result = SearchResults.FAILURE
357 self._search_result_rate = None
359 # else we found the rate, which is value from previous run
361 self._search_result = SearchResults.SUCCESS
362 self._search_result_rate = prev_rate
364 # there was no loss / loss below acceptance criteria
367 rate += self._rate_linear_step
368 if rate > self._rate_max:
369 if prev_rate != self._rate_max:
370 # one last step with rate set to _rate_max
371 rate = self._rate_max
374 self._search_result = SearchResults.SUCCESS
375 self._search_result_rate = prev_rate
380 raise RuntimeError("Unknown search result")
382 elif self._search_linear_direction == SearchDirection.TOP_DOWN:
383 # loss occurred, decrease rate
386 rate -= self._rate_linear_step
387 if rate < self._rate_min:
388 if prev_rate != self._rate_min:
389 # one last step with rate set to _rate_min
390 rate = self._rate_min
393 self._search_result = SearchResults.FAILURE
394 self._search_result_rate = None
398 # no loss => non/partial drop rate found
400 self._search_result = SearchResults.SUCCESS
401 self._search_result_rate = rate
404 raise RuntimeError("Unknown search result")
406 raise Exception("Unknown search direction")
408 raise Exception("Wrong codepath")
410 def verify_search_result(self):
411 """Fail if search was not successful.
413 :return: Result rate.
416 if self._search_result == SearchResults.FAILURE:
417 raise Exception('Search FAILED')
418 elif self._search_result in [SearchResults.SUCCESS,
419 SearchResults.SUSPICIOUS]:
420 return self._search_result_rate
422 def binary_search(self, b_min, b_max, traffic_type):
423 """Binary search of rate with loss below acceptance criteria.
425 :param b_min: Min range rate.
426 :param b_max: Max range rate.
427 :param traffic_type: Traffic profile.
430 :type traffic_type: str
434 if not self._rate_min <= float(b_min) <= self._rate_max:
435 raise ValueError("Min rate is not in min,max range")
436 if not self._rate_min <= float(b_max) <= self._rate_max:
437 raise ValueError("Max rate is not in min,max range")
438 if float(b_max) < float(b_min):
439 raise ValueError("Min rate is greater then max rate")
442 # rate is half of interval + start of interval
443 rate = ((float(b_max) - float(b_min)) / 2) + float(b_min)
444 # rate diff with previous run
445 rate_diff = abs(self._last_binary_rate - rate)
447 # convergence criterium
448 if float(rate_diff) < float(self._binary_convergence_threshold):
449 if not self._search_result_rate:
450 self._search_result = SearchResults.FAILURE
452 self._search_result = SearchResults.SUCCESS
455 self._last_binary_rate = rate
458 for dummy in range(self._max_attempts):
459 res.append(self.measure_loss(rate, self._frame_size,
460 self._loss_acceptance,
461 self._loss_acceptance_type,
464 res = self._get_res_based_on_search_type(res)
466 # loss occurred and it was above acceptance criteria
468 self.binary_search(b_min, rate, traffic_type)
469 # there was no loss / loss below acceptance criteria
471 self._search_result_rate = rate
472 self.binary_search(rate, b_max, traffic_type)
474 def combined_search(self, start_rate, traffic_type):
475 """Combined search of rate with loss below acceptance criteria.
477 :param start_rate: Initial rate.
478 :param traffic_type: Traffic profile.
479 :type start_rate: float
480 :type traffic_type: str
484 self.linear_search(start_rate, traffic_type)
486 if self._search_result in [SearchResults.SUCCESS,
487 SearchResults.SUSPICIOUS]:
488 b_min = self._search_result_rate
489 b_max = self._search_result_rate + self._rate_linear_step
491 # we found max rate by linear search
492 if self.floats_are_close_equal(float(b_min), self._rate_max):
495 # limiting binary range max value into max range
496 if float(b_max) > self._rate_max:
497 b_max = self._rate_max
500 temp_rate = self._search_result_rate
501 self._search_result_rate = None
503 # we will use binary search to refine search in one linear step
504 self.binary_search(b_min, b_max, traffic_type)
506 # linear and binary search succeed
507 if self._search_result == SearchResults.SUCCESS:
509 # linear search succeed but binary failed or suspicious
511 self._search_result = SearchResults.SUSPICIOUS
512 self._search_result_rate = temp_rate
514 raise RuntimeError("Linear search FAILED")
517 def floats_are_close_equal(num_a, num_b, rel_tol=1e-9, abs_tol=0.0):
518 """Compares two float numbers for close equality.
520 :param num_a: First number to compare.
521 :param num_b: Second number to compare.
522 :param rel_tol=1e-9: The relative tolerance.
523 :param abs_tol=0.0: The minimum absolute tolerance level.
528 :return: Returns True if num_a is close in value to num_b or equal.
536 if rel_tol < 0.0 or abs_tol < 0.0:
537 raise ValueError('Error tolerances must be non-negative')
539 return abs(num_b - num_a) <= max(rel_tol * max(abs(num_a), abs(num_b)),