summaryrefslogtreecommitdiff
path: root/cpp/src/IceStorm/SubscriberPool.cpp
blob: 6f42665af373ad45dcd976583ff46a07c8cf4f4a (plain)
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
// **********************************************************************
//
// Copyright (c) 2003-2006 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************

#include <IceStorm/SubscriberPool.h>
#include <IceStorm/Instance.h>
#include <IceStorm/TraceLevels.h>
#include <IceStorm/Subscribers.h>

#include <Ice/Communicator.h>
#include <Ice/Properties.h>
#include <Ice/LoggerUtil.h>

using namespace IceStorm;
using namespace std;

namespace IceStorm
{

class SubscriberPoolWorker : public IceUtil::Thread
{
public:

    SubscriberPoolWorker(const SubscriberPoolPtr& manager) :
	_manager(manager)
    {
	start();
    }

    ~SubscriberPoolWorker()
    {
    }

    virtual void
    run()
    {
	SubscriberPtr sub;
	while(true)
	{
	    sub = _manager->dequeue(sub);
	    if(!sub)
	    {
		return;
	    }
	    //
	    // If SubscriberPool returns true then the subscriber needs to be
	    // SubscriberPooled again, so therefore we will re-enqueue the
	    // subscriber in the call to dequeue.
	    //
	    if(!sub->flush())
	    {
		sub = 0;
	    }
	}
    }

private:

    const SubscriberPoolPtr _manager;
};

}

SubscriberPoolMonitor::SubscriberPoolMonitor(const SubscriberPoolPtr& manager, const IceUtil::Time& timeout) :
    _manager(manager),
    _timeout(timeout),
    _needCheck(false),
    _destroy(false)
{
    start();
}

SubscriberPoolMonitor::~SubscriberPoolMonitor()
{
}

void
SubscriberPoolMonitor::run()
{
    for(;;)
    {
        {
    	    Lock sync(*this);
    	    if(_destroy)
    	    {
    	        return;
    	    }
    
    	    if(_needCheck)
    	    {
    	        timedWait(_timeout);
    	        //
    	        // Monitoring was stopped.
    	        //
    	        if(!_needCheck)
    	        {
    		    continue;
    	        }
    	    }
    	    else
    	    {
    	        wait();
    	        continue;
    	    }
        }
        //
        // Call outside of the lock to prevent any deadlocks.
        //
        _manager->check();
    }
}

void
SubscriberPoolMonitor::startMonitor()
{
    Lock sync(*this);
    if(!_needCheck)
    {
        _needCheck = true;
        notify();
    }
}

void
SubscriberPoolMonitor::stopMonitor()
{
    Lock sync(*this);
    _needCheck = false;
}

void
SubscriberPoolMonitor::destroy()
{
    Lock sync(*this);
    _destroy = true;
    notify();
}

SubscriberPool::SubscriberPool(const InstancePtr& instance) :
    _instance(instance),
    _sizeMax(instance->properties()->getPropertyAsIntWithDefault(
		 "IceStorm.SubscriberPool.SizeMax", -1)),
    _sizeWarn(instance->properties()->getPropertyAsIntWithDefault(
		  "IceStorm.SubscriberPool.SizeWarn", 0)),
    _size(instance->properties()->getPropertyAsIntWithDefault(
	      "IceStorm.SubscriberPool.Size", 1)),
    _timeout(IceUtil::Time::milliSeconds(max(instance->properties()->getPropertyAsIntWithDefault(
						 "IceStorm.SubscriberPool.Timeout", 250), 50))), // minimum 50ms.
    _destroy(false),
    _inUse(0),
    _running(0),
    _load(1.0)
{
    try
    {
	__setNoDelete(true);
	_subscriberPoolMonitor = new SubscriberPoolMonitor(this, _timeout);
	for(int i = 0; i < _size; ++i)
	{
	    ++_running;
	    ++_inUse;
	    _workers.push_back(new SubscriberPoolWorker(this));
	}
    }
    catch(const IceUtil::Exception& ex)
    {
	{
	    Ice::Error out(_instance->traceLevels()->logger);
	    out << "SubscriberPool: " << ex;
	}
	destroy();
	__setNoDelete(false);
	throw;
    }

    __setNoDelete(false);
}

SubscriberPool::~SubscriberPool()
{
}
    
void
SubscriberPool::add(list<SubscriberPtr>& subscribers)
{
    IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
    //
    // Splice on the new set of subscribers to SubscriberPool.
    //
    _pending.splice(_pending.end(), subscribers);
    notifyAll();
}

//
// The passed subscriber need to be enqueued again.
//
SubscriberPtr
SubscriberPool::dequeue(const SubscriberPtr& sub)
{
    IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);

    if(sub)
    {
	_pending.push_back(sub);
    }

    //
    // Now we check if this thread can be destroyed, based on a
    // load factor.
    //
    // The load factor jumps immediately to the number of threads
    // that are currently in use, but decays exponentially if the
    // number of threads in use is smaller than the load
    // factor. This reflects that we create threads immediately
    // when they are needed, but want the number of threads to
    // slowly decline to the configured minimum.
    //
    double inUse = static_cast<double>(_inUse);
    if(_load < inUse)
    {
	_load = inUse;
    }
    else
    {
	const double loadFactor = 0.05; // TODO: Configurable?
	const double oneMinusLoadFactor = 1 - loadFactor;
	_load = _load * oneMinusLoadFactor + inUse * loadFactor;
    }

    if(_running > _size)
    {
	TraceLevelsPtr traceLevels = _instance->traceLevels();
	if(traceLevels->subscriberPool > 1)
	{
	    IceUtil::Time interval = IceUtil::Time::now() - _lastNext;
	    Ice::Trace out(traceLevels->logger, traceLevels->subscriberPoolCat);
	    out << "load check: " << _load;
	}

	int load = static_cast<int>(_load + 0.5);

	if(load < _running)
	{
	    assert(_inUse > 0);
	    --_inUse;

	    assert(_running > 0);
	    --_running;

	    if(traceLevels->subscriberPool > 0)
	    {
		Ice::Trace out(traceLevels->logger, traceLevels->subscriberPoolCat);
		out << "reducing SubscriberPool threads: load: " << _load << " threads: " << _running;
	    }

	    return 0;
	}
	
    }

    assert(_inUse > 0);
    --_inUse;

    while(_pending.empty() && !_destroy)
    {
	//
	// If we wait then there is no need to monitor anymore.
	//
	_subscriberPoolMonitor->stopMonitor();
	wait();
    }

    if(_destroy)
    {
	--_running;
	return 0;
    }

    _lastNext = IceUtil::Time::now();

    SubscriberPtr subscriber = _pending.front();
    _pending.pop_front();

    ++_inUse;

    //
    // If all threads are now in use then we need to start the
    // monitoring, otherwise we don't need to monitor.
    //
    if(_inUse == _running && (_running < _sizeMax || _sizeMax == -1))
    {
	_subscriberPoolMonitor->startMonitor();
    }
    else
    {
	_subscriberPoolMonitor->stopMonitor();
    }
    return subscriber;
}

void
SubscriberPool::destroy()
{
    //
    // First mark the pool as destroyed. This causes all of the worker
    // threads to unblock and terminate.
    //
    {
	IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
	_destroy = true;
	notifyAll();
	if(_subscriberPoolMonitor)
	{
	    _subscriberPoolMonitor->destroy();
	}
    }

    //
    // Next join with each worker.
    //
    for(list<IceUtil::ThreadPtr>::const_iterator p = _workers.begin(); p != _workers.end(); ++p)
    {
	(*p)->getThreadControl().join();
    }
    _workers.clear();

    //
    // Once all of the workers have gone then we'll no longer have
    // concurrent access to the pool monitor, so we can join with it
    // and then clear to remove the circular reference count.
    //
    if(_subscriberPoolMonitor)
    {
	_subscriberPoolMonitor->getThreadControl().join();
	_subscriberPoolMonitor = 0;
    }
}

void
SubscriberPool::check()
{
    Lock sync(*this);

    TraceLevelsPtr traceLevels = _instance->traceLevels();
    IceUtil::Time interval = IceUtil::Time::now() - _lastNext;
    if(traceLevels->subscriberPool > 1)
    {
	Ice::Trace out(traceLevels->logger, traceLevels->subscriberPoolCat);
	out << "check called: interval: "  << interval << " timeout: " << _timeout
	    << " pending: " << _pending.size() << " running: " << _running
	    << " sizeMax: " << _sizeMax;
    }
    
    if(interval > _timeout && _pending.size() > 0 && (_running < _sizeMax || _sizeMax == -1))
    {
	if(traceLevels->subscriberPool > 0)
	{
	    Ice::Trace out(traceLevels->logger, traceLevels->subscriberPoolCat);
	    out << "detected stall: creating thread: load: " << _load << " threads: " << _running;
	}
	
	++_running;
	++_inUse;
	_workers.push_back(new SubscriberPoolWorker(this));
    }
}