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 get_latency(self):
103 """Return min/avg/max latency.
105 :return: Latency stats.
111 def measure_loss(self, rate, frame_size, loss_acceptance,
112 loss_acceptance_type, traffic_type):
113 """Send traffic from TG and measure count of dropped frames.
115 :param rate: Offered traffic load.
116 :param frame_size: Size of frame.
117 :param loss_acceptance: Permitted drop ratio or frames count.
118 :param loss_acceptance_type: Type of permitted loss.
119 :param traffic_type: Traffic profile ([2,3]-node-L[2,3], ...).
121 :type frame_size: str
122 :type loss_acceptance: float
123 :type loss_acceptance_type: LossAcceptanceType
124 :type traffic_type: str
125 :return: Drop threshold exceeded? (True/False)
130 def set_search_rate_boundaries(self, max_rate, min_rate):
131 """Set search boundaries: min,max.
133 :param max_rate: Upper value of search boundaries.
134 :param min_rate: Lower value of search boundaries.
135 :type max_rate: float
136 :type min_rate: float
139 if float(min_rate) <= 0:
140 raise ValueError("min_rate must be higher than 0")
141 elif float(min_rate) > float(max_rate):
142 raise ValueError("min_rate must be lower than max_rate")
144 self._rate_max = float(max_rate)
145 self._rate_min = float(min_rate)
147 def set_loss_acceptance(self, loss_acceptance):
148 """Set loss acceptance treshold for PDR search.
150 :param loss_acceptance: Loss acceptance treshold for PDR search.
151 :type loss_acceptance: str
154 if float(loss_acceptance) < 0:
155 raise ValueError("Loss acceptance must be higher or equal 0")
157 self._loss_acceptance = float(loss_acceptance)
159 def get_loss_acceptance(self):
160 """Return configured loss acceptance treshold.
162 :return: Loss acceptance treshold.
165 return self._loss_acceptance
167 def set_loss_acceptance_type_percentage(self):
168 """Set loss acceptance treshold type to percentage.
172 self._loss_acceptance_type = LossAcceptanceType.PERCENTAGE
174 def set_loss_acceptance_type_frames(self):
175 """Set loss acceptance treshold type to frames.
179 self._loss_acceptance_type = LossAcceptanceType.FRAMES
181 def loss_acceptance_type_is_percentage(self):
182 """Return true if loss acceptance treshold type is percentage,
185 :return: True if loss acceptance treshold type is percentage.
188 return self._loss_acceptance_type == LossAcceptanceType.PERCENTAGE
190 def set_search_linear_step(self, step_rate):
191 """Set step size for linear search.
193 :param step_rate: Linear search step size.
194 :type step_rate: float
197 self._rate_linear_step = float(step_rate)
199 def set_search_rate_type_percentage(self):
200 """Set rate type to percentage of linerate.
204 self._set_search_rate_type(RateType.PERCENTAGE)
206 def set_search_rate_type_bps(self):
207 """Set rate type to bits per second.
211 self._set_search_rate_type(RateType.BITS_PER_SECOND)
213 def set_search_rate_type_pps(self):
214 """Set rate type to packets per second.
218 self._set_search_rate_type(RateType.PACKETS_PER_SECOND)
220 def _set_search_rate_type(self, rate_type):
221 """Set rate type to one of RateType-s.
223 :param rate_type: Type of rate to set.
224 :type rate_type: RateType
227 if rate_type not in RateType:
228 raise Exception("rate_type unknown: {}".format(rate_type))
230 self._rate_type = rate_type
232 def set_search_frame_size(self, frame_size):
233 """Set size of frames to send.
235 :param frame_size: Size of frames.
236 :type frame_size: str
239 self._frame_size = frame_size
241 def set_duration(self, duration):
242 """Set the duration of single traffic run.
244 :param duration: Number of seconds for traffic to run.
248 self._duration = int(duration)
250 def get_duration(self):
251 """Return configured duration of single traffic run.
253 :return: Number of seconds for traffic to run.
256 return self._duration
258 def set_binary_convergence_threshold(self, convergence):
259 """Set convergence for binary search.
261 :param convergence: Treshold value number.
262 :type convergence: float
265 self._binary_convergence_threshold = float(convergence)
267 def get_binary_convergence_threshold(self):
268 """Get convergence for binary search.
270 :return: Treshold value number.
273 return self._binary_convergence_threshold
275 def get_rate_type_str(self):
276 """Return rate type representation.
278 :return: String representation of rate type.
281 if self._rate_type == RateType.PERCENTAGE:
283 elif self._rate_type == RateType.BITS_PER_SECOND:
285 elif self._rate_type == RateType.PACKETS_PER_SECOND:
288 raise ValueError("RateType unknown")
290 def set_max_attempts(self, max_attempts):
291 """Set maximum number of traffic runs during one rate step.
293 :param max_attempts: Number of traffic runs.
294 :type max_attempts: int
297 if int(max_attempts) > 0:
298 self._max_attempts = int(max_attempts)
300 raise ValueError("Max attempt must by greater then zero")
302 def get_max_attempts(self):
303 """Return maximum number of traffic runs during one rate step.
305 :return: Number of traffic runs.
308 return self._max_attempts
310 def set_search_result_type_best_of_n(self):
311 """Set type of search result evaluation to Best of N.
315 self._set_search_result_type(SearchResultType.BEST_OF_N)
317 def set_search_result_type_worst_of_n(self):
318 """Set type of search result evaluation to Worst of N.
322 self._set_search_result_type(SearchResultType.WORST_OF_N)
324 def _set_search_result_type(self, search_type):
325 """Set type of search result evaluation to one of SearchResultType.
327 :param search_type: Type of search result evaluation to set.
328 :type search_type: SearchResultType
331 if search_type not in SearchResultType:
332 raise ValueError("search_type unknown: {}".format(search_type))
334 self._search_result_type = search_type
337 def _get_best_of_n(res_list):
338 """Return best result of N traffic runs.
340 :param res_list: List of return values from all runs at one rate step.
342 :return: True if at least one run is True, False otherwise.
345 # Return True if any element of the iterable is True.
349 def _get_worst_of_n(res_list):
350 """Return worst result of N traffic runs.
352 :param res_list: List of return values from all runs at one rate step.
354 :return: False if at least one run is False, True otherwise.
357 # Return False if not all elements of the iterable are True.
358 return not all(res_list)
360 def _get_res_based_on_search_type(self, res_list):
361 """Return result of search based on search evaluation type.
363 :param res_list: List of return values from all runs at one rate step.
365 :return: Boolean based on search result type.
368 if self._search_result_type == SearchResultType.BEST_OF_N:
369 return self._get_best_of_n(res_list)
370 elif self._search_result_type == SearchResultType.WORST_OF_N:
371 return self._get_worst_of_n(res_list)
373 raise ValueError("Unknown search result type")
375 def linear_search(self, start_rate, traffic_type):
376 """Linear search of rate with loss below acceptance criteria.
378 :param start_rate: Initial rate.
379 :param traffic_type: Traffic profile.
380 :type start_rate: float
381 :type traffic_type: str
385 if not self._rate_min <= float(start_rate) <= self._rate_max:
386 raise ValueError("Start rate is not in min,max range")
388 rate = float(start_rate)
389 # the last but one step
395 for dummy in range(self._max_attempts):
396 res.append(self.measure_loss(rate, self._frame_size,
397 self._loss_acceptance,
398 self._loss_acceptance_type,
401 res = self._get_res_based_on_search_type(res)
403 if self._search_linear_direction == SearchDirection.BOTTOM_UP:
404 # loss occurred and it was above acceptance criteria
406 # if this is first run then we didn't find drop rate
407 if prev_rate is None:
408 self._search_result = SearchResults.FAILURE
409 self._search_result_rate = None
411 # else we found the rate, which is value from previous run
413 self._search_result = SearchResults.SUCCESS
414 self._search_result_rate = prev_rate
416 # there was no loss / loss below acceptance criteria
419 rate += self._rate_linear_step
420 if rate > self._rate_max:
421 if prev_rate != self._rate_max:
422 # one last step with rate set to _rate_max
423 rate = self._rate_max
426 self._search_result = SearchResults.SUCCESS
427 self._search_result_rate = prev_rate
432 raise RuntimeError("Unknown search result")
434 elif self._search_linear_direction == SearchDirection.TOP_DOWN:
435 # loss occurred, decrease rate
438 rate -= self._rate_linear_step
439 if rate < self._rate_min:
440 if prev_rate != self._rate_min:
441 # one last step with rate set to _rate_min
442 rate = self._rate_min
445 self._search_result = SearchResults.FAILURE
446 self._search_result_rate = None
450 # no loss => non/partial drop rate found
452 self._search_result = SearchResults.SUCCESS
453 self._search_result_rate = rate
456 raise RuntimeError("Unknown search result")
458 raise Exception("Unknown search direction")
460 raise Exception("Wrong codepath")
462 def verify_search_result(self):
463 """Fail if search was not successful.
465 :return: Result rate and latency stats.
468 if self._search_result == SearchResults.FAILURE:
469 raise Exception('Search FAILED')
470 elif self._search_result in [SearchResults.SUCCESS,
471 SearchResults.SUSPICIOUS]:
472 return self._search_result_rate, self.get_latency()
474 def binary_search(self, b_min, b_max, traffic_type, skip_max_rate=False):
475 """Binary search of rate with loss below acceptance criteria.
477 :param b_min: Min range rate.
478 :param b_max: Max range rate.
479 :param traffic_type: Traffic profile.
480 :param skip_max_rate: Start with max rate first
483 :type traffic_type: str
484 :type skip_max_rate: bool
488 if not self._rate_min <= float(b_min) <= self._rate_max:
489 raise ValueError("Min rate is not in min,max range")
490 if not self._rate_min <= float(b_max) <= self._rate_max:
491 raise ValueError("Max rate is not in min,max range")
492 if float(b_max) < float(b_min):
493 raise ValueError("Min rate is greater than max rate")
497 # rate is half of interval + start of interval
498 rate = ((float(b_max) - float(b_min)) / 2) + float(b_min)
500 # rate is max of interval
502 # rate diff with previous run
503 rate_diff = abs(self._last_binary_rate - rate)
505 # convergence criterium
506 if float(rate_diff) < float(self._binary_convergence_threshold):
507 if not self._search_result_rate:
508 self._search_result = SearchResults.FAILURE
510 self._search_result = SearchResults.SUCCESS
513 self._last_binary_rate = rate
516 for dummy in range(self._max_attempts):
517 res.append(self.measure_loss(rate, self._frame_size,
518 self._loss_acceptance,
519 self._loss_acceptance_type,
522 res = self._get_res_based_on_search_type(res)
524 # loss occurred and it was above acceptance criteria
526 self.binary_search(b_min, rate, traffic_type, True)
527 # there was no loss / loss below acceptance criteria
529 self._search_result_rate = rate
530 self.binary_search(rate, b_max, traffic_type, True)
532 def combined_search(self, start_rate, traffic_type):
533 """Combined search of rate with loss below acceptance criteria.
535 :param start_rate: Initial rate.
536 :param traffic_type: Traffic profile.
537 :type start_rate: float
538 :type traffic_type: str
542 self.linear_search(start_rate, traffic_type)
544 if self._search_result in [SearchResults.SUCCESS,
545 SearchResults.SUSPICIOUS]:
546 b_min = self._search_result_rate
547 b_max = self._search_result_rate + self._rate_linear_step
549 # we found max rate by linear search
550 if self.floats_are_close_equal(float(b_min), self._rate_max):
553 # limiting binary range max value into max range
554 if float(b_max) > self._rate_max:
555 b_max = self._rate_max
558 temp_rate = self._search_result_rate
559 self._search_result_rate = None
561 # we will use binary search to refine search in one linear step
562 self.binary_search(b_min, b_max, traffic_type, True)
564 # linear and binary search succeed
565 if self._search_result == SearchResults.SUCCESS:
567 # linear search succeed but binary failed or suspicious
569 self._search_result = SearchResults.SUSPICIOUS
570 self._search_result_rate = temp_rate
572 raise RuntimeError("Linear search FAILED")
575 def floats_are_close_equal(num_a, num_b, rel_tol=1e-9, abs_tol=0.0):
576 """Compares two float numbers for close equality.
578 :param num_a: First number to compare.
579 :param num_b: Second number to compare.
580 :param rel_tol=1e-9: The relative tolerance.
581 :param abs_tol=0.0: The minimum absolute tolerance level.
586 :return: Returns True if num_a is close in value to num_b or equal.
594 if rel_tol < 0.0 or abs_tol < 0.0:
595 raise ValueError('Error tolerances must be non-negative')
597 return abs(num_b - num_a) <= max(rel_tol * max(abs(num_a), abs(num_b)),