summaryrefslogtreecommitdiff
path: root/cpp/src/IceGrid/Client.cpp
blob: 329d12dc2ab41141a2e1dd3acb44cf9b4f40c896 (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
// **********************************************************************
//
// 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 <IceUtil/DisableWarnings.h>
#include <IceUtil/Options.h>
#include <Ice/Application.h>
#include <Ice/SliceChecksums.h>
#include <IceGrid/Parser.h>
#include <IceGrid/FileParserI.h>
#include <IceGrid/Registry.h>
#include <Glacier2/Router.h>
#include <fstream>

using namespace std;
using namespace Ice;
using namespace IceGrid;

class SessionKeepAliveThread : public IceUtil::Thread, public IceUtil::Monitor<IceUtil::Mutex>
{
public:

    SessionKeepAliveThread(const AdminSessionPrx& session, long timeout) :
	_session(session),
        _timeout(IceUtil::Time::seconds(timeout)),
        _destroy(false)
    {
    }

    virtual void
    run()
    {
        Lock sync(*this);
        while(!_destroy)
        {
            timedWait(_timeout);
            if(_destroy)
            {
	        break;
	    }
            try
            {
                _session->keepAlive();
            }
            catch(const Ice::Exception&)
            {
		break;
            }
        }
    }

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

private:

    AdminSessionPrx _session;
    const IceUtil::Time _timeout;
    bool _destroy;
};
typedef IceUtil::Handle<SessionKeepAliveThread> SessionKeepAliveThreadPtr;

class Client : public Application
{
public:

    void usage();
    virtual int run(int, char*[]);

    string trim(const string&);
};

int
main(int argc, char* argv[])
{
    Client app;
    return app.main(argc, argv);
}

void
Client::usage()
{
    cerr << "Usage: " << appName() << " [options] [file...]\n";
    cerr <<	
	"Options:\n"
	"-h, --help           Show this message.\n"
	"-v, --version        Display the Ice version.\n"
	"-DNAME               Define NAME as 1.\n"
	"-DNAME=DEF           Define NAME as DEF.\n"
	"-UNAME               Remove any definition for NAME.\n"
	"-IDIR                Put DIR in the include file search path.\n"
	"-e COMMANDS          Execute COMMANDS.\n"
	"-d, --debug          Print debug messages.\n"
        "-s, --server         Start icegridadmin as a server (to parse XML files).\n"
        "-u, --username       Login with the given username.\n"
        "-p, --password       Login with the given password.\n"
        "-s, --ssl            Authenticate through SSL.\n"
        "-r, --routed         Login through a Glacier2 router.\n"
	;
}

int
Client::run(int argc, char* argv[])
{
    string cpp("cpp");
    string commands;
    bool debug;

    IceUtil::Options opts;
    opts.addOpt("h", "help");
    opts.addOpt("v", "version");
    opts.addOpt("D", "", IceUtil::Options::NeedArg, "", IceUtil::Options::Repeat);
    opts.addOpt("U", "", IceUtil::Options::NeedArg, "", IceUtil::Options::Repeat);
    opts.addOpt("I", "", IceUtil::Options::NeedArg, "", IceUtil::Options::Repeat);
    opts.addOpt("e", "", IceUtil::Options::NeedArg, "", IceUtil::Options::Repeat);
    opts.addOpt("u", "username", IceUtil::Options::NeedArg, "", IceUtil::Options::NoRepeat);
    opts.addOpt("p", "password", IceUtil::Options::NeedArg, "", IceUtil::Options::NoRepeat);
    opts.addOpt("S", "ssl");
    opts.addOpt("r", "routed");
    opts.addOpt("d", "debug");
    opts.addOpt("s", "server");
    opts.addOpt("R", "replica", IceUtil::Options::NeedArg, "", IceUtil::Options::NoRepeat);

    vector<string> args;
    try
    {
    	args = opts.parse(argc, (const char**)argv);
    }
    catch(const IceUtil::BadOptException& e)
    {
        cerr << e.reason << endl;
	usage();
	return EXIT_FAILURE;
    }

    if(opts.isSet("help"))
    {
	usage();
	return EXIT_SUCCESS;
    }
    if(opts.isSet("version"))
    {
	cout << ICE_STRING_VERSION << endl;
	return EXIT_SUCCESS;
    }

    if(opts.isSet("server"))
    {
	ObjectAdapterPtr adapter = communicator()->createObjectAdapterWithEndpoints("FileParser", "tcp -h localhost");
	adapter->activate();
	ObjectPrx proxy = adapter->add(new FileParserI, communicator()->stringToIdentity("FileParser"));
	cout << proxy << endl;

	communicator()->waitForShutdown();
	return EXIT_SUCCESS;
    }


    if(opts.isSet("D"))
    {
	vector<string> optargs = opts.argVec("D");
	for(vector<string>::const_iterator i = optargs.begin(); i != optargs.end(); ++i)
	{
	    cpp += " -D" + *i;
	}
    }
    if(opts.isSet("U"))
    {
	vector<string> optargs = opts.argVec("U");
	for(vector<string>::const_iterator i = optargs.begin(); i != optargs.end(); ++i)
	{
	    cpp += " -U" + *i;
	}
    }
    if(opts.isSet("I"))
    {
	vector<string> optargs = opts.argVec("I");
	for(vector<string>::const_iterator i = optargs.begin(); i != optargs.end(); ++i)
	{
	    cpp += " -I" + *i;
	}
    }
    if(opts.isSet("e"))
    {
	vector<string> optargs = opts.argVec("e");
	for(vector<string>::const_iterator i = optargs.begin(); i != optargs.end(); ++i)
	{
	    commands += *i + ";";
	}
    }
    debug = opts.isSet("debug");

    if(!args.empty() && !commands.empty())
    {
	cerr << appName() << ": `-e' option cannot be used if input files are given" << endl;
	usage();
	return EXIT_FAILURE;
    }

    string instanceName;
    if(communicator()->getDefaultLocator())
    {
	instanceName = communicator()->getDefaultLocator()->ice_getIdentity().category;	
    }
    else
    {
	instanceName = communicator()->getProperties()->getPropertyWithDefault("IceGrid.InstanceName", "IceGrid");
    }
    
    int timeout;
    AdminSessionPrx session;
    bool ssl = communicator()->getProperties()->getPropertyAsInt("IceGridAdmin.AuthenticateUsingSSL");
    if(opts.isSet("ssl"))
    {
    	ssl = true;
    }

    string id = communicator()->getProperties()->getProperty("IceGridAdmin.Username");
    if(!opts.optArg("username").empty())
    {
	id = opts.optArg("username");
    }
    string password = communicator()->getProperties()->getProperty("IceGridAdmin.Password");
    if(!opts.optArg("password").empty())
    {
	password = opts.optArg("password");
    }

    //
    // If a glacier2 router is configured, then set routed to true by
    // default.
    //
    bool routed = communicator()->getProperties()->getPropertyAsIntWithDefault(
	"IceGridAdmin.Routed", communicator()->getDefaultRouter());
    if(opts.isSet("routed"))
    {
    	routed = true;
    }
    string replica = communicator()->getProperties()->getProperty("IceGridAdmin.Replica");
    if(!opts.optArg("replica").empty())
    {
	replica = opts.optArg("replica");
    }


    try
    {
	if(routed)
	{
	    Glacier2::RouterPrx router = Glacier2::RouterPrx::checkedCast(communicator()->getDefaultRouter());
	    if(!router)
	    {
		cerr << argv[0] << ": configured router is not a Glacier2 router" << endl;
		return EXIT_FAILURE;
	    }

	    // Use SSL if available.
	    try
	    {
		router = Glacier2::RouterPrx::checkedCast(router->ice_secure(true));
	    }
	    catch(const Ice::NoEndpointException&)
	    {
	    }

	    if(ssl)
	    {
		session = AdminSessionPrx::uncheckedCast(router->createSessionFromSecureConnection());
		if(!session)
		{
		    cerr << argv[0]
			 << ": Glacier2 returned a null session, please set the Glacier2.SSLSessionManager property"
			 << endl;
		    return EXIT_FAILURE;
		}
	    }
	    else
	    {
		while(id.empty())
		{
		    cout << "user id: " << flush;
		    getline(cin, id);
		    id = trim(id);
		}
		
		if(password.empty())
		{
		    cout << "password: " << flush;
		    getline(cin, password);
		    password = trim(password);
		}
		    
		session = AdminSessionPrx::uncheckedCast(router->createSession(id, password));
		if(!session)
		{
		    cerr << argv[0]
			 << ": Glacier2 returned a null session, please set the Glacier2.SessionManager property"
			 << endl;
		    return EXIT_FAILURE;
		}
	    }
	    timeout = static_cast<int>(router->getSessionTimeout());
	}
	else
	{
	    Identity registryId;
	    registryId.category = instanceName;
	    registryId.name = "Registry";
	    if(!replica.empty() && replica != "Master")
	    {
		registryId.name += "-" + replica;
	    }

	    RegistryPrx registry;
	    try
	    {
		registry = RegistryPrx::checkedCast(
			communicator()->stringToProxy("\"" + communicator()->identityToString(registryId) + "\""));
		if(!registry)
		{
		    cerr << argv[0] << ": could not contact registry" << endl;
		    return EXIT_FAILURE;
		}
	    }
	    catch(const Ice::NotRegisteredException&)
	    {
		cerr << argv[0] << ": no active registry replica named `" << replica << "'" << endl;
		return EXIT_FAILURE;		
	    }

	    // Use SSL if available.
	    try
	    {
		registry = RegistryPrx::checkedCast(registry->ice_secure(true));
	    }
	    catch(const Ice::NoEndpointException&)
	    {
	    }

	    if(ssl)
	    {
		session = registry->createAdminSessionFromSecureConnection();
	    }
	    else
	    {
		while(id.empty())
		{
		    cout << "user id: " << flush;
		    getline(cin, id);
		    id = trim(id);
		}
		
		if(password.empty())
		{
		    cout << "password: " << flush;
		    getline(cin, password);
		    password = trim(password);
		}
		    
		session = registry->createAdminSession(id, password);
	    }
	    assert(session);
	    timeout = registry->getSessionTimeout();
	}
    }
    catch(const IceGrid::PermissionDeniedException& ex)
    {
	cout << "permission denied:\n" << ex.reason << endl;
	return EXIT_FAILURE;
    }

    SessionKeepAliveThreadPtr keepAlive = new SessionKeepAliveThread(session, timeout / 2);
    keepAlive->start();

    AdminPrx admin = session->getAdmin();

    Ice::SliceChecksumDict serverChecksums = admin->getSliceChecksums();
    Ice::SliceChecksumDict localChecksums = Ice::sliceChecksums();

    //
    // The following slice types are only used by the admin CLI.
    //
    localChecksums.erase("::IceGrid::FileParser");
    localChecksums.erase("::IceGrid::ParseException");
			 
    for(Ice::SliceChecksumDict::const_iterator q = localChecksums.begin(); q != localChecksums.end(); ++q)
    {
        Ice::SliceChecksumDict::const_iterator r = serverChecksums.find(q->first);
        if(r == serverChecksums.end())
        {
            cerr << appName() << ": server is using unknown Slice type `" << q->first << "'" << endl;
        }
        else if(q->second != r->second)
        {
            cerr << appName() << ": server is using a different Slice definition of `" << q->first << "'" << endl;
        }
    }

    ParserPtr p = Parser::createParser(communicator(), admin);

    int status = EXIT_SUCCESS;

    if(args.empty()) // No files given
    {
	if(!commands.empty()) // Commands were given
	{
	    int parseStatus = p->parse(commands, debug);
	    if(parseStatus == EXIT_FAILURE)
	    {
		status = EXIT_FAILURE;
	    }
	}
	else // No commands, let's use standard input
	{
	    p->showBanner();

	    int parseStatus = p->parse(stdin, debug);
	    if(parseStatus == EXIT_FAILURE)
	    {
		status = EXIT_FAILURE;
	    }
	}
    }
    else // Process files given on the command line
    {
	for(vector<string>::const_iterator i = args.begin(); i != args.end(); ++i)
	{
	    ifstream test(i->c_str());
	    if(!test)
	    {
		cerr << appName() << ": can't open `" << *i << "' for reading: " << strerror(errno) << endl;
		return EXIT_FAILURE;
	    }
	    test.close();
	    
	    string cmd = cpp + " " + *i;
#ifdef _WIN32
	    FILE* cppHandle = _popen(cmd.c_str(), "r");
#else
	    FILE* cppHandle = popen(cmd.c_str(), "r");
#endif
	    if(cppHandle == NULL)
	    {
		cerr << appName() << ": can't run C++ preprocessor: " << strerror(errno) << endl;
		return EXIT_FAILURE;
	    }
	    
	    int parseStatus = p->parse(cppHandle, debug);
	    
#ifdef _WIN32
	    _pclose(cppHandle);
#else
	    pclose(cppHandle);
#endif

	    if(parseStatus == EXIT_FAILURE)
	    {
		status = EXIT_FAILURE;
	    }
	}
    }

    keepAlive->destroy();
    keepAlive->getThreadControl().join();

    try
    {
	session->destroy();
    }
    catch(const Ice::Exception&)
    {
	// Ignore. If the registry has been shutdown this will cause
	// an exception.
    }

    return status;
}

string
Client::trim(const string& s)
{
    static const string delims = "\t\r\n ";
    string::size_type last = s.find_last_not_of(delims);
    if(last != string::npos)
    {
        return s.substr(s.find_first_not_of(delims), last+1);
    }
    return s;
}