summaryrefslogtreecommitdiff
path: root/cpp/src/Ice/Collector.cpp
blob: 360cb89739a15140a565ab82c65913b38c54a744 (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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
// **********************************************************************
//
// Copyright (c) 2001
// MutableRealms, Inc.
// Huntsville, AL, USA
//
// All Rights Reserved
//
// **********************************************************************

#include <Ice/Collector.h>
#include <Ice/Instance.h>
#include <Ice/Logger.h>
#include <Ice/Properties.h>
#include <Ice/TraceUtil.h>
#include <Ice/Transceiver.h>
#include <Ice/Acceptor.h>
#include <Ice/ThreadPool.h>
#include <Ice/ObjectAdapter.h>
#include <Ice/Endpoint.h>
#include <Ice/Incoming.h>
#include <Ice/Exception.h>
#include <Ice/Protocol.h>
#include <Ice/Functional.h>
#include <Ice/SslException.h>

using namespace std;
using namespace Ice;
using namespace IceInternal;
using IceSecurity::SecurityException;

void IceInternal::incRef(Collector* p) { p->__incRef(); }
void IceInternal::decRef(Collector* p) { p->__decRef(); }

void IceInternal::incRef(CollectorFactory* p) { p->__incRef(); }
void IceInternal::decRef(CollectorFactory* p) { p->__decRef(); }

void
IceInternal::Collector::destroy()
{
    JTCSyncT<JTCRecursiveMutex> sync(*this);
    setState(StateClosing);
}

bool
IceInternal::Collector::destroyed() const
{
    JTCSyncT<JTCRecursiveMutex> sync(*this);
    return _state >= StateClosing;
}

void
IceInternal::Collector::hold()
{
    JTCSyncT<JTCRecursiveMutex> sync(*this);
    setState(StateHolding);
}

void
IceInternal::Collector::activate()
{
    JTCSyncT<JTCRecursiveMutex> sync(*this);
    setState(StateActive);
}

bool
IceInternal::Collector::server() const
{
    return true;
}

bool
IceInternal::Collector::readable() const
{
    return true;
}

void
IceInternal::Collector::read(BasicStream& stream)
{
    _transceiver->read(stream, 0);
}

void
IceInternal::Collector::message(BasicStream& stream)
{
    Incoming in(_instance, _adapter);
    BasicStream* os = in.os();
    bool invoke = false;
    bool batch = false;
    bool response = false;

    {
	JTCSyncT<JTCRecursiveMutex> sync(*this);

	_threadPool->promoteFollower();

	if (_state != StateActive && _state != StateClosing)
	{
	    return;
	}
	
	try
	{
	    assert(stream.i == stream.b.end());
	    stream.i = stream.b.begin() + 2;
	    Byte messageType;
	    stream.read(messageType);
	    stream.i = stream.b.begin() + headerSize;

	    //
	    // Write partial message header
	    //
	    os->write(protocolVersion);
	    os->write(encodingVersion);
	    
	    switch (messageType)
	    {
		case requestMsg:
		{
		    if (_state == StateClosing)
		    {
			traceRequest("received request during closing\n"
				     "(ignored by server, client will retry)",
				     stream, _logger, _traceLevels);
		    }
		    else
		    {
			traceRequest("received request",
				     stream, _logger, _traceLevels);
			invoke = true;
			Int requestId;
			stream.read(requestId);
			if (!_endpoint->oneway() && requestId != 0) // 0 means oneway
			{
			    response = true;
			    ++_responseCount;
			    os->write(replyMsg);
			    os->write(Int(0)); // Message size (placeholder)
			    os->write(requestId);
			}
		    }
		    break;
		}
		
		case requestBatchMsg:
		{
		    if (_state == StateClosing)
		    {
			traceBatchRequest("received batch request during closing\n"
					  "(ignored by server, client will retry)",
					  stream, _logger, _traceLevels);
		    }
		    else
		    {
			traceBatchRequest("received batch request",
					  stream, _logger, _traceLevels);
			invoke = true;
			batch = true;
		    }
		    break;
		}
		
		case replyMsg:
		{
		    traceReply("received reply on server side\n"
			       "(invalid, closing connection)",
			       stream, _logger, _traceLevels);
		    throw InvalidMessageException(__FILE__, __LINE__);
		    break;
		}
		
		case closeConnectionMsg:
		{
		    traceHeader("received close connection on server side\n"
				"(invalid, closing connection)",
				stream, _logger, _traceLevels);
		    throw InvalidMessageException(__FILE__, __LINE__);
		    break;
		}
		
		default:
		{
		    traceHeader("received unknown message\n"
				"(invalid, closing connection)",
				stream, _logger, _traceLevels);
		    throw UnknownMessageException(__FILE__, __LINE__);
		    break;
		}
	    }
	}
	catch (const ConnectionLostException&)
	{
	    setState(StateClosed); // Connection drop from client is ok
	    return;
	}
	catch (const LocalException& ex)
	{
	    warning(ex);
	    setState(StateClosed);
	    return;
	}
    }
    
    if (invoke)
    {
	do
	{
	    try
	    {
		if (batch)
		{
		    stream.startReadEncaps();
		}

		in.invoke(stream);

		if (batch)
		{
		    stream.swap(*in.is()); // If we're in batch mode, we need the input stream back
		    stream.endReadEncaps();
		}
	    }
	    catch (const Exception& ex)
	    {
		JTCSyncT<JTCRecursiveMutex> sync(*this);
		warning(ex);
	    }
	    catch (...)
	    {
		assert(false); // Should not happen
	    }
	}
	while (batch && stream.i < stream.b.end());
    }

    if (response)
    {
	JTCSyncT<JTCRecursiveMutex> sync(*this);
	
	if (_state != StateActive && _state != StateClosing)
	{
	    return;
	}
	
	try
	{
	    os->i = os->b.begin();
	    
	    //
	    // Fill in the message size
	    //
	    const Byte* p;
	    Int sz = os->b.size();
	    p = reinterpret_cast<Byte*>(&sz);
	    copy(p, p + sizeof(Int), os->i + 3);
	    
	    traceReply("sending reply", *os, _logger, _traceLevels);
	    _transceiver->write(*os, _endpoint->timeout());
	    
	    --_responseCount;

	    if (_state == StateClosing && _responseCount == 0)
	    {
		closeConnection();
	    }
	}
	catch (const ConnectionLostException&)
	{
	    setState(StateClosed); // Connection drop from client is ok
	    return;
	}
	catch (const LocalException& ex)
	{
	    warning(ex);
	    setState(StateClosed);
	    return;
	}
    }
}

void
IceInternal::Collector::exception(const LocalException& ex)
{
    JTCSyncT<JTCRecursiveMutex> sync(*this);

    if (_state != StateActive && _state != StateClosing)
    {
	return;
    }

    if (!dynamic_cast<const ConnectionLostException*>(&ex))
    {
	warning(ex);
    }

    setState(StateClosed);
}

void
IceInternal::Collector::finished()
{
    JTCSyncT<JTCRecursiveMutex> sync(*this);

    //
    // We also unregister with the thread poool if we go to holding
    // state, but in this case we may not close the connection.
    //
    if (_state == StateClosed)
    {
	_transceiver->close();
    }
}

bool
IceInternal::Collector::tryDestroy()
{
    bool isLocked = trylock();
    if(!isLocked)
    {
	return false;
    }

    _threadPool->promoteFollower();

    try
    {
	setState(StateClosing);
    }
    catch (...)
    {
	unlock();
	throw;
    }
    
    unlock();    
    return true;
}

IceInternal::Collector::Collector(const InstancePtr& instance,
				  const ObjectAdapterPtr& adapter,
				  const TransceiverPtr& transceiver,
				  const EndpointPtr& endpoint) :
    EventHandler(instance),
    _adapter(adapter),
    _transceiver(transceiver),
    _endpoint(endpoint),
    _traceLevels(instance->traceLevels()),
    _logger(instance->logger()),
    _responseCount(0),
    _state(StateHolding)
{
    _warnAboutExceptions =
	atoi(_instance->properties()->getProperty("Ice.WarnAboutServerExceptions").c_str()) > 0 ? true : false;

    _threadPool = _instance->threadPool();
}

IceInternal::Collector::~Collector()
{
    assert(_state == StateClosed);
}

void
IceInternal::Collector::setState(State state)
{
    if (_endpoint->oneway() && state == StateClosing)
    {
	state = StateClosed;
    }
    
    if (_state == state) // Don't switch twice
    {
	return;
    }
    
    switch (state)
    {
	case StateActive:
	{
	    if (_state != StateHolding) // Can only switch from holding to active
	    {
		return;
	    }

	    _threadPool->_register(_transceiver->fd(), this);
	    break;
	}
	
	case StateHolding:
	{
	    if (_state != StateActive) // Can only switch from active to holding
	    {
		return;
	    }

	    _threadPool->unregister(_transceiver->fd());
	    break;
	}

	case StateClosing:
	{
	    if (_state == StateClosed) // Can't change back from closed
	    {
		return;
	    }

	    if (_responseCount == 0)
	    {
		try
		{
		    closeConnection();
		}
		catch (const ConnectionLostException&)
		{
		    state = StateClosed;
		    setState(state); // Connection drop from client is ok
		}
		catch (const LocalException& ex)
		{
		    warning(ex);
		    state = StateClosed;
		    setState(state);
		}
	    }
	    
	    //
	    // We need to continue to read data in closing state
	    //
	    if (_state == StateHolding)
	    {
		_threadPool->_register(_transceiver->fd(), this);
	    }
	    break;
	}

	case StateClosed:
	{
	    //
	    // If we come from holding state, we are already unregistered,
	    // so we can close right away.
	    //
	    if (_state == StateHolding)
	    {
		_transceiver->close();
	    }
	    else
	    {
		_threadPool->unregister(_transceiver->fd());
	    }
	    break;
	}
    }

    _state = state;
}

void
IceInternal::Collector::closeConnection()
{
    BasicStream os(_instance);
    os.write(protocolVersion);
    os.write(encodingVersion);
    os.write(closeConnectionMsg);
    os.write(headerSize); // Message size
    os.i = os.b.begin();
    traceHeader("sending close connection", os, _logger, _traceLevels);
    _transceiver->write(os, _endpoint->timeout());
    _transceiver->shutdown();
}

void
IceInternal::Collector::warning(const Exception& ex) const
{
    if (_warnAboutExceptions)
    {
	ostringstream s;
	s << "server exception:\n" << ex << '\n' << _transceiver->toString();
	_logger->warning(s.str());
    }
}

void
IceInternal::CollectorFactory::destroy()
{
    JTCSyncT<JTCMutex> sync(*this);
    setState(StateClosed);
}

void
IceInternal::CollectorFactory::hold()
{
    JTCSyncT<JTCMutex> sync(*this);
    setState(StateHolding);
}

void
IceInternal::CollectorFactory::activate()
{
    JTCSyncT<JTCMutex> sync(*this);
    setState(StateActive);
}

EndpointPtr
IceInternal::CollectorFactory::endpoint() const
{
    return _endpoint;
}

bool
IceInternal::CollectorFactory::equivalent(const EndpointPtr& endp) const
{
    if (_transceiver)
    {
	return endp->equivalent(_transceiver);
    }
    
    assert(_acceptor);
    return endp->equivalent(_acceptor);
}

bool
IceInternal::CollectorFactory::server() const
{
    return true;
}

bool
IceInternal::CollectorFactory::readable() const
{
    return false;
}

void
IceInternal::CollectorFactory::read(BasicStream&)
{
    assert(false); // Must not be called
}

void
IceInternal::CollectorFactory::message(BasicStream&)
{
    JTCSyncT<JTCMutex> sync(*this);

    _threadPool->promoteFollower();

    if (_state != StateActive)
    {
	return;
    }
    
    //
    // First reap destroyed collectors
    //
    // Can't use _collectors.remove_if(constMemFun(...)), because VC++
    // doesn't support member templates :-(
    _collectors.erase(remove_if(_collectors.begin(), _collectors.end(), ::Ice::constMemFun(&Collector::destroyed)),
		      _collectors.end());

    //
    // Now accept a new connection and create a new CollectorPtr
    //
    try
    {
	TransceiverPtr transceiver = _acceptor->accept(0);
	CollectorPtr collector = new Collector(_instance, _adapter, transceiver, _endpoint);
	collector->activate();
	_collectors.push_back(collector);
    }
    catch (const SecurityException&)
    {
        // TODO: bandaid.  Takes care of SSL Handshake problems during creation of a Transceiver
        // Ignore, nothing we can do here
    }
    catch (const SocketException&)
    {
        // TODO: bandaid.  Takes care of SSL Handshake problems during creation of a Transceiver
        // Ignore, nothing we can do here
    }
    catch (const TimeoutException&)
    {
	// Ignore timeouts
    }
    catch (const LocalException& ex)
    {
	warning(ex);
	destroy();
    }
}

void
IceInternal::CollectorFactory::exception(const LocalException&)
{
    assert(false); // Must not be called
}

void
IceInternal::CollectorFactory::finished()
{
    JTCSyncT<JTCMutex> sync(*this);

    //
    // We also unregister with the thread poool if we go to holding
    // state, but in this case we may not close the acceptor.
    //
    if (_state == StateClosed)
    {
	_acceptor->shutdown();
	clearBacklog();
	_acceptor->close();
    }
}

bool
IceInternal::CollectorFactory::tryDestroy()
{
    //
    // Do nothing. We don't want collector factories to be closed by
    // active connection management.
    //
    return false;
}

IceInternal::CollectorFactory::CollectorFactory(const InstancePtr& instance,
						const ObjectAdapterPtr& adapter,
						const EndpointPtr& endpoint) :
    EventHandler(instance),
    _adapter(adapter),
    _endpoint(endpoint),
    _traceLevels(instance->traceLevels()),
    _logger(instance->logger()),
    _state(StateHolding)
{
    _warnAboutExceptions =
	atoi(_instance->properties()->getProperty("Ice.WarnAboutServerExceptions").c_str()) > 0 ? true : false;

    try
    {
	_transceiver = _endpoint->serverTransceiver(_instance, _endpoint);
	if (_transceiver)
	{
	    CollectorPtr collector = new Collector(_instance, _adapter, _transceiver, _endpoint);
	    _collectors.push_back(collector);
	}
	else
	{
	    _acceptor = _endpoint->acceptor(_instance, _endpoint);
	    assert(_acceptor);
	    _acceptor->listen();
	    _threadPool = _instance->threadPool();
	}
    }
    catch (...)
    {
	setState(StateClosed);
	throw;
    }
}

IceInternal::CollectorFactory::~CollectorFactory()
{
    assert(_state == StateClosed);
}

void
IceInternal::CollectorFactory::setState(State state)
{
    if (_state == state) // Don't switch twice
    {
	return;
    }

    switch (state)
    {
	case StateActive:
	{
	    if (_state != StateHolding) // Can only switch from holding to active
	    {
		return;
	    }

	    if (_threadPool)
	    {
		_threadPool->_register(_acceptor->fd(), this);
	    }

	    for_each(_collectors.begin(), _collectors.end(), ::Ice::voidMemFun(&Collector::activate));
	    break;
	}
	
	case StateHolding:
	{
	    if (_state != StateActive) // Can only switch from active to holding
	    {
		return;
	    }

	    if (_threadPool)
	    {
		_threadPool->unregister(_acceptor->fd());
	    }

	    for_each(_collectors.begin(), _collectors.end(), ::Ice::voidMemFun(&Collector::hold));
	    break;
	}
	
	case StateClosed:
	{
	    if (_threadPool)
	    {
		//
		// If we come from holding state, we are already
		// unregistered, so we can close right away.
		//
		if (_state == StateHolding)
		{
		    _acceptor->shutdown();
		    clearBacklog();
		    _acceptor->close();
		}
		else
		{
		    _threadPool->unregister(_acceptor->fd());
		}
	    }
	    for_each(_collectors.begin(), _collectors.end(), ::Ice::voidMemFun(&Collector::destroy));
	    _collectors.clear();
	    break;
	}
    }

    _state = state;
}

void
IceInternal::CollectorFactory::clearBacklog()
{
    //
    // Clear listen() backlog properly by accepting all queued
    // connections, and then shutting them down.
    //
    while (true)
    {
	try
	{
	    TransceiverPtr transceiver = _acceptor->accept(0);
	    CollectorPtr collector = new Collector(_instance, _adapter, transceiver, _endpoint);
	    collector->destroy();
	}
	catch (const Exception&)
	{
	    break;
	}
    }
}

void
IceInternal::CollectorFactory::warning(const Exception& ex) const
{
    if (_warnAboutExceptions)
    {
	ostringstream s;
	s << "server exception:\n" << ex << '\n' << _acceptor->toString();
	_logger->warning(s.str());
    }
}