15815213711
2024-08-26 67b8b6731811983447e053d4396b3708c14dfe3c
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
const Consts = require("./consts");
const Scheduler = require("./scheduler");
 
/**
 * 负载均衡器
 * @intro 参考electron-re项目,并做了一些改动
 * @since 1.0.0
 */
class LoadBalancer {
 
  static Algorithm = Consts;
 
  /**
    * @param  {Object} options
    * @param  {Array } options.targets [ targets for load balancing calculation: [{id: 1, weight: 1}, {id: 2, weight: 2}] ]
    * @param  {String} options.algorithm 
    */
  constructor(options) {
    this.targets = options.targets;
    this.algorithm = options.algorithm || Consts.polling;
    this.params = { // data for algorithm
      currentIndex: 0, // index
      weightIndex: 0, // index for weight alogrithm
      weightTotal: 0, // total weight
      connectionsMap: {}, // connections of each target
      cpuOccupancyMap: {}, // cpu occupancy of each target
      memoryOccupancyMap: {}, // cpu occupancy of each target
    };
    this.scheduler = new Scheduler(this.algorithm);
    this.memoParams = this.memorizedParams();
    this.calculateWeightIndex();
  }
 
  /**
   * 算法参数
   */
  memorizedParams() {
    return {
      [Consts.random]: () => [],
      [Consts.polling]: () => [this.params.currentIndex, this.params],
      [Consts.weights]: () => [this.params.weightTotal, this.params],
      [Consts.specify]: (id) => [id],
      [Consts.weightsRandom]: () => [this.params.weightTotal],
      [Consts.weightsPolling]: () => [this.params.weightIndex, this.params.weightTotal, this.params],
      [Consts.minimumConnection]: () => [this.params.connectionsMap],
      [Consts.weightsMinimumConnection]: () => [this.params.weightTotal, this.params.connectionsMap, this.params],
    };
  }
 
  /**
   * 刷新参数
   */
  refreshParams(pidMap) {
    const infos = Object.values(pidMap);
    for (let info of infos) {
      // this.params.connectionsMap[id] = connections;
      this.params.cpuOccupancyMap[info.pid] = info.cpu;
      this.params.memoryOccupancyMap[info.pid] = info.memory;
    }
  }
 
  /**
   * 选举出一个进程
   */
  pickOne(...params) {
    return this.scheduler.calculate(
      this.targets, this.memoParams[this.algorithm](...params)
    );
  }
 
  /**
   * 选举出多个进程
   */
  pickMulti(count = 1, ...params) {
    return new Array(count).fill().map(
      () => this.pickOne(...params)
    );
  }
 
  /**
   * 计算权重
   */
  calculateWeightIndex() {
    this.params.weightTotal = this.targets.reduce((total, cur) => total + (cur.weight || 0), 0);
    if (this.params.weightIndex > this.params.weightTotal) {
      this.params.weightIndex = this.params.weightTotal;
    }
  }
 
  /**
   * 计算索引
   */
  calculateIndex() {
    if (this.params.currentIndex >= this.targets.length) {
      this.params.currentIndex = (this.params.currentIndex - 1 >= 0) ? (this.params.currentIndex - 1) : 0;
    }
  }
 
  /**
   * 清除data
   */
  clean(id) {
    if (id) {
      delete this.params.connectionsMap[id];
      delete this.params.cpuOccupancyMap[id];
      delete this.params.memoryOccupancyMap[id];
    } else {
      this.params = {
        currentIndex: 0,
        connectionsMap: {},
        cpuOccupancyMap: {},
        memoryOccupancyMap: {},
      };
    }
  }
 
  /**
   * 添加一个进程信息
   */
  add(task) {
    if (this.targets.find(target => target.id === task.id)) {
      return console.warn(`Add Operation: the task ${task.id} already exists.`);
    }
    this.targets.push(task);
    this.calculateWeightIndex();
  }
 
  /**
   * 删除一个进程信息
   */
  del(target) {
    let found = false;
    for (let i  = 0; i < this.targets.length; i++) {
      if (this.targets[i].id === target.id) {
        this.targets.splice(i, 1);
        this.clean(target.id);
        this.calculateIndex();
        found = true;
        break;
      }
    }
 
    if (found) {
      this.calculateWeightIndex();
    } else {
      console.warn(`Del Operation: the task ${target.id} is not found.`, this.targets);
    }
  }
 
  /**
   * 擦除
   */
  wipe() {
    this.targets = [];
    this.calculateWeightIndex();
    this.clean();
  }
 
  /**
   * 更新计算参数
   */
  updateParams(object) {
    Object.entries(object).map(([key, value]) => {
      if (key in this.params) {
        this.params[key] = value;
      }
    });
  }
 
  /**
   * 设置targets
   */
  setTargets(targets) {
    const targetsMap = targets.reduce((total, cur) => {
      total[cur.id] = 1;
      return total;
    }, {});
    this.targets.forEach(target => {
      if (!(target.id in targetsMap)) {
        this.clean(target.id);
        this.calculateIndex();
      }
    });
    this.targets = targets;
    this.calculateWeightIndex();
  }
 
  /**
   * 设置算法
   */
  setAlgorithm = (algorithm) => {
    if (algorithm in Consts) {
      this.algorithm = algorithm;
      this.params.weightIndex = 0;
      this.scheduler.setAlgorithm(this.algorithm);
    } else {
      throw new Error(`Invalid algorithm: ${algorithm}, pick from ${Object.keys(Consts).join('|')}`);
    }
  }
}
 
module.exports = LoadBalancer;