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")
324 def linear_search(self, start_rate, traffic_type):
325 """Linear search of rate with loss below acceptance criteria.
327 :param start_rate: Initial rate.
328 :param traffic_type: Traffic profile.
329 :type start_rate: float
330 :param traffic_type: str
334 if not self._rate_min <= float(start_rate) <= self._rate_max:
335 raise ValueError("Start rate is not in min,max range")
337 rate = float(start_rate)
338 # the last but one step
344 for dummy in range(self._max_attempts):
345 res.append(self.measure_loss(rate, self._frame_size,
346 self._loss_acceptance,
347 self._loss_acceptance_type,
350 res = self._get_res_based_on_search_type(res)
352 if self._search_linear_direction == SearchDirection.BOTTOM_UP:
353 # loss occured and it was above acceptance criteria
355 # if this is first run then we didn't find drop rate
356 if prev_rate is None:
357 self._search_result = SearchResults.FAILURE
358 self._search_result_rate = None
360 # else we found the rate, which is value from previous run
362 self._search_result = SearchResults.SUCCESS
363 self._search_result_rate = prev_rate
365 # there was no loss / loss below acceptance criteria
368 rate += self._rate_linear_step
369 if rate > self._rate_max:
370 if prev_rate != self._rate_max:
371 # one last step with rate set to _rate_max
372 rate = self._rate_max
375 self._search_result = SearchResults.SUCCESS
376 self._search_result_rate = prev_rate
381 raise RuntimeError("Unknown search result")
383 elif self._search_linear_direction == SearchDirection.TOP_DOWN:
384 # loss occured, decrease rate
387 rate -= self._rate_linear_step
388 if rate < self._rate_min:
389 if prev_rate != self._rate_min:
390 # one last step with rate set to _rate_min
391 rate = self._rate_min
394 self._search_result = SearchResults.FAILURE
395 self._search_result_rate = None
399 # no loss => non/partial drop rate found
401 self._search_result = SearchResults.SUCCESS
402 self._search_result_rate = rate
405 raise RuntimeError("Unknown search result")
407 raise Exception("Unknown search direction")
409 raise Exception("Wrong codepath")
411 def verify_search_result(self):
412 """Fail if search was not successful.
414 :return: Result rate.
417 if self._search_result == SearchResults.FAILURE:
418 raise Exception('Search FAILED')
419 elif self._search_result in [SearchResults.SUCCESS,
420 SearchResults.SUSPICIOUS]:
421 return self._search_result_rate
423 def binary_search(self, b_min, b_max, traffic_type):
424 """Binary search of rate with loss below acceptance criteria.
426 :param b_min: Min range rate.
427 :param b_max: Max range rate.
428 :param traffic_type: Traffic profile.
431 :type traffic_type: str
435 if not self._rate_min <= float(b_min) <= self._rate_max:
436 raise ValueError("Min rate is not in min,max range")
437 if not self._rate_min <= float(b_max) <= self._rate_max:
438 raise ValueError("Max rate is not in min,max range")
439 if float(b_max) < float(b_min):
440 raise ValueError("Min rate is greater then max rate")
443 # rate is half of interval + start of interval
444 rate = ((float(b_max) - float(b_min)) / 2) + float(b_min)
445 # rate diff with previous run
446 rate_diff = abs(self._last_binary_rate - rate)
448 # convergence criterium
449 if float(rate_diff) < float(self._binary_convergence_threshold):
450 if not self._search_result_rate:
451 self._search_result = SearchResults.FAILURE
453 self._search_result = SearchResults.SUCCESS
456 self._last_binary_rate = rate
459 for dummy in range(self._max_attempts):
460 res.append(self.measure_loss(rate, self._frame_size,
461 self._loss_acceptance,
462 self._loss_acceptance_type,
465 res = self._get_res_based_on_search_type(res)
467 # loss occured and it was above acceptance criteria
469 self.binary_search(b_min, rate, traffic_type)
470 # there was no loss / loss below acceptance criteria
472 self._search_result_rate = rate
473 self.binary_search(rate, b_max, traffic_type)
475 def combined_search(self, start_rate, traffic_type):
476 """Combined search of rate with loss below acceptance criteria.
478 :param start_rate: Initial rate.
479 :param traffic_type: Traffic profile.
480 :type start_rate: float
481 :type traffic_type: str
485 self.linear_search(start_rate, traffic_type)
487 if self._search_result in [SearchResults.SUCCESS,
488 SearchResults.SUSPICIOUS]:
489 b_min = self._search_result_rate
490 b_max = self._search_result_rate + self._rate_linear_step
492 # we found max rate by linear search
493 if self.floats_are_close_equal(float(b_min), self._rate_max):
496 # limiting binary range max value into max range
497 if float(b_max) > self._rate_max:
498 b_max = self._rate_max
501 temp_rate = self._search_result_rate
502 self._search_result_rate = None
504 # we will use binary search to refine search in one linear step
505 self.binary_search(b_min, b_max, traffic_type)
507 # linear and binary search succeed
508 if self._search_result == SearchResults.SUCCESS:
510 # linear search succeed but binary failed or suspicious
512 self._search_result = SearchResults.SUSPICIOUS
513 self._search_result_rate = temp_rate
515 raise RuntimeError("Linear search FAILED")
518 def floats_are_close_equal(num_a, num_b, rel_tol=1e-9, abs_tol=0.0):
519 """Compares two float numbers for close equality.
521 :param num_a: First number to compare.
522 :param num_b: Second number to compare.
523 :param rel_tol=1e-9: The relative tolerance.
524 :param abs_tol=0.0: The minimum absolute tolerance level.
529 :return: Returns True if num_a is close in value to num_b or equal.
537 if rel_tol < 0.0 or abs_tol < 0.0:
538 raise ValueError('Error tolerances must be non-negative')
540 return abs(num_b - num_a) <= max(rel_tol * max(abs(num_a), abs(num_b)),