summaryrefslogtreecommitdiff
path: root/cpp/src/IcePack/ServerI.cpp
blob: 97a32cdba7e9b0ab335f9b43c9da06735e20d218 (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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
// **********************************************************************
//
// Copyright (c) 2003-2004 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.
//
// **********************************************************************

#ifdef __sun
#define _POSIX_PTHREAD_SEMANTICS
#endif

#include <IceUtil/UUID.h>
#include <Ice/Ice.h>
#include <IcePack/ServerI.h>
#include <IcePack/ServerFactory.h>
#include <IcePack/TraceLevels.h>
#include <IcePack/Activator.h>

#include <sys/types.h>
#include <sys/stat.h>

#ifdef _WIN32
#   include <direct.h>
#else
#   include <unistd.h>
#   include <dirent.h>
#endif

#include <fstream>

using namespace std;
using namespace IcePack;

ServerI::ServerI(const ServerFactoryPtr& factory, 
		 const TraceLevelsPtr& traceLevels, 
		 const ActivatorPtr& activator,
		 Ice::Int waitTime,
		 const string& serversDir) :
    _factory(factory),
    _traceLevels(traceLevels),
    _activator(activator),
    _waitTime(waitTime),
    _serversDir(serversDir),
    _state(Inactive)
{
    assert(_activator);
}

ServerI::~ServerI()
{
}

bool
ServerI::start(ServerActivation act, const Ice::Current& current)
{
    string exe;
    string wd;
    Ice::StringSeq opts;
    Ice::StringSeq evs;

    while(true)
    {
	Lock sync(*this);
	switch(_state)
	{
	case Inactive:
	{
	    if(act < activation)
	    {
	        return false;
	    }

	    _state = Activating;

	    //
	    // Prevent eviction of the server object once it's not anymore in the inactive state.
	    //
	    _factory->getServerEvictor()->keep(current.id);

	    break;
	}
	case Activating:
	case Deactivating:
	{
	    wait(); // TODO: Timeout?
	    continue;
	}
 	case Active:
	{
	    return true; // Raise an exception instead?
	}
	case Destroying:
	case Destroyed:
	{
	    Ice::ObjectNotExistException ex(__FILE__,__LINE__);
	    ex.id = current.id;
	    throw ex;
	}
	}

	if(_traceLevels->server > 2)
	{
	    Ice::Trace out(_traceLevels->logger, _traceLevels->serverCat);
	    out << "changed server `" << name << "' state to `Activating'";
	}
	assert(_state == Activating);

	exe = exePath;
	wd = pwd;
	opts = options;
	evs = envs;
	break;
    }

    try
    {
	ServerPrx self = ServerPrx::uncheckedCast(current.adapter->createProxy(current.id));
	bool active  = _activator->activate(name, exe, wd, opts, evs, self);
	setState(active ? Active : Inactive, current);
	return active;
    }
    catch(const Ice::SyscallException& ex)
    {
	Ice::Warning out(_traceLevels->logger);
	out << "activation failed for server `" << name << "':\n";
	out << ex;

	setState(Inactive, current);
	return false;
    }
}

void
ServerI::stop(const Ice::Current& current)
{
    while(true)
    {
	Lock sync(*this);
	switch(_state)
	{
	case Inactive:
	{
	    return;
	}
	case Activating:
	case Deactivating:
	{
	    wait(); // TODO: Timeout?
	    continue;
	}
 	case Active:
	{	    
	    _state = Deactivating;
	    break;
	}
	case Destroying:
	case Destroyed:
	{
	    Ice::ObjectNotExistException ex(__FILE__,__LINE__);
	    ex.id = current.id;
	    throw ex;
	}
	}

	if(_traceLevels->server > 2)
	{
	    Ice::Trace out(_traceLevels->logger, _traceLevels->serverCat);
	    out << "changed server `" << name << "' state to `Deactivating'";
	}
	assert(_state == Deactivating);
	break;
    }

    stopInternal(current);
}

void
ServerI::sendSignal(const string& signal, const Ice::Current& current)
{
    _activator->sendSignal(name, signal);
}

void
ServerI::writeMessage(const string& message, Ice::Int fd, const Ice::Current& current)
{
    IceUtil::Monitor< ::IceUtil::Mutex>::Lock sync(*this);
    if(_process != 0)
    {
	try
	{
	    _process->writeMessage(message, fd);
	}
	catch(const Ice::LocalException&)
	{
	}
    }
}

void
ServerI::destroy(const Ice::Current& current)
{
    bool stop = false;

    while(true)
    {
	Lock sync(*this);
	switch(_state)
	{
	case Inactive:
	{
	    _state = Destroyed;
	    break;
	}
 	case Active:
	{
	    stop = true;
	    _state = Destroying;
	    break;
	}
	case Activating:
	case Deactivating:
	{
	    wait(); // TODO: Timeout?
	    continue;
	}
	case Destroying:
	case Destroyed:
	{
	    Ice::ObjectNotExistException ex(__FILE__,__LINE__);
	    ex.id = current.id;
	    throw ex;
	}
	}

	assert(_state == Destroyed || _state == Destroying);

	if(_traceLevels->server > 2)
	{
	    Ice::Trace out(_traceLevels->logger, _traceLevels->serverCat);
	    out << "changed server `" << name << "' state to `";
	    out << (_state == Destroyed ? "Destroyed" : "Destroying") << "'";
	}
	break;
    }

    if(stop)
    {
	stopInternal(current);
    }

    
    _factory->destroy(this, current.id);
}

void
ServerI::terminated(const Ice::Current& current)
{
    ServerState newState = Inactive; // Initialize to keep the compiler happy.
    ServerAdapterPrxDict adpts;
    while(true)
    {
	Lock sync(*this);
	switch(_state)
	{
	case Inactive:
	{
	    assert(false);
	}
	case Activating:
	{
	    wait(); // TODO: Timeout?
	    continue;
	}
	case Active:
	{
	    _state = Deactivating;
	    if(_traceLevels->server > 2)
	    {
		Ice::Trace out(_traceLevels->logger, _traceLevels->serverCat);
		out << "changed server `" << name << "' state to `Deactivating'";
	    }
	    newState = Inactive;
	    break;
	}
	case Deactivating:
	{
	    //
	    // Deactivation was initiated by the stop method.
	    //
	    newState = Inactive;
	    break;
	}
	case Destroying:
	{
	    //
	    // Deactivation was initiated by the destroy method.
	    //
	    newState = Destroyed;
	    break;
	}
	case Destroyed:
	{
	    assert(false);
	}
	}

	assert(_state == Deactivating || _state == Destroying);
	adpts = adapters;

	//
	// Clear the process proxy.
	//
	_process = 0;
	break;
    }

    if(newState != Destroyed)
    {
	//
	// The server has terminated, set its adapter direct proxies to
	// null to cause the server re-activation if one of its adapter
	// direct proxy is requested.
	//
	for(ServerAdapterPrxDict::iterator p = adpts.begin(); p != adpts.end(); ++p)
	{
	    try
	    {
		p->second->setDirectProxy(0);
	    }
	    catch(const Ice::ObjectNotExistException&)
	    {
	    }
	}
    }

    setState(newState, current);
}

ServerState
ServerI::getState(const Ice::Current&)
{
    Lock sync(*this);
    return _state;
}

Ice::Int
ServerI::getPid(const Ice::Current& current)
{
    return _activator->getServerPid(name);
}

void 
ServerI::setActivationMode(ServerActivation mode, const ::Ice::Current&)
{
    Lock sync(*this);
    activation = mode;
}

ServerActivation 
ServerI::getActivationMode(const ::Ice::Current&)
{
    Lock sync(*this);
    return activation;
}

ServerDescriptorPtr
ServerI::getDescriptor(const Ice::Current&)
{
    Lock sync(*this);
    return descriptor;
}

void 
ServerI::setExePath(const string& path, const ::Ice::Current&)
{
    Lock sync(*this);
    exePath = path;
}

void 
ServerI::setPwd(const string& path,const ::Ice::Current&)
{
    Lock sync(*this);
    pwd = path;
}

void 
ServerI::setEnvs(const Ice::StringSeq& s, const ::Ice::Current&)
{
    Lock sync(*this);
    envs = s;
}

void 
ServerI::setOptions(const Ice::StringSeq& opts, const ::Ice::Current&)
{
    Lock sync(*this);
    options = opts;
}

void 
ServerI::addAdapter(const ServerAdapterPrx& adapter, bool registerProcess, const ::Ice::Current&)
{
    Lock sync(*this);
    ServerAdapterPrxDict::const_iterator p = adapters.find(adapter->ice_getIdentity());
    if(p != adapters.end())
    {
	DeploymentException ex;
	ex.reason = "failed to add adapter because it already exists";
	throw ex;
    }
    adapters[adapter->ice_getIdentity()] = adapter;
    processRegistered |= registerProcess;
}

void
ServerI::removeAdapter(const ServerAdapterPrx& adapter, const ::Ice::Current&)
{
    Lock sync(*this);
    adapters.erase(adapter->ice_getIdentity());
}

string
ServerI::addConfigFile(const string& n, const PropertyDescriptorSeq& properties, const ::Ice::Current&)
{
    string file = _serversDir + name + "/config/" + n;

    ofstream configfile;
    configfile.open(file.c_str(), ios::out);
    if(!configfile)
    {
	DeploymentException ex;
	ex.reason = "couldn't create configuration file: " + file;
	throw ex;
    }

    for(PropertyDescriptorSeq::const_iterator p = properties.begin(); p != properties.end(); ++p)
    {
	configfile << p->name;
	if(!p->value.empty())
	{
	    configfile << "=" << p->value;
	}
	configfile << endl;
    }
    configfile.close();
    
    return file;
}

void 
ServerI::removeConfigFile(const string& n, const ::Ice::Current&)
{
    string file = _serversDir + name + "/config/" + n;
    if(unlink(file.c_str()) != 0)
    {
	Ice::Warning out(_traceLevels->logger);
	out << "couldn't remove configuration file: " + file + ": " + strerror(getSystemErrno());
    }
}

string
ServerI::addDbEnv(const DbEnvDescriptor& dbEnv, const string& path, const ::Ice::Current&)
{
    string dir;
    if(dbEnv.dbHome.empty())
    {
	dir = _serversDir + name + "/dbs/" + dbEnv.name;
    }
    else
    {
	dir = dbEnv.dbHome;
    }

    //
    // If no db home directory is specified for this db env, we provide one.
    //
    if(dbEnv.dbHome.empty())
    {
	//
	// First, we try to move the given backup if specified, if not successful, we just
	// create the database environment directory.
	//
	if(path.empty() || rename((path + "/" + dbEnv.name).c_str(), dir.c_str()) != 0)
	{
	    //
	    // Create the database environment directory.
	    //
#ifdef _WIN32
	    if(_mkdir(dir.c_str()) != 0)
#else
	    if(mkdir(dir.c_str(), 0755) != 0)
#endif
	    {
		DeploymentException ex;
		ex.reason = "couldn't create directory " + dir + ": " + strerror(getSystemErrno());
		throw ex;
	    }
	}
    }

    string file = dir + "/DB_CONFIG";
    ofstream configfile;
    configfile.open(file.c_str(), ios::out);
    if(!configfile)
    {
	rmdir(dir.c_str());

	DeploymentException ex;
	ex.reason = "couldn't create configuration file: " + file;
	throw ex;
    }

    for(PropertyDescriptorSeq::const_iterator p = dbEnv.properties.begin(); p != dbEnv.properties.end(); ++p)
    {
	if(!p->name.empty())
	{
	    configfile << p->name;
	    if(!p->value.empty())
	    {
		configfile << " " << p->value;
	    }
	    configfile << endl;
	}
    }
    configfile.close();

    return dir;
}

void 
ServerI::removeDbEnv(const DbEnvDescriptor& dbEnv, const string& moveTo, const ::Ice::Current&)
{
    string path;
    if(dbEnv.dbHome.empty())
    {
	path = _serversDir + name + "/dbs/" + dbEnv.name;
    }
    else
    {
	path = dbEnv.dbHome;
    }

    if(unlink((path + "/DB_CONFIG").c_str()) != 0)
    {
	Ice::Warning out(_traceLevels->logger);
	out << "couldn't remove file: " + path + "/DB_CONFIG: " + strerror(getSystemErrno());
    }

    //
    // If no db home directory was specified for this db env, we provided one. We need to cleanup
    // this directory now.
    //
    if(dbEnv.dbHome.empty())
    {
	if(!moveTo.empty())
	{
	    //
	    // Move the database environment directory to the given directory.
	    //
	    if(rename(path.c_str(), (moveTo + "/" + dbEnv.name).c_str()) != 0)
	    {
		Ice::Warning out(_traceLevels->logger);
		out << "couldn't rename directory " + path + " to " + moveTo + "/" + dbEnv.name + ": " + 
		    strerror(getSystemErrno());
	    }
	}
	else
	{
	    //
	    // Delete the database environment directory.
	    //
	    Ice::StringSeq files;
	    
#ifdef _WIN32
	    string pattern = path + "/*";
	    WIN32_FIND_DATA data;
	    HANDLE hnd = FindFirstFile(pattern.c_str(), &data);
	    if(hnd == INVALID_HANDLE_VALUE)
	    {
		// TODO: log a warning, throw an exception?
		return;
	    }
	    
	    do
	    {
		if((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
		{
		    files.push_back(path + "/" + data.cFileName);
		}
	    } 
	    while(FindNextFile(hnd, &data));
	    
	    FindClose(hnd);
#else
	    
	    DIR* dir = opendir(path.c_str());
	    if(dir == 0)
	    {
		// TODO: log a warning, throw an exception?
		return;
	    }
	    
	    // TODO: make the allocation/deallocation exception-safe
	    struct dirent* entry = static_cast<struct dirent*>(malloc(pathconf(path.c_str(), _PC_NAME_MAX) + 1));
	    
	    while(readdir_r(dir, entry, &entry) == 0 && entry != 0)
	    {
		string name = path + "/" + entry->d_name;
		struct stat buf;
		
		if(::stat(name.c_str(), &buf) != 0)
		{
		    if(errno != ENOENT)
		    {
			//
			// TODO: log error
			//
		    }
		}
		else if(S_ISREG(buf.st_mode))
		{
		    files.push_back(name);
		}
	    }
	    
	    free(entry);
	    closedir(dir);
#endif
	    
	    for(Ice::StringSeq::iterator p = files.begin(); p != files.end(); ++p)
	    {
		if(unlink(p->c_str()) != 0)
		{
		    //
		    // TODO: log error
		    //
		}
	    }
	    
	    if(rmdir(path.c_str()) != 0)
	    {
		Ice::Warning out(_traceLevels->logger);
		out << "couldn't remove directory: " + path + ": " + strerror(getSystemErrno());
	    }
	}
    }
}

void
ServerI::setProcess(const ::Ice::ProcessPrx& proc, const ::Ice::Current&)
{
    IceUtil::Monitor< ::IceUtil::Mutex>::Lock sync(*this);
    _process = proc;
    notifyAll();
}

void
ServerI::stopInternal(const Ice::Current& current)
{
    Ice::ProcessPrx process;
    {
	IceUtil::Monitor< ::IceUtil::Mutex>::Lock sync(*this);
	if(!_process && processRegistered)
	{
	    while(!_process)
	    {
		if(_state == Inactive || _state == Destroyed)
		{
		    //
		    // State changed to inactive or destroyed, the server
		    // has been correctly deactivated, we can return.
		    //
		    return;
		}

		//
		// Wait for the process to be set.
		//
		wait(); // TODO: timeout?
	    }
	}
	process = _process;
    }

    try
    {
	//
	// Deactivate the server.
	//
	_activator->deactivate(name, process);

	//
	// Wait for the server to be inactive (the activator monitors
	// the process and should notify us when it detects the
	// process termination by calling the terminated() method).
	//
	Lock sync(*this);

#ifndef NDEBUG
	ServerState oldState = _state;
#endif

	while(true)
	{
	    if(_state == Inactive || _state == Destroyed)
	    {
		//
		// State changed to inactive or destroyed, the server
		// has been correctly deactivated, we can return.
		//
		return;
	    }
	    
	    //
	    // Wait for a notification.
	    //
	    bool notify = timedWait(IceUtil::Time::seconds(_waitTime));
	    if(!notify)
	    {
		assert(oldState == _state);
		break;
	    }
	}

	if(_traceLevels->server > 1)
	{
	    Ice::Trace out(_traceLevels->logger, _traceLevels->serverCat);
	    out << "graceful server shutdown timed out, killing server `" << name << "'";
	}
    }
    catch(const Ice::Exception& ex)
    {
	Ice::Warning out(_traceLevels->logger);
	out << "graceful server shutdown failed, killing server `" << name << "':\n";
	out << ex;
    }

    
    //
    // The server is still not inactive, kill it.
    //
    try
    {
	_activator->kill(name);
    }
    catch(const Ice::SyscallException& ex)
    {
	Ice::Warning out(_traceLevels->logger);
	out << "deactivation failed for server `" << name << "':\n";
	out << ex;
	
	setState(Active, current);
    }
}

void
ServerI::setState(ServerState st, const Ice::Current& current)
{
    Lock sync(*this);

    //
    // Allow eviction of an inactive server object.
    //
    if(_state != Inactive && st == Inactive)
    {
	_factory->getServerEvictor()->release(current.id);
    }

    _state = st;

    if(_traceLevels->server > 1)
    {
	if(_state == Active)
	{
	    Ice::Trace out(_traceLevels->logger, _traceLevels->serverCat);
	    out << "changed server `" << name << "' state to `Active'";
	}
	else if(_state == Inactive)
	{
	    Ice::Trace out(_traceLevels->logger, _traceLevels->serverCat);
	    out << "changed server `" << name << "' state to `Inactive'";
	}
	else if(_state == Destroyed)
	{
	    Ice::Trace out(_traceLevels->logger, _traceLevels->serverCat);
	    out << "changed server `" << name << "' state to `Destroyed'";
	}
	else if(_traceLevels->server > 2)
	{
	    if(_state == Activating)
	    {
		Ice::Trace out(_traceLevels->logger, _traceLevels->serverCat);
		out << "changed server `" << name << "' state to `Activating'";
	    }
	    else if(_state == Deactivating)
	    {
		Ice::Trace out(_traceLevels->logger, _traceLevels->serverCat);
		out << "changed server `" << name << "' state to `Deactivating'";
	    }
	}
    }

    notifyAll();
}