summaryrefslogtreecommitdiff
path: root/cpp/src/IcePack/ComponentDeployer.cpp
blob: b267db0f20403be6c14eb6202e65aa51466b3267 (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
// **********************************************************************
//
// Copyright (c) 2001
// Mutable Realms, Inc.
// Huntsville, AL, USA
//
// All Rights Reserved
//
// **********************************************************************

#include <Ice/Ice.h>
#include <Ice/Locator.h>

#include <IcePack/ComponentDeployer.h>
#include <IcePack/Admin.h>

#include <Yellow/Yellow.h>

#include <parsers/SAXParser.hpp>
#include <sax/HandlerBase.hpp>

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

#include <stack>
#include <iterator>
#include <fstream>

using namespace std;
using namespace IcePack;

void IcePack::incRef(Task* p) { p->__incRef(); }
void IcePack::decRef(Task* p) { p->__decRef(); }

namespace IcePack
{

static string
toString(const XMLCh* ch)
{
    char* t = XMLString::transcode(ch);
    string s(t);
    delete[] t;
    return s;
}

//
// Create a directory. 
//
class CreateDirectory : public Task
{
public:

    CreateDirectory(const string& name)
	: _name(name)
    {
    }

    virtual void
    deploy()
    {
	if(mkdir(_name.c_str(), 0755) != 0)
	{
	    cerr << "Can't create directory: " << _name << endl;

	    Ice::SystemException ex(__FILE__, __LINE__);
	    ex.error = getSystemErrno();
	    throw ex;
	}
    }

    virtual void
    undeploy()
    {
	if(rmdir(_name.c_str()) != 0)
	{
	    cerr << "Can't remove directory: " << _name << endl;

	    Ice::SystemException ex(__FILE__, __LINE__);
	    ex.error = getSystemErrno();
	    throw ex;
	}
    }
    
private:

    string _name;
};

//
// Generate a configuration file from a property set.
//
class GenerateConfiguration : public Task
{
    class WriteConfigProperty : public unary_function<Ice::PropertyDict::value_type, string>
    {
    public:

	string 
	operator()(const Ice::PropertyDict::value_type& p) const
	{
		return p.first + "=" + p.second;
	}
    };

public:

    GenerateConfiguration(const string& file, const Ice::PropertiesPtr& properties) :
	_file(file),
	_properties(properties)
    {
    }

    virtual void
    deploy()  
    {
	ofstream configfile;
	configfile.open(_file.c_str(), ios::out);
	if(!configfile)
	{
	    cerr << "Can't create configuration file: " << _file << endl;
	    Ice::SystemException ex(__FILE__, __LINE__);
	    throw ex;
	}
	
	Ice::PropertyDict props = _properties->getPropertiesForPrefix("");
	transform(props.begin(), props.end(), ostream_iterator<string>(configfile,"\n"), WriteConfigProperty());
	configfile.close();
    }

    virtual void
    undeploy()
    {
	if(unlink(_file.c_str()) != 0)
	{
	    cerr << "Can't remove configuration file: " << _file << endl;

	    Ice::SystemException ex(__FILE__, __LINE__);
	    ex.error = getSystemErrno();
	    throw ex;	    
	}
    }

private:

    string _file;
    Ice::PropertiesPtr _properties;
};

//
// Register an offer with the yellow page service.
//
class RegisterOffer : public Task
{
public:

    RegisterOffer(const Yellow::AdminPrx& admin, const string& offer, const Ice::ObjectPrx& proxy) :
	_admin(admin),
	_offer(offer),
	_proxy(proxy)
    {
    }

    virtual void
    deploy()
    {
	_admin->add(_offer, _proxy);
    }

    virtual void
    undeploy()
    {
	try
	{
	    _admin->remove(_offer, _proxy);
	}
	catch(const Yellow::NoSuchOfferException&)
	{
	    //
	    // TODO: The offer doesn't exist anymore so no need to
	    // worry about removing it. We should print a warning
	    // though.
	    //
	}	
    }

private:

    Yellow::AdminPrx _admin;
    string _offer;
    Ice::ObjectPrx _proxy;
};

}

IcePack::ComponentErrorHandler::ComponentErrorHandler(ComponentDeployer& deployer) :
    _deployer(deployer)
{
}

void
IcePack::ComponentErrorHandler::warning(const SAXParseException& exception)
{
    string s = toString(exception.getMessage());
    cerr << "warning: " << s << endl;
}

void
IcePack::ComponentErrorHandler::error(const SAXParseException& exception)
{
    string s = toString(exception.getMessage());
    cerr << "error: " << s << endl;
}

void
IcePack::ComponentErrorHandler::fatalError(const SAXParseException& exception)
{
    string s = toString(exception.getMessage());
    cerr << "fatal:" << s << endl;
}

void
IcePack::ComponentErrorHandler::resetErrors()
{
}

IcePack::ComponentDeployHandler::ComponentDeployHandler(ComponentDeployer& deployer) :
    _deployer(deployer)
{
}

void
IcePack::ComponentDeployHandler::characters(const XMLCh *const chars, const unsigned int length)
{
    _elements.top().assign(toString(chars));
}

void
IcePack::ComponentDeployHandler::startElement(const XMLCh *const name, AttributeList &attrs)
{
    _elements.push("");

    string str = toString(name);

    if(str == "property")
    {
	string value = getAttributeValueWithDefault(attrs, "value", "");
	if(value.empty())
	{
	    value = getAttributeValueWithDefault(attrs, "location", "");
	    if(!value.empty() && value[0] != '/')
	    {
		value = _deployer.substitute("${basedir}/") + value;
	    }
	}
	_deployer.addProperty(getAttributeValue(attrs, "name"), value);
    }
    else if(str == "adapter")
    {
	_adapter = getAttributeValue(attrs, "name");
    }
    else if(str == "offer")
    {
	_deployer.addOffer(getAttributeValue(attrs, "interface"), _adapter, getAttributeValue(attrs, "identity"));
    }
}

void
IcePack::ComponentDeployHandler::endElement(const XMLCh *const name)
{
    _elements.pop();

    string str = toString(name);

    if(str == "adapter")
    {
	_adapter = "";
    }
}

string
IcePack::ComponentDeployHandler::getAttributeValue(const AttributeList& attrs, const string& name) const
{
    XMLCh* n = XMLString::transcode(name.c_str());
    const XMLCh* value = attrs.getValue(n);
    delete[] n;
    
    if(value == 0)
    {
	cerr << "Missing attribute '" << name << "'" << endl;
	return "";
    }

    return _deployer.substitute(toString(value));
}

string
IcePack::ComponentDeployHandler::getAttributeValueWithDefault(const AttributeList& attrs, const string& name, 
							      const string& def) const
{
    XMLCh* n = XMLString::transcode(name.c_str());
    const XMLCh* value = attrs.getValue(n);
    delete[] n;
    
    if(value == 0)
    {
	return _deployer.substitute(def);
    }
    else
    {
	return _deployer.substitute(toString(value));
    }
}

string
IcePack::ComponentDeployHandler::toString(const XMLCh* ch) const
{
    return IcePack::toString(ch);
}

string
IcePack::ComponentDeployHandler::elementValue() const
{
    return _elements.top();
}

IcePack::ComponentDeployer::ComponentDeployer(const Ice::CommunicatorPtr& communicator) :
    _communicator(communicator),
    _properties(Ice::createProperties())
{
    string serversPath = _communicator->getProperties()->getProperty("IcePack.Data");
    assert(!serversPath.empty());
    _variables["datadir"] = serversPath + (serversPath[serversPath.length() - 1] == '/' ? "" : "/") + "servers";
}

void 
IcePack::ComponentDeployer::parse(const string& xmlFile, ComponentDeployHandler& handler)
{
    _error = 0;

    //
    // Setup the base directory for this deploment descriptor to the
    // location of the desciptor file.
    //
    string::size_type end = xmlFile.find_last_of('/');
    if(end != string::npos)
    {
	_variables["basedir"] = xmlFile.substr(0, end);
    }

    if(_variables["basedir"].empty())
    {
	_variables["basedir"] = ".";
    }
    
    SAXParser* parser = new SAXParser;
    parser->setValidationScheme(SAXParser::Val_Never);

    try
    {
	ComponentErrorHandler err(*this);
	parser->setDocumentHandler(&handler);
	parser->setErrorHandler(&err);
	parser->parse(xmlFile.c_str());
    }
    catch(const XMLException& e)
    {
	cerr << "XMLException: " << toString(e.getMessage()) << endl;
	_error++;
    }
    int rc = parser->getErrorCount();
    delete parser;

    if(_error > 0 || rc > 0)
    {
	throw DeploymentException();
    }    
}

void
IcePack::ComponentDeployer::deploy()
{
    vector<TaskPtr>::iterator p;
    for(p = _tasks.begin(); p != _tasks.end(); p++)
    {
	try
	{
	    (*p)->deploy();
	}
	catch(const DeploymentException& ex)
	{
	    cerr << "Deploy: " << ex << endl;
	    undeployFrom(p);
	    throw;
	}
	catch(const Ice::SystemException& ex)
	{
	    cerr << "Deploy: " << ex << endl;
	    undeployFrom(p);
	    throw DeploymentException();;
	}
    }
}

void
IcePack::ComponentDeployer::undeploy()
{
    for(vector<TaskPtr>::reverse_iterator p = _tasks.rbegin(); p != _tasks.rend(); p++)
    {
	try
	{
	    (*p)->undeploy();
	}
	catch(const DeploymentException& ex)
	{
	    //
	    // TODO: we probably need to log the failure to execute
	    // this task so that the use can take necessary steps to
	    // ensure it's correctly undeployed.
	    //
	    cerr << "Undeploy: " << ex << endl;
	}
	catch(const Ice::SystemException& ex)
	{
	    cerr << "Undeploy: " << ex << endl;
	}
    }
}

void
IcePack::ComponentDeployer::createDirectory(const string& name)
{
    string path = _variables["datadir"] + (name.empty() || name[0] == '/' ? name : "/" + name);
    _tasks.push_back(new CreateDirectory(path));
}

void
IcePack::ComponentDeployer::createConfigFile(const string& name)
{
    assert(!name.empty());
    _configFile = _variables["datadir"] + (name[0] == '/' ? name : "/" + name);
    _tasks.push_back(new GenerateConfiguration(_configFile, _properties));
}

void
IcePack::ComponentDeployer::addProperty(const string& name, const string& value)
{
    _properties->setProperty(name, value);
}

void
IcePack::ComponentDeployer::addOffer(const string& offer, const string& adapter, const string& identity)
{
    assert(!adapter.empty());

    Yellow::AdminPrx yellowAdmin;    
    try
    {
	//
	// TODO: Find a better way to bootstrap the yellow service. We
	// need to set the locator on the proxy here, because the
	// communicator doesn't have a default locator since it's the
	// locator communicator...
	//
	Ice::ObjectPrx object = _communicator->stringToProxy(
	    _communicator->getProperties()->getProperty("IcePack.Yellow.Admin"));

	if(!object)
	{	
	    cerr << "IcePack.Yellow.Admin is not set, can't register the offer '" << offer << "'" << endl;
	    _error++;
	    return;	
	}

	Ice::LocatorPrx locator = Ice::LocatorPrx::uncheckedCast(
	    _communicator->stringToProxy(_communicator->getProperties()->getProperty("Ice.Default.Locator")));

	yellowAdmin = Yellow::AdminPrx::checkedCast(object->ice_locator(locator));
    }
    catch(Ice::LocalException& ex)
    {
	cerr << "Couldn't contact the yellow service to register the offer '" << offer << "':" << ex << endl;
	_error++;
	return;	
    }

    Ice::ObjectPrx object = _communicator->stringToProxy(identity + "@" + adapter);
    assert(object);
    
    _tasks.push_back(new RegisterOffer(yellowAdmin, offer, object));
}

//
// Substitute variables with their values.
//
string
IcePack::ComponentDeployer::substitute(const string& v) const
{
    string value(v);
    string::size_type beg;
    string::size_type end = 0;

    while((beg = value.find("${")) != string::npos)
    {
	end = value.find("}", beg);
	
	if(end == string::npos)
	{
	    cerr << "Malformed variable name in : " << value << endl;
	    break; // Throw instead?
	}

	
	string name = value.substr(beg + 2, end - beg - 2);
	map<string, string>::const_iterator p = _variables.find(name);
	if(p == _variables.end())
	{
	    cerr << "Unknown variable: " << name << endl;
	    break; // Throw instead?
	}

	value.replace(beg, end - beg + 1, p->second);
    }

    return value;
}

void
IcePack::ComponentDeployer::undeployFrom(vector<TaskPtr>::iterator p)
{
    if(p != _tasks.begin())
    {
	for(vector<TaskPtr>::reverse_iterator q(p); q != _tasks.rend(); q++)
	{
	    try
	    {
		(*q)->undeploy();
	    }
	    catch(DeploymentException& ex)
	    {
		cerr << "Undeploy: " << ex << endl;
	    }
	    catch(Ice::SystemException& ex)
	    {
		cerr << "Undeploy: " << ex << endl;
	    }
	}
    }
}