File: ApplicationManager.cpp

package info (click to toggle)
qtop 2.3.4-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,976 kB
  • sloc: cpp: 40,477; makefile: 7
file content (535 lines) | stat: -rw-r--r-- 18,599 bytes parent folder | download | duplicates (3)
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
/******************************************************************************
*
* Copyright (C) 2002 Hugo PEREIRA <mailto: hugo.pereira@free.fr>
*
* This is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This software is distributed in the hope that it will be useful, but WITHOUT
* Any WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program.  If not, see <http://www.gnu.org/licenses/>.
*
*******************************************************************************/

#include "ApplicationManager.h"

#include "Client.h"
#include "CppUtil.h"
#include "Debug.h"
#include "Util.h"
#include "XmlOptions.h"

#include <QCoreApplication>
#include <algorithm>

namespace Server
{

    //_________________________________________
    ApplicationManager::ApplicationManager( QObject* parent ):
        QObject( parent ),
        Counter( "ApplicationManager" ),
        host_( QHostAddress::LocalHost ),
        port_( 8091 ),
        server_( new QTcpServer( this ) ),
        serverInitialized_( false ),
        client_( new Client( this ) ),
        state_( AwaitingReply )
    {

        Debug::Throw( "ApplicationManager::ApplicationManager.\n" );
        setApplicationName( "Generic Application" );

        connect( server_, SIGNAL(newConnection()), SLOT(_newConnection()) );

        // create new socket
        connect( &client_->socket(), SIGNAL(error(QAbstractSocket::SocketError)), SLOT(_error(QAbstractSocket::SocketError)) );
        connect( &client_->socket(), SIGNAL(connected()), SLOT(_startTimer()) );
        connect( &client_->socket(), SIGNAL(disconnected()), SLOT(_serverConnectionClosed()) );
        connect( client_, SIGNAL(commandAvailable(Server::ServerCommand)), SLOT(_process(Server::ServerCommand)) );

        if( !XmlOptions::get().contains( "SERVER_HOST" ) )
        { XmlOptions::get().setRaw( "SERVER_HOST", host_.toString(), true ); }

        if( !XmlOptions::get().contains( "SERVER_PORT" ) )
        { XmlOptions::get().set<int>( "SERVER_PORT", port_, true ); }

    }

    //_________________________________________
    ApplicationManager::~ApplicationManager()
    {}

    //_________________________________________
    CommandLineParser ApplicationManager::commandLineParser( CommandLineArguments arguments, bool ignoreWarnings )
    {

        Debug::Throw() << "ApplicationManager::commandLineParser" << endl;

        CommandLineParser out;
        out.setGroup( CommandLineParser::serverGroupName );
        out.registerFlag( CommandLineParser::Tag( "--replace", "-r" ), tr( "replace existing application instance with new one" ) );
        out.registerFlag( CommandLineParser::Tag( "--abort", "-q" ), tr( "exit existing instance" ) );
        out.registerFlag( "--no-server", tr( "ignore server mode. Run new application instance" ) );
        out.registerOption( "--server-host", tr( "string" ), tr( "use specified host for server communication" ) );
        out.registerOption( "--server-port", tr( "integer" ), tr( "use specified port for server communication" ) );

        if( !arguments.isEmpty() )
        { out.parse( arguments, ignoreWarnings ); }

        return out;

    }

    //_____________________________________________________
    void ApplicationManager::initialize( CommandLineArguments arguments )
    {

        Debug::Throw( "ApplicationManager::init.\n" );

        // store arguments
        arguments_ = arguments;

        // overwrite host from command line arguments
        CommandLineParser parser( commandLineParser( arguments_ ) );
        if( parser.hasOption( "--server-host" ) )
        {

            QString host( parser.option( "--server-host" ) );
            host_ = QHostAddress( host );

        } else host_ = QHostAddress( QString( XmlOptions::get().raw( "SERVER_HOST" ) ) );

        // overwrite port from command line arguments
        if( parser.hasOption( "--server-port" ) )
        {

            int port( parser.option( "--server-port" ).toUInt() );
            port_ = port;

        } else port_ = XmlOptions::get().get<int>( "SERVER_PORT" );

        Debug::Throw() << "ApplicationManager::initialize - port: " << port_ << endl;
        _initializeClient();

        Debug::Throw( "ApplicationManager::init. done.\n" );

    }

    //_____________________________________________________
    void ApplicationManager::setApplicationName( const QString& name )
    {
        Debug::Throw() << "ApplicationManager::setApplicationName - " << name << endl;
        id_ = ApplicationId( name );
        id_.setProcessId( QCoreApplication::applicationPid() );
    }

    //______________________________________________________________
    void ApplicationManager::timerEvent(QTimerEvent *event)
    {

        if (event->timerId() == timer_.timerId() )
        {

            Debug::Throw( "ApplicationManager::timerEvent.\n" );
            timer_.stop();

            // the timer is triggered only when the client is connected
            // its expiration means it could not recieve acceptation/denial
            // from the server it is connected to.
            // the application is then set to Alive
            if( state_ == AwaitingReply && setState( Alive ) )
            { emit commandRecieved( ServerCommand( id_, ServerCommand::Accepted ) ); }

        }

        return QObject::timerEvent( event );

    }

    //_____________________________________________________
    ApplicationManager::ClientMap::iterator ApplicationManager::_register( const ApplicationId& id, Client* client, bool forced )
    {
        Debug::Throw( "ApplicationManager::_register.\n" );

        if( forced ) return acceptedClients_.insert( id, client );
        else {

            ClientMap::iterator iter( acceptedClients_.find( id ) );
            SameClientFTor sameClientFTor( client );
            if( iter == acceptedClients_.end() && std::find_if( acceptedClients_.begin(), acceptedClients_.end(), sameClientFTor ) == acceptedClients_.end() )
            {

                return acceptedClients_.insert( id, client );

            } else return iter;

        }
    }

    //_____________________________________________________
    void ApplicationManager::_redirect( ServerCommand command, Client* sender )
    {

        Debug::Throw() << "ApplicationManager::_redirect -"
            << " application:" << command.id().name()
            << " command: " << command.commandName()
            << endl;

        CommandLineParser parser( commandLineParser( command.arguments() ) );
        switch( command.command() )
        {

            case ServerCommand::Unlock:
            {

                // unlock request. Clear list of registered applications
                acceptedClients_.clear();
                return;

            }

            case ServerCommand::Request:
            {

                // server request

                // get existing client
                ClientMap::iterator clientIterator( _register( command.id(), sender ) );
                if( clientIterator == acceptedClients_.end() ) return;

                Client* existingClient( clientIterator.value() );

                if( sender == existingClient )
                {

                    if( parser.hasFlag( "--abort" ) )
                    {

                        // abort existing client
                        sender->sendCommand( ServerCommand( command.id(), ServerCommand::Denied ) );
                        _broadcast( ServerCommand( command.id(), ServerCommand::Identify ), sender );
                        _register( command.id(), sender, true );

                    } else {

                        // tell client it is accepted
                        sender->sendCommand( ServerCommand( command.id(), ServerCommand::Accepted ) );
                        _broadcast( ServerCommand( command.id(), ServerCommand::Identify ), sender );

                    }

                } else if( parser.hasFlag( "--replace" ) ) {

                    // tell existing client to die
                    ServerCommand abortCommand( command.id(), ServerCommand::Abort );
                    existingClient->sendCommand( abortCommand );
                    _broadcast( ServerCommand( command.id(), ServerCommand::Killed ), existingClient );

                    // tell new client it is accepted
                    sender->sendCommand( ServerCommand( command.id(), ServerCommand::Accepted ) );
                    _broadcast( ServerCommand( command.id(), ServerCommand::Identify ), sender );
                    _register( command.id(), sender, true );

                    // update iterator pid
                    const_cast<ApplicationId*>( &clientIterator.key() )->setProcessId( command.id().processId() );

                } else if( parser.hasFlag( "--abort" ) ) {

                    // tell existing client to die
                    ServerCommand abortCommand( command.id(), ServerCommand::Abort );
                    existingClient->sendCommand( abortCommand );
                    _broadcast( ServerCommand( command.id(), ServerCommand::Killed ), existingClient );

                    // tell new client it is denied too
                    sender->sendCommand( ServerCommand( command.id(), ServerCommand::Denied ) );
                    _broadcast( ServerCommand( command.id(), ServerCommand::Identify ), sender );
                    _register( command.id(), sender, true );

                } else {

                    // tell existing client to raise itself
                    ServerCommand raiseCommand( command.id(), ServerCommand::Raise );
                    raiseCommand.setArguments( command.arguments() );
                    existingClient->sendCommand( raiseCommand );

                }

                return;
            }

            case ServerCommand::Alive:
            {
                // client exist and is alive. Deny current
                _broadcast( ServerCommand( command.id(), ServerCommand::Denied ) );
                return;

            }

            case ServerCommand::Identify:
            {

                // identify the server
                sender->sendCommand( ServerCommand( id_, ServerCommand::IdentifyServer ) );

                /*
                identification request. Loop over registered clients
                send the associated Identity to the sender
                */

                for( auto&& it=acceptedClients_.begin(); it!=acceptedClients_.end(); it++ )
                { sender->sendCommand( ServerCommand( it.key(), ServerCommand::Identify ) ); }

                return;
            }

            default:
            {
                // redirect unrecognized message to all clients but the sender
                _broadcast( command, sender );
                return;
            }

        }

    }

    //_____________________________________________________
    void ApplicationManager::_broadcast( ServerCommand command, Client* sender )
    {

        Debug::Throw() << "ApplicationManager::_Broadcast - id: " << command.id().name() << " command: " << command.commandName() << endl;
        for( auto& client:connectedClients_ )
        { if( client != sender ) client->sendCommand( command ); }

    }

    //_____________________________________________________
    void ApplicationManager::_newConnection()
    {
        Debug::Throw( "ApplicationManager::_newConnection.\n" );
        while( server_->hasPendingConnections() )
        {
            // create client from pending connection
            Client *client( new Client( this, server_->nextPendingConnection() ) );
            connect( client, SIGNAL(commandAvailable(Server::ServerCommand)), SLOT(_redirect(Server::ServerCommand)) );
            connect( &client->socket(), SIGNAL(disconnected()), SLOT(_clientConnectionClosed()) );
            connectedClients_ << client;
        }

    }

    //_____________________________________________________
    void ApplicationManager::_serverConnectionClosed()
    {
        Debug::Throw( "ApplicationManager::_serverConnectionClosed - lost connection to server.\n" );
        serverInitialized_ = false;
        initialize();
    }

    //_____________________________________________________
    void ApplicationManager::_clientConnectionClosed()
    {

        Debug::Throw( "ApplicationManager::_clientConnectionClosed - client has disconnected.\n" );

        // look for disconnected clients in client map
        {
            ClientMap::iterator iter;
            while( ( iter = std::find_if(  acceptedClients_.begin(), acceptedClients_.end(), SameStateFTor( QAbstractSocket::UnconnectedState ) )  ) != acceptedClients_.end() )
            {

                // broadcast client as dead
                _broadcast( ServerCommand( iter.key(), ServerCommand::Killed ), iter.value() );

                // erase from map of accepted clients
                acceptedClients_.erase( iter );

            }
        }

        // look for disconnected clients in connected clients list
        {
            ClientList::iterator iter;
            while( ( iter = std::find_if( connectedClients_.begin(), connectedClients_.end(), SameStateFTor( QAbstractSocket::UnconnectedState ) ) ) != connectedClients_.end() )
            {
                (*iter)->deleteLater();
                connectedClients_.erase( iter );
            }
        }

        return;

    }

    //_____________________________________________________
    void ApplicationManager::_error( QAbstractSocket::SocketError error )
    {

        Debug::Throw() << "ApplicationManager::_error - error:" << client_->socket().errorString() << endl;

        if( error == QAbstractSocket::ConnectionRefusedError )
        {
            // stop timeout signal
            timer_.stop();

            // do nothing if client has already been denied connection
            if( state_ == Dead ) return;

            // try initialize server
            if( !serverInitialized_ )
            {

                _initializeServer();
                _initializeClient();

            } else if( setState( Alive  ) ) {

                emit commandRecieved( ServerCommand( id_, ServerCommand::Accepted ) );

            }

        } else {
            Debug::Throw() << "ApplicationManager::_error - unhandled error:" << client_->socket().errorString() << endl;
        }

        return;
    }

    //_____________________________________________________
    void ApplicationManager::_redirect( ServerCommand command )
    {

        Debug::Throw( "Application::_redirect.\n" );

        ClientList::iterator iter( std::find_if(  connectedClients_.begin(), connectedClients_.end(), Client::SameIdFTor( command.clientId() ) ) );
        Q_ASSERT( iter != connectedClients_.end() );
        _redirect( command, *iter );

        return;
    }


    //_____________________________________________________
    void ApplicationManager::_process( ServerCommand command )
    {

        Debug::Throw() << "ApplicationManager::_process -"
            << "  app:" << command.id().name()
            << " command: " << command.commandName()
            << endl;

        Q_ASSERT( client_->id() == command.clientId() );

        // check command id is valid
        if( !command.id().isValid() ) return;

        // check id match
        if( !( command.id() == id() ) ) return;

        switch( command.command() )
        {

            case ServerCommand::Raise:
            if( state_ == Alive )
            {

                client_->sendCommand( ServerCommand( id_, ServerCommand::Alive ) );
                emit commandRecieved( command );
                return;

            } else break;

            case ServerCommand::Denied:
            if( state_ == AwaitingReply )
            {
                timer_.stop();
                if( setState( Dead ) ) emit commandRecieved( command );
                return;
            } else break;


            case ServerCommand::Abort:
            if( state_ == Alive )
            {
                timer_.stop();
                if( setState( Dead ) ) emit commandRecieved( command );
                return;
            } else break;

            case ServerCommand::Accepted:
            if( state_ == AwaitingReply )
            {
                timer_.stop();
                if( setState( Alive ) ) emit commandRecieved( command );
                return;
            } else break;

            default:
            {
                emit commandRecieved( command );
                break;
            }

        }

    }

    //__________________________________________________________________________
    bool ApplicationManager::_initializeServer()
    {

        Debug::Throw( "ApplicationManager::_initializeServer.\n" );

        serverInitialized_ = true;

        // connect server to port
        return server_->listen( host_, port_ );

    }


    //__________________________________________________________________________
    bool ApplicationManager::_initializeClient()
    {

        Debug::Throw( "ApplicationManager::_initializeClient.\n" );
        Debug::Throw() << "ApplicationManager::_initializeClient - connecting to host: " << host_.toString() << " port: " << port_ << endl;

        // connect client to port
        client_->socket().abort();
        client_->socket().connectToHost( host_, port_ );

        // emit initialization signal
        emit initialized();
        setState( AwaitingReply );

        // create request command
        ServerCommand command( id_, ServerCommand::Request );

        // add command line arguments if any
        command.setArguments( arguments_ );

        // send request command
        client_->sendCommand( command );

        return true;

    }

    //__________________________________________________________________________
    void ApplicationManager::_startTimer()
    {
        // time out delay (for existing server to reply)
        // one should really start the timer only when the client is connected
        int timeout_delay( XmlOptions::get().contains( "SERVER_TIMEOUT_DELAY" ) ? XmlOptions::get().get<int>( "SERVER_TIMEOUT_DELAY" ) : 2000 );
        timer_.start( timeout_delay, this );
    }

}