process.cpp 15.7 KB
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


#include <QBuffer>
#include <QCoreApplication>
#include <QLocalServer>
#include <QLocalSocket>
#include <QMutex>
#include <QProcess>
#include <QUuid>
#include <QWaitCondition>

#include "openbr_internal.h"
#include "openbr/core/opencvutils.h"

using namespace cv;

namespace br
{

class CommunicationManager : public QObject
{
    Q_OBJECT
public:
    QThread * basis;
    CommunicationManager()
    {
        basis = new QThread;
        basis->moveToThread(QCoreApplication::instance()->thread());
        moveToThread(basis);
        server.moveToThread(basis);
        outbound.moveToThread(basis);

        // signals for our sever
        connect(this, SIGNAL(pulseEndThread()), basis, SLOT(quit() ));
        connect(&server, SIGNAL(newConnection()), this, SLOT(receivedConnection() ));
        connect(this, SIGNAL(pulseStartServer(QString)), this, SLOT(startServerInternal(QString)), Qt::BlockingQueuedConnection);
        connect(this, SIGNAL(pulseOutboundConnect(QString)), this, SLOT(startConnectInternal(QString) ), Qt::BlockingQueuedConnection);


        // internals, cause work to be done by the main thread because reasons.
        connect(this, SIGNAL(pulseSignal()), this, SLOT(sendSignalInternal()), Qt::BlockingQueuedConnection);
        connect(this, SIGNAL(pulseReadSignal() ), this, SLOT(readSignalInternal()), Qt::BlockingQueuedConnection);
        connect(this, SIGNAL(pulseReadSerialized() ), this, SLOT(readSerializedInternal()), Qt::BlockingQueuedConnection); 
        connect(this, SIGNAL(pulseSendSerialized() ), this, SLOT(sendSerializedInternal() ), Qt::BlockingQueuedConnection);
        connect(this, SIGNAL(pulseShutdown() ), this, SLOT(shutdownInternal() ), Qt::BlockingQueuedConnection);

        // signals for our outbound connection
        connect(&outbound, SIGNAL(connected() ), this, SLOT(outboundConnected() ));
        connect(&outbound, SIGNAL(disconnected() ), this, SLOT(outboundDisconnected() ));

        connect(&outbound, SIGNAL(error(QLocalSocket::LocalSocketError)), this, SLOT(outboundConnectionError(QLocalSocket::LocalSocketError) ) );
        connect(&outbound, SIGNAL(stateChanged(QLocalSocket::LocalSocketState)), this, SLOT(outboundStateChanged(QLocalSocket::LocalSocketState) ) );

        inbound = NULL;
        basis->start();
    }

    ~CommunicationManager()
    {

    }

    void shutDownThread()
    {
        emit pulseEndThread();
        basis->quit();
        basis->wait();
        delete basis;
    }

    enum SignalType
    {
        INPUT_AVAILABLE,
        OUTPUT_AVAILABLE,
        SHOULD_END
    };


public slots:
    // matching server signals
    void receivedConnection()
    {
        inbound = server.nextPendingConnection();
        connect(inbound, SIGNAL(disconnected() ), this, SLOT(inboundDisconnected() ));
        connect(inbound, SIGNAL(error(QLocalSocket::LocalSocketError)), this, SLOT(inboundConnectionError(QLocalSocket::LocalSocketError) ) );
        connect(inbound, SIGNAL(stateChanged(QLocalSocket::LocalSocketState)), this, SLOT(inboundStateChanged(QLocalSocket::LocalSocketState) ) );

        receivedWait.wakeAll();
    }

    // matching outbound socket signals

    // Oh boy.
    void outboundConnected()
    {
        outboundWait.wakeAll();
    }

    // Oh no!
    void outboundDisconnected()
    {
        //qDebug() << key << " outbound socket has disconnected";
    }

    // informative.
    void outboundConnectionError(QLocalSocket::LocalSocketError socketError)
    {
        (void) socketError;
        //qDebug() << key << " outbound socket error " << socketError;
    }

    void outboundStateChanged(QLocalSocket::LocalSocketState socketState)
    {
        (void) socketState;
        //qDebug() << key << " outbound socket state changed to " << socketState;
    }

    // matching inbound socket signals
    void inboundDisconnected()
    {
        //qDebug() << key << " inbound socket has disconnected";
    }

    void inboundConnectionError(QLocalSocket::LocalSocketError socketError)
    {
        (void) socketError;
        //qDebug() << key << " inbound socket error " << socketError;
    }

    void inboundStateChanged(QLocalSocket::LocalSocketState socketState)
    {
        (void) socketState;
        //qDebug() << key << " inbound socket state changed to " << socketState;
    }

    void startServerInternal(QString serverName)
    {
         if (!server.isListening()) {
            bool listen_res = server.listen(serverName);
            if (!listen_res)
                qDebug() << key << " Failed to start server at " << serverName;
         }
    }

    void sendSignalInternal()
    {
        SignalType signal=  sendType;
        qint64 signal_wrote = outbound.write((char *) &signal, sizeof(signal));
        if (signal_wrote != sizeof(signal))
            qDebug() << key << " inconsistent signal size";

        bool res = outbound.waitForBytesWritten(-1);
        if (!res)
            qDebug() << key << " failed to wait for bytes written in signal size";
    }

    void readSignalInternal()
    {
        while (inbound->bytesAvailable() < qint64(sizeof(readSignal)) ) {
            bool size_ready = inbound->waitForReadyRead(-1);
            if (!size_ready)
            {
                qDebug("Failed to received object size in signal!");
            }
        }

        qint64 signalBytesRead = inbound->read((char *) &readSignal, sizeof(readSignal));
        if (signalBytesRead != sizeof(readSignal))
            qDebug("Inconsistent signal size read!");

        if (readSignal == SHOULD_END)
        {
            server.close();
            outbound.abort();
            inbound->abort();
        }
    }

    void sendSerializedInternal()
    {
        qint64 serializedSize = writeArray.size();
        qint64 size_wrote = outbound.write((char *) &serializedSize, sizeof(serializedSize));
        if (size_wrote != sizeof(serializedSize)) {
            qDebug() << key << "inconsistent size sent in send data!";
            return;
        }
        bool res = outbound.waitForBytesWritten(-1);
        
        if (!res) {
            qDebug() << key << " wait for bytes failed!";
            return;
        }

        qint64 data_wrote = outbound.write(writeArray.data(), serializedSize);
        if (data_wrote != serializedSize)
            qDebug() << key << " inconsistent data written!";

        while (outbound.bytesToWrite() > 0) {
            bool write_res = outbound.waitForBytesWritten(-1);
            if (!write_res) {
                qDebug() << key << " wait for bytes failed!";
                return;
            }
        }

        return;

    }

    void readSerializedInternal()
    {
        qint64 bufferSize;
        while (inbound->bytesAvailable() < qint64(sizeof(bufferSize))) {
            bool size_ready = inbound->waitForReadyRead(-1);
            if (!size_ready)
            {
                qDebug() << key << " Failed to received object size in read data!";
                qDebug() << key << "inbound status: " << inbound->state() << " error: " << inbound->errorString();
                return;
            }
        }
        qint64 sizeBytesRead = inbound->read((char *) &bufferSize, sizeof(bufferSize));
        if (sizeBytesRead != sizeof(bufferSize)) {
            qDebug("failed to read size of buffer!");
            return;
        }

        // allocate the input buffer
        readArray.resize(bufferSize);

        // read the data, we may get it in serveral bursts
        qint64 arrayPosition = 0;
        while (arrayPosition < bufferSize) {
            if (!inbound->bytesAvailable()) {
                bool ready_res = inbound->waitForReadyRead(-1);

                if (!ready_res) {
                    qDebug() << key << "failed to wait for data!";
                    return;
                }
            }

            // how many bytes do we still need?
            qint64 bytes_remaining = bufferSize - arrayPosition;

            if (bytes_remaining < inbound->bytesAvailable() )
            {
                qDebug() << key << "!!!excessive bytes received";
            }
            arrayPosition += inbound->read(readArray.data()+arrayPosition, qMin(inbound->bytesAvailable(), bytes_remaining));
        }
        if (arrayPosition != bufferSize)
            qDebug() << key <<  "Read wrong size object!";

    }

    void shutdownInternal()
    {
        outbound.abort();
        inbound->abort();
        server.close();
    }


    void startConnectInternal(QString remoteName)
    {
        outbound.connectToServer(remoteName);
    }


signals:
    void pulseStartServer(QString serverName);
    void pulseSignal();
    void pulseReadSignal();
    void pulseReadSerialized();
    void pulseSendSerialized();
    void pulseShutdown();
    void pulseOutboundConnect(QString serverName);
    void pulseEndThread();


public:
    QByteArray readArray;
    QByteArray writeArray;

    SignalType readSignal;
    QMutex receivedLock;
    QWaitCondition receivedWait;

    QMutex outboundLock;
    QWaitCondition outboundWait;

    QString key;
    QString serverName;
    QString remoteName;

    QLocalSocket * inbound;
    QLocalSocket outbound;
    QLocalServer server;


    void waitForInbound()
    {
        QMutexLocker locker(&receivedLock);
        while (!inbound || inbound->state() != QLocalSocket::ConnectedState) {
            bool res = receivedWait.wait(&receivedLock,30*1000);
            if (!res)
            {
                qDebug() << key << " " << QThread::currentThread() << " waiting timed out, server thread is " << server.thread() << " base thread " << basis;
            }
        }
    }

    void connectToRemote(const QString & remoteName)
    {
        emit pulseOutboundConnect(remoteName);

        QMutexLocker locker(&outboundLock);
        while (outbound.state() != QLocalSocket::ConnectedState) {
            outboundWait.wait(&outboundLock,30*1000);

        }
    }

    SignalType getSignal()
    {
        emit pulseReadSignal();
        return readSignal;
    }


    template<typename T>
    bool readData(T & input)
    {
        emit pulseReadSerialized();
        QDataStream deserializer(readArray);
        deserializer >> input;
        return true;
    }

    template<typename T>
    bool sendData(const T & output)
    {
        QBuffer buffer;
        buffer.open(QBuffer::ReadWrite);

        QDataStream serializer(&buffer);
        serializer << output;
        writeArray = buffer.data();
        emit pulseSendSerialized();
        return true;
    }

    SignalType sendType;
    void sendSignal(SignalType signal)
    {
        sendType = signal;
        if (QThread::currentThread() == this->thread() )
            this->sendSignalInternal();
        else
            emit pulseSignal();
    }

    void startServer(QString server)
    {
        emit pulseStartServer(server);
    }

    void shutdown()
    {
        emit pulseShutdown();
    }

 
};

class EnrollmentWorker : public QObject
{
    Q_OBJECT
public:
    CommunicationManager * comm;
    QString name;

    ~EnrollmentWorker()
    {
        delete transform;

        comm->shutDownThread();
        delete comm;
    }

    br::Transform * transform;

public:
    void connections(const QString & baseName)
    {
        comm = new CommunicationManager();
        name = baseName;
        comm->key = "worker_"+baseName.mid(1,5);
        comm->startServer(baseName+"_worker");
        comm->connectToRemote(baseName+"_master");

        comm->waitForInbound();
    }

    void workerLoop()
    {
        QString sign = "worker " + name;
        CommunicationManager::SignalType signal;
        forever
        {
            signal= comm->getSignal();

            if (signal == CommunicationManager::SHOULD_END) {
                break;
            }
            TemplateList inList;
            TemplateList outList;

            comm->readData(inList);
            transform->projectUpdate(inList,outList);
            comm->sendData(outList);
        }
        comm->shutdown();
    }
};

void WorkerProcess::mainLoop()
{
    processInterface = new EnrollmentWorker();
    processInterface->transform = Transform::make(this->transform,NULL);
    processInterface->connections(baseName);
    processInterface->workerLoop();
    delete processInterface;
}

class ProcessInterface : public QObject
{
    Q_OBJECT
public:
    ProcessInterface()
    {
        this->moveToThread(QCoreApplication::instance()->thread());
        workerProcess.moveToThread(QCoreApplication::instance()->thread());
        connect(this, SIGNAL(pulseEnd()), this, SLOT(endProcessInternal()), Qt::BlockingQueuedConnection);
        connect(this, SIGNAL(pulseStart(QStringList)), this, SLOT(startProcessInternal(QStringList)), Qt::BlockingQueuedConnection);
    }
    QProcess workerProcess;
    void endProcess()
    {
        if (QThread::currentThread() != QCoreApplication::instance()->thread())
            emit pulseEnd();
        else
            endProcessInternal();
    }
    void startProcess(QStringList arguments)
    {
        if (QThread::currentThread() != QCoreApplication::instance()->thread() )
            emit pulseStart(arguments);
        else
            startProcessInternal(arguments);
    }
signals:
    void pulseEnd();
    void pulseStart(QStringList);

protected slots:
    void endProcessInternal()
    {
        workerProcess.waitForFinished(-1);
    }

    void startProcessInternal(QStringList arguments)
    {
        workerProcess.setProcessChannelMode(QProcess::ForwardedChannels);
        workerProcess.start("br", arguments);
        workerProcess.waitForStarted(-1);
    }
};

/*!
 * \ingroup transforms
 * \brief Interface to a separate process
 * \author Charles Otto \cite caotto
 */
class ProcessWrapperTransform : public TimeVaryingTransform
{
    Q_OBJECT

    Q_PROPERTY(QString transform READ get_transform WRITE set_transform RESET reset_transform)
    BR_PROPERTY(QString, transform, "")

    QString baseKey;

    ProcessInterface workerProcess;
    CommunicationManager * comm;

    void projectUpdate(const TemplateList &src, TemplateList &dst)
    {

        if (!processActive)
        {
            activateProcess();
        }
        comm->sendSignal(CommunicationManager::INPUT_AVAILABLE);

        comm->sendData(src);

        comm->readData(dst);
    }


    void train(const TemplateList& data)
    {
        (void) data;
    }

    // create the process
    void init()
    {
        processActive = false;
    }

    void activateProcess()
    {
        comm = new CommunicationManager();
        processActive = true;

        // generate a uuid for our local servers
        QUuid id = QUuid::createUuid();
        baseKey = id.toString();

        QStringList argumentList;
        argumentList.append("-useGui");
        argumentList.append("0");
        argumentList.append("-algorithm");
        argumentList.append(transform);
        if (!Globals->path.isEmpty()) {
            argumentList.append("-path");
            argumentList.append(Globals->path);
        }
        argumentList.append("-parallelism");
        argumentList.append(QString::number(0));
        argumentList.append("-slave");
        argumentList.append(baseKey);

        comm->key = "master_"+baseKey.mid(1,5);

        comm->startServer(baseKey+"_master");
        workerProcess.startProcess(argumentList);
        comm->waitForInbound();
        comm->connectToRemote(baseKey+"_worker");
    }

    bool timeVarying() const {
        return false;
    }

    ~ProcessWrapperTransform()
    {
        // end the process
        if (this->processActive) {
            comm->sendSignal(CommunicationManager::SHOULD_END);

            workerProcess.endProcess();
            processActive = false;
            comm->shutdown();
            comm->shutDownThread();

            delete comm;
        }
    }

public:
    bool processActive;
    ProcessWrapperTransform() : TimeVaryingTransform(false,false) { processActive = false; }
};

BR_REGISTER(Transform, ProcessWrapperTransform)

}

#include "process.moc"