1 #include "lbs_ii.h"
2
3 Define_Module( LBS_II )
4
5 void LBS_II::activity()
6 {
7
8 simtime_t delta_t = par("delta_t");
9
10
11
12 cModule *compound = parentModule();
13
14 for (int i = 0; i<serverCount; i++) {
15 cModule *svr = compound->submodule("server", i);
16 if ((svr==0) || (strcmp(svr->className(), "Server")!=0)) {
17 throw cException("server[] contains non-Server");
18 }
19 server[i] = (Server*) svr;
20 rate[i] = svr->par("rate");
21 }
22
23
24 cMessage *updateMsg = new cMessage("update-balancer");
25 scheduleAt(simTime() + delta_t, updateMsg);
26 update();
27
28
29 for (;;) {
30
31 cMessage *msg = receive();
32
33 if (msg==updateMsg) {
34
35 update();
36 scheduleAt(simTime() + delta_t, updateMsg);
37 } else {
38
39 send(msg, "out", chooseServer());
40 }
41 }
42
43 }
44
45 void LBS_II::update()
46 {
47
48 int i;
49 double load = 100000000;
50 for (i = 0; i<serverCount; i++) {
51
52 long l = server[i]->getJobsInSystem();
53 if (l>0) --l;
54
55 double bl = (double) l/rate[i];
56 balancing[i] = bl;
57
58 if (bl<load) {
59 load = bl;
60 }
61 }
62
63
64 if (load==0.0) {
65
66 for (i = 0; i<serverCount; i++) {
67 if (balancing[i]!=0.0) balancing[i] = 1/(1+balancing[i]);
68 else balancing[i] = 1.0;
69 }
70 } else {
71
72 for (i = 0; i<serverCount; i++) {
73 if (balancing[i]!=0.0) balancing[i] = load/balancing[i];
74 else balancing[i] = 1.0;
75 }
76 }
77
78
79 double wSum = 0.0;
80 for (i = 0; i<serverCount; i++) wSum += balancing[i];
81
82
83 for (i = 0; i<serverCount; i++) {
84 balancing[i] /= wSum;
85 ev << "balancing[" << i << "] = " << balancing[i] << endl;
86 }
87
88
89 for (i = 1; i<serverCount; i++) balancing[i] += balancing[i-1];
90 }
91
92 int LBS_II::chooseServer()
93 {
94
95 double rVal = uniform(0, 1, rg);
96
97
98 int i = 0;
99 while ((i<serverCount) && (balancing[i]<rVal)) ++i;
100 if (i==serverCount) throw cException("error while choosing server!");
101
102 ev << "chose server " << i << endl;
103
104 return i;
105 }
106
107 void LBS_II::initialize()
108 {
109
110 rg = par("random_generator");
111 serverCount = par("server_count");
112
113 server = new Server *[serverCount];
114 rate = new double[serverCount];
115 balancing = new double[serverCount];
116 }
117
118 void LBS_II::finish()
119 {
120 delete [] server;
121 delete [] rate;
122 delete [] balancing;
123 }
124
125