-
Notifications
You must be signed in to change notification settings - Fork 175
Expand file tree
/
Copy pathload_balancing.py
More file actions
69 lines (49 loc) · 1.65 KB
/
load_balancing.py
File metadata and controls
69 lines (49 loc) · 1.65 KB
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
from __future__ import annotations
from abc import ABCMeta, abstractmethod
from collections.abc import Mapping
import attrs
from yarl import URL
@attrs.define(auto_attribs=True, frozen=True)
class LoadBalancerConfig:
name: str
args: tuple[str, ...]
class LoadBalancer(metaclass=ABCMeta):
@staticmethod
def load(config: LoadBalancerConfig) -> LoadBalancer:
cls = _cls_map[config.name]
return cls(*config.args)
@staticmethod
def clean_config(config: str) -> LoadBalancerConfig:
name, _, raw_args = config.partition(":")
args = raw_args.split(",")
return LoadBalancerConfig(name, tuple(args))
@abstractmethod
def rotate(self, endpoints: list[URL]) -> None:
raise NotImplementedError
class SimpleRRLoadBalancer(LoadBalancer):
"""
Rotates the endpoints upon every request.
"""
def rotate(self, endpoints: list[URL]) -> None:
if len(endpoints) == 1:
return
item = endpoints.pop(0)
endpoints.append(item)
class PeriodicRRLoadBalancer(LoadBalancer):
"""
Rotates the endpoints upon the specified interval.
"""
def rotate(self, endpoints: list[URL]) -> None:
pass
class LowestLatencyLoadBalancer(LoadBalancer):
"""
Change the endpoints with the lowest average latency for last N requests.
"""
def rotate(self, endpoints: list[URL]) -> None:
pass
# TODO: we need to collect and allow access to the latency statistics.
_cls_map: Mapping[str, type[LoadBalancer]] = {
"simple_rr": SimpleRRLoadBalancer,
"periodic_rr": PeriodicRRLoadBalancer,
"lowest_latency": LowestLatencyLoadBalancer,
}