예제 #1
0
void ParticipantIdStorage::loadEntriesFromFile()
{
    if (!joynr::util::fileExists(fileName)) {
        return;
    }

    JOYNR_LOG_TRACE(logger(), "Attempting to load ParticipantIdStorage from: {}", fileName);

    boost::property_tree::ptree pt;
    WriteLocker lockAccessToStorage(storageMutex);
    try {
        boost::property_tree::ini_parser::read_ini(fileName, pt);
        for (boost::property_tree::ptree::const_iterator it = pt.begin(); it != pt.end(); ++it) {
            StorageItem item{it->first, it->second.data()};
            auto retVal = storage.insert(std::move(item));
            assert(retVal.second);
        }
    } catch (const std::exception& ex) {
        JOYNR_LOG_WARN(logger(),
                       "Cannot read participantId storage file {}. Removing file. Exception: {}",
                       fileName,
                       ex.what());
        std::remove(fileName.c_str());
    }

    // set entriesWrittenToDisk to the size of the storage
    entriesWrittenToDisk = storage.get<participantIdStorageTags::write>().size();
    JOYNR_LOG_TRACE(logger(), "Loaded {} entries.", entriesWrittenToDisk);
}
types::DiscoveryEntryWithMetaInfo QosArbitrationStrategyFunction::select(
        const std::map<std::string, types::CustomParameter> customParameters,
        const std::vector<types::DiscoveryEntryWithMetaInfo>& discoveryEntries) const
{
    std::ignore = customParameters;
    auto selectedDiscoveryEntryIt = discoveryEntries.cend();
    std::int64_t highestPriority = types::ProviderQos().getPriority(); // get default value

    for (auto it = discoveryEntries.cbegin(); it != discoveryEntries.cend(); ++it) {
        const types::ProviderQos& providerQos = it->getQos();
        JOYNR_LOG_TRACE(logger(), "Looping over discoveryEntry: {}", it->toString());

        if (providerQos.getPriority() >= highestPriority) {
            selectedDiscoveryEntryIt = it;
            JOYNR_LOG_TRACE(logger(),
                            "setting selectedParticipantId to {}",
                            selectedDiscoveryEntryIt->getParticipantId());
            highestPriority = providerQos.getPriority();
        }
    }

    if (selectedDiscoveryEntryIt == discoveryEntries.cend()) {
        std::stringstream errorMsg;
        errorMsg << "There was more than one entry in capabilitiesEntries, but none of the "
                    "compatible entries had a priority >= " << types::ProviderQos().getPriority();
        JOYNR_LOG_WARN(logger(), errorMsg.str());
        throw exceptions::DiscoveryException(errorMsg.str());
    }

    return *selectedDiscoveryEntryIt;
}
JoynrClusterControllerRuntime::~JoynrClusterControllerRuntime()
{
    JOYNR_LOG_TRACE(logger, "entering ~JoynrClusterControllerRuntime");
    stopMessaging();

    if (joynrDispatcher != nullptr) {
        JOYNR_LOG_TRACE(logger, "joynrDispatcher");
        // joynrDispatcher->stopMessaging();
        delete joynrDispatcher;
    }

    delete inProcessDispatcher;
    inProcessDispatcher = nullptr;
    delete capabilitiesClient;
    capabilitiesClient = nullptr;

    delete inProcessPublicationSender;
    inProcessPublicationSender = nullptr;
    delete joynrMessageSender;
    delete proxyFactory;
    delete messagingSettings;
    delete libjoynrSettings;
    delete capabilitiesRegistrar;

#ifdef USE_DBUS_COMMONAPI_COMMUNICATION
    delete ccDbusMessageRouterAdapter;
    delete dbusSettings;
#endif // USE_DBUS_COMMONAPI_COMMUNICATION
    delete settings;

    JOYNR_LOG_TRACE(logger, "leaving ~JoynrClusterControllerRuntime");
}
예제 #4
0
void WebSocketMessagingStub::transmit(
        JoynrMessage& message,
        const std::function<void(const exceptions::JoynrRuntimeException&)>& onFailure)
{
    if (!webSocket->isInitialized()) {
        JOYNR_LOG_TRACE(logger,
                        "WebSocket not ready. Unable to send message {}",
                        JsonSerializer::serialize(message));
        onFailure(exceptions::JoynrDelayMessageException(
                "WebSocket not ready. Unable to send message"));
    }

    std::string serializedMessage = JsonSerializer::serialize(message);
    JOYNR_LOG_TRACE(logger, ">>>> OUTGOING >>>> {}", serializedMessage);
    webSocket->send(serializedMessage, onFailure);
}
예제 #5
0
void ParticipantIdStorage::writeStoreToFile()
{
    std::lock_guard<std::mutex> lockAccessToFile(fileMutex);
    WriteLocker lockAccessToStorage(storageMutex);

    auto& writeIndex = storage.get<participantIdStorageTags::write>();
    const size_t entries = writeIndex.size();

    // The storage in memory is supposed to contain at least one entry at this point.
    if (entries == 0) {
        assert(entriesWrittenToDisk == 0);
        return;
    }

    if (entries > entriesWrittenToDisk) {
        JOYNR_LOG_TRACE(
                logger(), "Writing {} new entries to file.", entries - entriesWrittenToDisk);

        // write not present entries to File
        size_t writtenToDisk = 0;
        for (size_t i = entriesWrittenToDisk; i < entries; ++i, ++writtenToDisk) {
            auto entry = writeIndex[i];
            try {
                joynr::util::appendStringToFile(fileName, entry.toIniForm());
            } catch (const std::runtime_error& ex) {
                JOYNR_LOG_ERROR(logger(),
                                "Cannot save ParticipantId to file. Next application lifecycle "
                                "might not function correctly. Exception: ",
                                ex.what());
                entriesWrittenToDisk += writtenToDisk;
                return;
            }
        }
        assert(entries == entriesWrittenToDisk + writtenToDisk);
        entriesWrittenToDisk = entries;
        JOYNR_LOG_TRACE(logger(), "Storage on file contains now {} entries.", entriesWrittenToDisk);
    } else if (entries < entriesWrittenToDisk) {
        // This actually means that someone modified the file and inserted other entries.
        // Do nothing.
    } else {
        // In this case the number of entries written to disk matches those in the store.
        // Do nothing.
    }
}
예제 #6
0
void HttpMessagingStub::transmit(
        std::shared_ptr<ImmutableMessage> message,
        const std::function<void(const exceptions::JoynrRuntimeException&)>& onFailure)
{
    if (logger().getLogLevel() == LogLevel::Debug) {
        JOYNR_LOG_DEBUG(logger(), ">>> OUTGOING >>> {}", message->getTrackingInfo());
    } else {
        JOYNR_LOG_TRACE(logger(), ">>> OUTGOING >>> {}", message->toLogMessage());
    }
    messageSender->sendMessage(destinationAddress, std::move(message), onFailure);
}
void WebSocketLibJoynrMessagingSkeleton::onTextMessageReceived(const std::string& message)
{
    // deserialize message and transmit
    JoynrMessage* joynrMsg = JsonSerializer::deserialize<JoynrMessage>(message);
    if (joynrMsg == nullptr || joynrMsg->getType().empty()) {
        JOYNR_LOG_ERROR(logger, "Unable to deserialize joynr message object from: {}", message);
        return;
    }
    JOYNR_LOG_TRACE(logger, "<<< INCOMING <<< {}", message);
    // message router copies joynr message when scheduling thread that handles
    // message delivery
    transmit(*joynrMsg);
    delete joynrMsg;
}
void LongPollingMessageReceiver::checkServerTime()
{
    std::string timeCheckUrl = bounceProxyUrl.getTimeCheckUrl().toString();

    std::shared_ptr<IHttpGetBuilder> timeCheckRequestBuilder(
            HttpNetworking::getInstance()->createHttpGetBuilder(timeCheckUrl));
    std::shared_ptr<HttpRequest> timeCheckRequest(
            timeCheckRequestBuilder->addHeader("Accept", "text/plain")
                    ->withTimeout(settings.bounceProxyTimeout)
                    ->build());
    JOYNR_LOG_DEBUG(logger, "CheckServerTime: sending request to Bounce Proxy ({})", timeCheckUrl);
    std::chrono::system_clock::time_point localTimeBeforeRequest = std::chrono::system_clock::now();
    HttpResult timeCheckResult = timeCheckRequest->execute();
    std::chrono::system_clock::time_point localTimeAfterRequest = std::chrono::system_clock::now();
    std::uint64_t localTime = (TypeUtil::toMilliseconds(localTimeBeforeRequest) +
                               TypeUtil::toMilliseconds(localTimeAfterRequest)) /
                              2;
    if (timeCheckResult.getStatusCode() != 200) {
        JOYNR_LOG_ERROR(logger,
                        "CheckServerTime: Bounce Proxy not reached [statusCode={}] [body={}]",
                        timeCheckResult.getStatusCode(),
                        QString(timeCheckResult.getBody()).toStdString());
    } else {
        JOYNR_LOG_TRACE(logger,
                        "CheckServerTime: reply received [statusCode={}] [body={}]",
                        timeCheckResult.getStatusCode(),
                        QString(timeCheckResult.getBody()).toStdString());
        std::uint64_t serverTime =
                TypeUtil::toStdUInt64(QString(timeCheckResult.getBody()).toLongLong());

        auto minMaxTime = std::minmax(serverTime, localTime);
        std::uint64_t diff = minMaxTime.second - minMaxTime.first;

        JOYNR_LOG_INFO(
                logger,
                "CheckServerTime [server time={}] [local time={}] [diff={} ms]",
                TypeUtil::toDateString(JoynrTimePoint(std::chrono::milliseconds(serverTime))),
                TypeUtil::toDateString(JoynrTimePoint(std::chrono::milliseconds(localTime))),
                diff);

        if (diff > 500) {
            JOYNR_LOG_ERROR(logger, "CheckServerTime: time difference to server is {} ms", diff);
        }
    }
}
예제 #9
0
void SubscriptionManager::checkMissedPublication(
    const Timer::TimerId id)
{
    std::lock_guard<std::recursive_mutex> subscriptionLocker(&mutex);

    if (!isExpired() && !subscription->isStopped)
    {
        JOYNR_LOG_DEBUG(logger, "Running MissedPublicationRunnable for subscription id= {}",subscriptionId);
        std::int64_t delay = 0;
        std::int64_t now = duration_cast<milliseconds>(
            system_clock::now().time_since_epoch()).count();
        std::int64_t timeSinceLastPublication = now
            - subscription->timeOfLastPublication;
        bool publicationInTime = timeSinceLastPublication < alertAfterInterval;
        if (publicationInTime)
        {
            JOYNR_LOG_TRACE(logger, "Publication in time!");
            delay = alertAfterInterval - timeSinceLastPublication;
        }
        else
        {
            JOYNR_LOG_DEBUG(logger, "Publication missed!");
            std::shared_ptr<ISubscriptionCallback> callback =
                subscription->subscriptionCaller;

            callback->onError();
            delay = alertAfterInterval
                - timeSinceLastExpectedPublication(timeSinceLastPublication);
        }
        JOYNR_LOG_DEBUG(logger, "Resceduling MissedPublicationRunnable with delay: {}",std::string::number(delay));
        subscription->missedPublicationRunnableHandle =
            subscriptionManager.missedPublicationScheduler->schedule(
                new MissedPublicationRunnable(decayTime,
                    expectedIntervalMSecs,
                    subscriptionId,
                    subscription,
                    subscriptionManager,
                    alertAfterInterval),
                delay);
    }
    else
    {
        JOYNR_LOG_DEBUG(logger, "Publication expired / interrupted. Expiring on subscription id={}",subscriptionId);
    }
}
예제 #10
0
파일: Dispatcher.cpp 프로젝트: zabela/joynr
void Dispatcher::handleBroadcastSubscriptionRequestReceived(const JoynrMessage& message)
{
    JOYNR_LOG_TRACE(logger, "Starting handleBroadcastSubscriptionRequestReceived");
    // Make sure that noone is registering a Caller at the moment, because a racing condition could
    // occour.
    std::lock_guard<std::mutex> lock(subscriptionHandlingMutex);
    assert(publicationManager != nullptr);

    std::string receiverId = message.getHeaderTo();
    std::shared_ptr<RequestCaller> caller = requestCallerDirectory.lookup(receiverId);

    std::string jsonSubscriptionRequest = message.getPayload();

    // PublicationManager is responsible for deleting SubscriptionRequests
    try {
        BroadcastSubscriptionRequest subscriptionRequest =
                JsonSerializer::deserialize<BroadcastSubscriptionRequest>(jsonSubscriptionRequest);

        if (!caller) {
            // Provider not registered yet
            // Dispatcher will call publicationManger->restore when a new provider is added to
            // activate
            // subscriptions for that provider
            publicationManager->add(
                    message.getHeaderFrom(), message.getHeaderTo(), subscriptionRequest);
        } else {
            publicationManager->add(message.getHeaderFrom(),
                                    message.getHeaderTo(),
                                    caller,
                                    subscriptionRequest,
                                    messageSender);
        }
    } catch (const std::invalid_argument& e) {
        JOYNR_LOG_ERROR(
                logger,
                "Unable to deserialize broadcast subscription request object from: {} - error: {}",
                jsonSubscriptionRequest,
                e.what());
    }
}