boost::shared_ptr<IHttpResponse> HttpClient::sendRequest(const IHttpRequest& request) { KAA_MUTEX_LOCKING("guard_"); boost::unique_lock<boost::mutex> lock(guard_); KAA_MUTEX_LOCKED("guard_"); if (sock_.is_open()) { doSocketClose(); } KAA_LOG_INFO(boost::format("Sending request to the server %1%:%2%") % request.getHost() % request.getPort()); const auto& ep = HttpUtils::getEndpoint(request.getHost(), request.getPort()); const auto& data = request.getRequestData(); boost::system::error_code errorCode; sock_.open(ep.protocol(), errorCode); checkError(errorCode); sock_.connect(ep, errorCode); checkError(errorCode); boost::asio::write(sock_, boost::asio::buffer(data.data(), data.size()), errorCode); checkError(errorCode); std::ostringstream responseStream; boost::asio::streambuf responseBuf; while (boost::asio::read(sock_, responseBuf, boost::asio::transfer_at_least(1), errorCode)) { responseStream << &responseBuf; } checkError(errorCode); const std::string& responseStr = responseStream.str(); KAA_LOG_INFO(boost::format("Response from server %1%:%2% successfully received") % request.getHost() % request.getPort()); doSocketClose(); return boost::shared_ptr<IHttpResponse>(new HttpResponse(responseStr)); }
kaa_error_t on_kaa_tcp_channel_event(void *context , kaa_tcp_channel_event_t event_type , kaa_fd_t fd) { KAA_RETURN_IF_NIL(context, KAA_ERR_BADPARAM); kaa_client_t *self = (kaa_client_t *)context; switch (event_type) { case SOCKET_CONNECTED: KAA_LOG_INFO(self->kaa_context->logger, KAA_ERR_NONE, "Bootstrap socket(%d) Connected", fd); if (self->bootstrap_state == BOOTSRAP_UNDEF) self->bootstrap_state = BOOTSRAP_STARTED; break; case SOCKET_DISCONNECTED: KAA_LOG_INFO(self->kaa_context->logger, KAA_ERR_NONE, "Bootstrap socket Disconnected"); if (self->bootstrap_state == BOOTSRAP_STARTED) self->bootstrap_state = BOOTSRAP_FINISHED; break; default: KAA_LOG_ERROR(self->kaa_context->logger, KAA_ERR_NONE, "Bootstrap socket Error"); self->bootstrap_state = BOOTSRAP_UNDEF; break; } return KAA_ERR_NONE; }
kaa_error_t kaa_profile_handle_server_sync(kaa_profile_manager_t *self , kaa_platform_message_reader_t *reader , uint16_t extension_options , size_t extension_length) { // Only used for logging (void)extension_options; (void)extension_length; KAA_RETURN_IF_NIL2(self, reader, KAA_ERR_BADPARAM); KAA_LOG_INFO(self->logger, KAA_ERR_NONE, "Received profile server sync: options %u, payload size %zu", extension_options, extension_length); kaa_error_t error_code = KAA_ERR_NONE; self->need_resync = false; if (extension_options & KAA_PROFILE_RESYNC_OPTION) { self->need_resync = true; KAA_LOG_INFO(self->logger, KAA_ERR_NONE, "Going to resync profile..."); /* Ignoring an error code: the channels can be not initialized */ (void)kaa_profile_force_sync(self); } if (!self->status->is_registered) { KAA_LOG_INFO(self->logger, KAA_ERR_NONE, "Endpoint has been registered"); self->status->is_registered = true; } return error_code; }
void ConfigurationPersistenceManager::onConfigurationUpdated(const KaaRootConfiguration& configuration) { if (ignoreConfigurationUpdate_) { ignoreConfigurationUpdate_ = false; return; } KAA_LOG_INFO("Configuration updated."); AvroByteArrayConverter<KaaRootConfiguration> converter; SharedDataBuffer buffer = converter.toByteArray(configuration); KAA_LOG_INFO(boost::format("Going to store configuration using configuration storage %1%") % storage_); KAA_MUTEX_LOCKING("confPersistenceGuard_"); KAA_MUTEX_UNIQUE_DECLARE(confPersistenceGuardLock, confPersistenceGuard_); KAA_MUTEX_LOCKED("confPersistenceGuard_"); if (storage_) { storage_->saveConfiguration(std::vector<std::uint8_t>(buffer.first.get(), buffer.first.get() + buffer.second)); } KAA_MUTEX_UNLOCKING("confPersistenceGuard_"); KAA_UNLOCK(confPersistenceGuardLock); KAA_MUTEX_UNLOCKED("confPersistenceGuard_"); configurationHash_ = EndpointObjectHash(buffer); KAA_LOG_INFO(boost::format("Calculated configuration hash: %1%") % LoggingUtils::ByteArrayToString(configurationHash_.getHashDigest())); }
kaa_error_t kaa_profile_handle_server_sync(kaa_profile_manager_t *self , kaa_platform_message_reader_t *reader , uint16_t extension_options , size_t extension_length) { // Only used for logging (void)extension_options; (void)extension_length; KAA_RETURN_IF_NIL2(self, reader, KAA_ERR_BADPARAM); KAA_LOG_INFO(self->logger, KAA_ERR_NONE, "Received profile server sync: options %u, payload size %zu", extension_options, extension_length); kaa_error_t error_code = KAA_ERR_NONE; self->need_resync = false; if (extension_options & KAA_PROFILE_RESYNC_OPTION) { self->need_resync = true; KAA_LOG_INFO(self->logger, KAA_ERR_NONE, "Going to resync profile..."); kaa_transport_channel_interface_t *channel = kaa_channel_manager_get_transport_channel(self->channel_manager, profile_sync_services[0]); if (channel) channel->sync_handler(channel->context, profile_sync_services, 1); } if (!self->status->is_registered) { KAA_LOG_INFO(self->logger, KAA_ERR_NONE, "Endpoint has been registered"); self->status->is_registered = true; } return error_code; }
kaa_error_t kaa_client_init_channel(kaa_client_t *kaa_client, kaa_client_channel_type_t channel_type) { KAA_RETURN_IF_NIL(kaa_client, KAA_ERR_BADPARAM); kaa_error_t error_code = KAA_ERR_NONE; KAA_LOG_TRACE(kaa_client->kaa_context->logger, KAA_ERR_NONE, "Initializing channel...."); switch (channel_type) { case KAA_CLIENT_CHANNEL_TYPE_BOOTSTRAP: error_code = kaa_tcp_channel_create(&kaa_client->channel, kaa_client->kaa_context->logger, BOOTSTRAP_SERVICE, BOOTSTRAP_SERVICE_COUNT); break; case KAA_CLIENT_CHANNEL_TYPE_OPERATIONS: error_code = kaa_tcp_channel_create(&kaa_client->channel , kaa_client->kaa_context->logger , OPERATIONS_SERVICES , OPERATIONS_SERVICES_COUNT); break; } if (error_code) { KAA_LOG_ERROR(kaa_client->kaa_context->logger, error_code, "Error initializing channel %d", channel_type); return error_code; } error_code = kaa_tcp_channel_set_keepalive_timeout(&kaa_client->channel, 120); if (error_code) { KAA_LOG_ERROR(kaa_client->kaa_context->logger, error_code, "Error set keepalive"); } error_code = kaa_channel_manager_add_transport_channel(kaa_client->kaa_context->channel_manager, &kaa_client->channel, &kaa_client->channel_id); if (error_code) { KAA_LOG_ERROR(kaa_client->kaa_context->logger, error_code, "Error register channel %d as transport", channel_type); return error_code; } KAA_LOG_INFO(kaa_client->kaa_context->logger, KAA_ERR_NONE, "Channel(type=%d,id=%08X) initialized successfully" , channel_type, kaa_client->channel_id); char *hostname = NULL; size_t hostname_size = 0; uint16_t port = 0; error_code = kaa_tcp_channel_get_access_point(&kaa_client->channel, &hostname, &hostname_size, &port); if (error_code) { KAA_LOG_ERROR(kaa_client->kaa_context->logger, error_code, "Kaa tcp channel get access point failed"); } else if (hostname_size > 0){ char *n_hostname = strndup(hostname, hostname_size); KAA_LOG_INFO(kaa_client->kaa_context->logger, KAA_ERR_NONE, "Channel(type=%d,id=%08X) destination %s:%d", channel_type , kaa_client->channel_id, n_hostname, port); free(n_hostname); } return error_code; }
kaa_error_t kaa_client_create(kaa_client_t **kaa_client, kaa_client_props_t *props) { KAA_RETURN_IF_NIL2(kaa_client, props, KAA_ERR_BADPARAM); kaa_error_t error_code = KAA_ERR_NONE; kaa_client_t *self = calloc(1, sizeof(kaa_client_t)); KAA_RETURN_IF_NIL(self, KAA_ERR_NOMEM); esp8266_error_t esp8266_error = esp8266_create(&self->controler, props->serial, DEFAULT_ESP8266_CONTROLER_BUFFER_SIZE); if (esp8266_error) { debug("Error during esp8266 creation %d\n", esp8266_error); kaa_client_destroy(self); return KAA_ERR_BADDATA; } esp8266_error = esp8266_tcp_register_receive_callback(self->controler, esp8266_tcp_receive_fn, (void *)self); if (esp8266_error) { debug("Error during esp8266 registering receive callback %d\n", esp8266_error); kaa_client_destroy(self); return KAA_ERR_BADDATA; } error_code = kaa_init_security_stuff(props->kaa_public_key, props->kaa_public_key_length); if (error_code) { debug("Error generate SHA1 diges form Public Key, error %d", error_code); kaa_client_destroy(self); return error_code; } error_code = kaa_init(&self->kaa_context); if (error_code) { debug("Error during Kaa context creation %d\n", error_code); kaa_client_destroy(self); return error_code; } KAA_LOG_INFO(self->kaa_context->logger, KAA_ERR_NONE, "Kaa framework initialized."); self->wifi_ssid = props->wifi_ssid; self->wifi_pswd = props->wifi_pswd; self->operate = true; self->blink_timeout = 500; error_code = kaa_log_collector_init(self); if (error_code) { KAA_LOG_ERROR(self->kaa_context->logger, error_code, "Failed to init Kaa log collector %d", error_code); kaa_client_destroy(self); return error_code; } KAA_LOG_INFO(self->kaa_context->logger, KAA_ERR_NONE, "Kaa log collector initialized."); *kaa_client = self; return error_code; }
kaa_error_t kaa_configuration_manager_handle_server_sync(kaa_configuration_manager_t *self , kaa_platform_message_reader_t *reader , uint32_t extension_options , size_t extension_length) { KAA_RETURN_IF_NIL2(self, reader, KAA_ERR_BADPARAM); KAA_LOG_INFO(self->logger, KAA_ERR_NONE, "Received configuration server sync: options %u, payload size %u", extension_options, extension_length); if (extension_length >= sizeof(uint32_t)) { self->status->config_seq_n = KAA_NTOHL(*((uint32_t *) reader->current)); KAA_LOG_TRACE(self->logger, KAA_ERR_NONE, "Configuration state sequence number is '%d'", self->status->config_seq_n); reader->current += sizeof(uint32_t); if (extension_options & KAA_CONFIGURATION_BODY_PRESENT) { uint32_t body_size = KAA_NTOHL(*((uint32_t *) reader->current)); reader->current += sizeof(uint32_t); KAA_LOG_INFO(self->logger, KAA_ERR_NONE, "Received configuration body, size '%u' ", body_size); const char* body = reader->current; kaa_error_t error = kaa_platform_message_skip(reader, kaa_aligned_size_get(body_size)); if (error) { KAA_LOG_ERROR(self->logger, error, "Failed to read configuration body, size %u", body_size); return error; } #if KAA_CONFIGURATION_DELTA_SUPPORT #else if (self->root_record) self->root_record->destroy(self->root_record); self->root_record = kaa_configuration_manager_deserialize(body, body_size); if (!self->root_record) { KAA_LOG_ERROR(self->logger, KAA_ERR_READ_FAILED, "Failed to deserialize configuration body, size %u", body_size); return KAA_ERR_READ_FAILED; } kaa_error_t err = ext_calculate_sha_hash(body, body_size, self->configuration_hash); if (err) { KAA_LOG_WARN(self->logger, err, "Failed to calculate configuration body hash"); return err; } ext_configuration_store(body, body_size); #endif if (self->root_receiver.on_configuration_updated) self->root_receiver.on_configuration_updated(self->root_receiver.context, self->root_record); kaa_transport_channel_interface_t *channel = kaa_channel_manager_get_transport_channel(self->channel_manager, configuration_sync_services[0]); if (channel) channel->sync_handler(channel->context, configuration_sync_services, 1); } } return KAA_ERR_NONE; }
kaa_error_t kaa_client_deinit_bootstrap_channel(kaa_client_t *kaa_client) { KAA_RETURN_IF_NIL(kaa_client, KAA_ERR_BADPARAM); KAA_LOG_TRACE(kaa_client->kaa_context->logger, KAA_ERR_NONE, "Bootstrap channel deinitialization starting ...."); print_mem_stat(kaa_client); kaa_error_t error_code = KAA_ERR_NONE; error_code = kaa_channel_manager_remove_transport_channel( kaa_client->kaa_context->channel_manager,kaa_client->bootstrap_channel_id); if (error_code) { KAA_LOG_TRACE(kaa_client->kaa_context->logger, error_code, "Bootstrap channel error removing from channel manager"); return error_code; } kaa_client->bootstrap_channel.context = NULL; kaa_client->bootstrap_channel.destroy = NULL; kaa_client->bootstrap_channel.get_protocol_id = NULL; kaa_client->bootstrap_channel.get_supported_services = NULL; kaa_client->bootstrap_channel.init = NULL; kaa_client->bootstrap_channel.set_access_point = NULL; kaa_client->bootstrap_channel.sync_handler = NULL; kaa_client->bootstrap_state = BOOTSRAP_UNDEF; KAA_LOG_INFO(kaa_client->kaa_context->logger, KAA_ERR_NONE, "Bootstrap channel deinitialized"); return error_code; }
kaa_error_t kaa_client_init_operations_channel(kaa_client_t *kaa_client) { KAA_RETURN_IF_NIL(kaa_client, KAA_ERR_BADPARAM); kaa_error_t error_code = KAA_ERR_NONE; KAA_LOG_TRACE(kaa_client->kaa_context->logger, KAA_ERR_NONE, "Start operations channel initialization"); error_code = kaa_tcp_channel_create(&kaa_client->operations_channel , kaa_client->kaa_context->logger , OPERATIONS_SERVICES , OPERATIONS_SERVICES_COUNT); if (error_code) { KAA_LOG_ERROR(kaa_client->kaa_context->logger, error_code, "Operations channel initialization failed"); return error_code; } KAA_LOG_TRACE(kaa_client->kaa_context->logger, KAA_ERR_NONE, "Initializing Kaa SDK Operations channel added to transport channel manager"); error_code = kaa_channel_manager_add_transport_channel(kaa_client->kaa_context->channel_manager , &kaa_client->operations_channel , &kaa_client->operations_channel_id); if (error_code) { KAA_LOG_ERROR(kaa_client->kaa_context->logger, error_code, "Error during Kaa operations channel setting as transport"); return error_code; } KAA_LOG_INFO(kaa_client->kaa_context->logger, KAA_ERR_NONE, "Operations channel initialized successfully"); print_mem_stat(kaa_client); return error_code; }
void KaaClient::init(int options /*= KAA_DEFAULT_OPTIONS*/) { options_ = options; KAA_LOG_INFO(boost::format("Starting Kaa C++ sdk version %1%, commit hash %2%. Options: %3%") % BUILD_VERSION % BUILD_COMMIT_HASH % options); initClientKeys(); #ifdef KAA_USE_CONFIGURATION configurationProcessor_.reset(new ConfigurationProcessor); configurationManager_.reset(new ConfigurationManager); #endif bootstrapManager_.reset(new BootstrapManager); channelManager_.reset(new KaaChannelManager(*bootstrapManager_, getBootstrapServers())); #ifdef KAA_USE_EVENTS registrationManager_.reset(new EndpointRegistrationManager(status_)); eventManager_.reset(new EventManager(status_)); eventFamilyFactory_.reset(new EventFamilyFactory(*eventManager_, *eventManager_)); #endif #ifdef KAA_USE_NOTIFICATIONS notificationManager_.reset(new NotificationManager(status_)); #endif profileManager_.reset(new ProfileManager()); #ifdef KAA_USE_LOGGING logCollector_.reset(new LogCollector(channelManager_.get())); #endif initKaaConfiguration(); initKaaTransport(); }
/** Handles timeout event. Must be called if timeout is occurred. */ static void handle_timeout(kaa_log_collector_t *self) { // TODO(KAA-982): Use asserts if (!self || !self->timeouts) { return; } kaa_error_t err = ext_log_upload_strategy_on_timeout(self->log_upload_strategy_context); bool expire_every_entry = (err == KAA_ERR_EVENT_NOT_ATTACHED); if (expire_every_entry) { /* Upload strategy decided to switch an access point. All pending logs are now deemed as * timeouted. */ KAA_LOG_INFO(self->logger, KAA_ERR_NONE, "Access point has been switched. All buckets are expired."); } for (kaa_list_node_t *it = kaa_list_begin(self->timeouts); it; it = kaa_list_next(it)) { timeout_info_t *info = kaa_list_get_data(it); if (expire_every_entry || !info->deadline) { ext_log_storage_unmark_by_bucket_id(self->log_storage_context, info->log_bucket_id); if (self->log_delivery_listeners.on_timeout) { kaa_log_bucket_info_t log_bucket_info = { .bucket_id = info->log_bucket_id, .log_count = info->log_count, }; self->log_delivery_listeners.on_timeout(self->log_delivery_listeners.ctx, &log_bucket_info); } } }
kaa_error_t kaa_platform_protocol_serialize_client_sync(kaa_platform_protocol_t *self , const kaa_serialize_info_t *info , char **buffer , size_t *buffer_size) { KAA_RETURN_IF_NIL4(self, info, buffer, buffer_size, KAA_ERR_BADPARAM); KAA_RETURN_IF_NIL3(info->allocator, info->services, info->services_count, KAA_ERR_BADDATA); KAA_LOG_TRACE(self->logger, KAA_ERR_NONE, "Serializing client sync..."); *buffer_size = 0; kaa_error_t error = kaa_client_sync_get_size(self, info->services, info->services_count, buffer_size); KAA_RETURN_IF_ERR(error); KAA_LOG_DEBUG(self->logger, KAA_ERR_NONE, "Going to request sync buffer (size %zu)", *buffer_size); *buffer = info->allocator(info->allocator_context, *buffer_size); if (*buffer) { self->request_id++; error = kaa_client_sync_serialize(self, info->services, info->services_count, *buffer, buffer_size); } else { error = KAA_ERR_WRITE_FAILED; } if (error) { self->request_id--; } else { KAA_LOG_INFO(self->logger, KAA_ERR_NONE, "Client sync serialized: request id '%u', payload size '%zu'", self->request_id, *buffer_size); } return error; }
void DefaultOperationTcpChannel::onServerFailed(KaaFailoverReason failoverReason) { if (isFailoverInProgress_) { KAA_LOG_TRACE(boost::format("Channel [%1%] failover processing already in progress. " "Ignore '%2%' failover") % getId() % LoggingUtils::toString(failoverReason)); return; } isFailoverInProgress_ = true; closeConnection(); KaaFailoverReason finalFailoverReason = failoverReason; if (failoverReason == KaaFailoverReason::CURRENT_OPERATIONS_SERVER_NA) { if (connectivityChecker_ && !connectivityChecker_->checkConnectivity()) { KAA_LOG_INFO(boost::format("Channel [%1%] detected loss of connectivity") % getId()); finalFailoverReason = KaaFailoverReason::NO_CONNECTIVITY; } } auto server = std::dynamic_pointer_cast<ITransportConnectionInfo, IPTransportInfo>(currentServer_); KAA_LOG_WARN(boost::format("Channel [%1%] detected '%2%' failover for %3%") % getId() % LoggingUtils::toString(finalFailoverReason) % LoggingUtils::toString(*server)); channelManager_.onServerFailed(server, finalFailoverReason); }
void HttpClient::doSocketClose() { KAA_LOG_INFO("Closing socket connection..."); boost::system::error_code errorCode; sock_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, errorCode); sock_.close(errorCode); }
kaa_error_t kaa_client_create(kaa_client_t **client, kaa_client_props_t *props) { (void)props; KAA_RETURN_IF_NIL(client, KAA_ERR_BADPARAM); kaa_client_t *self = (kaa_client_t*)KAA_CALLOC(1, sizeof(kaa_client_t)); KAA_RETURN_IF_NIL(self, KAA_ERR_NOMEM); kaa_error_t error_code = kaa_init(&self->context); if(error_code) { printf("Error initialising kaa_context\n"); kaa_client_destroy(self); return error_code; } self->operate = true; #ifndef KAA_DISABLE_FEATURE_LOGGING error_code = kaa_log_collector_init(self); if (error_code) { KAA_LOG_ERROR(self->context->logger, error_code, "Failed to init Kaa log collector, error %d", error_code); kaa_client_destroy(self); return error_code; } #endif KAA_LOG_INFO(self->context->logger,KAA_ERR_NONE, "Kaa client initiallized"); *client = self; return error_code; }
kaa_error_t kaa_client_deinit_channel(kaa_client_t *kaa_client) { KAA_RETURN_IF_NIL(kaa_client, KAA_ERR_BADPARAM); kaa_error_t error_code = KAA_ERR_NONE; if (kaa_client->channel_id == 0) return KAA_ERR_NONE; KAA_LOG_TRACE(kaa_client->kaa_context->logger, KAA_ERR_NONE, "Deinitializing channel...."); error_code = kaa_channel_manager_remove_transport_channel( kaa_client->kaa_context->channel_manager,kaa_client->channel_id); if (error_code) { KAA_LOG_TRACE(kaa_client->kaa_context->logger, error_code, "Bootstrap channel error removing from channel manager"); return error_code; } kaa_client->channel_id = 0; kaa_client->channel.context = NULL; kaa_client->channel.destroy = NULL; kaa_client->channel.get_protocol_id = NULL; kaa_client->channel.get_supported_services = NULL; kaa_client->channel.init = NULL; kaa_client->channel.set_access_point = NULL; kaa_client->channel.sync_handler = NULL; KAA_LOG_INFO(kaa_client->kaa_context->logger, KAA_ERR_NONE, "Channel deinitialized successfully"); return error_code; }
kaa_error_t kaa_profile_manager_update_profile(kaa_profile_manager_t *self, kaa_profile_t *profile_body) { #if KAA_PROFILE_SCHEMA_VERSION > 0 KAA_RETURN_IF_NIL2(self, profile_body, KAA_ERR_BADPARAM); size_t serialized_profile_size = profile_body->get_size(profile_body); if (!serialized_profile_size) { KAA_LOG_ERROR(self->logger, KAA_ERR_BADDATA, "Failed to update profile: serialize profile size is null. Maybe profile schema is empty"); return KAA_ERR_BADDATA; } char *serialized_profile = (char *) KAA_MALLOC(serialized_profile_size * sizeof(char)); KAA_RETURN_IF_NIL(serialized_profile, KAA_ERR_NOMEM); avro_writer_t writer = avro_writer_memory(serialized_profile, serialized_profile_size); if (!writer) { KAA_FREE(serialized_profile); return KAA_ERR_NOMEM; } profile_body->serialize(writer, profile_body); avro_writer_free(writer); kaa_digest new_hash; ext_calculate_sha_hash(serialized_profile, serialized_profile_size, new_hash); if (!memcmp(new_hash, self->status->profile_hash, SHA_1_DIGEST_LENGTH)) { self->need_resync = false; KAA_FREE(serialized_profile); return KAA_ERR_NONE; } KAA_LOG_INFO(self->logger, KAA_ERR_NONE, "Endpoint profile is updated"); if (ext_copy_sha_hash(self->status->profile_hash, new_hash)) { KAA_FREE(serialized_profile); return KAA_ERR_BAD_STATE; } if (self->profile_body.size > 0) { KAA_FREE(self->profile_body.buffer); self->profile_body.buffer = NULL; } self->profile_body.buffer = (uint8_t*)serialized_profile; self->profile_body.size = serialized_profile_size; self->need_resync = true; kaa_transport_channel_interface_t *channel = kaa_channel_manager_get_transport_channel(self->channel_manager, profile_sync_services[0]); if (channel) channel->sync_handler(channel->context, profile_sync_services, 1); #endif return KAA_ERR_NONE; }
kaa_error_t kaa_client_stop(kaa_client_t *kaa_client) { KAA_RETURN_IF_NIL(kaa_client, KAA_ERR_BADPARAM); KAA_LOG_INFO(kaa_client->context->logger, KAA_ERR_NONE, "Going to stop Kaa client..."); kaa_client->operate = false; return kaa_stop(kaa_client->context); }
void LogCollector::setUploadStrategy(ILogUploadStrategyPtr strategy) { if (!strategy) { KAA_LOG_ERROR("Failed to set log upload strategy: bad data"); throw KaaException("Bad log upload strategy"); } KAA_LOG_INFO("New log upload strategy was set"); uploadStrategy_ = strategy; }
void KaaClient::setFailoverStrategy(IFailoverStrategyPtr strategy) { if (!strategy) { KAA_LOG_ERROR("Failed to set failover strategy: bad data"); throw KaaException("Bad failover strategy"); } KAA_LOG_INFO("New failover strategy was set"); failoverStrategy_ = strategy; channelManager_->setFailoverStrategy(failoverStrategy_); }
kaa_error_t kaa_init(kaa_context_t **kaa_context_p) { KAA_RETURN_IF_NIL(kaa_context_p, KAA_ERR_BADPARAM); // Initialize logger kaa_logger_t *logger = NULL; FILE *logfile = fopen("run.log", "w"); kaa_error_t error = kaa_log_create(&logger, KAA_MAX_LOG_MESSAGE_LENGTH, KAA_MAX_LOG_LEVEL, logfile); // TODO: make log destination configurable if (error) return error; KAA_LOG_INFO(logger, KAA_ERR_NONE, "Kaa SDK version %s, commit hash %s", BUILD_VERSION, BUILD_COMMIT_HASH); // Initialize general Kaa context error = kaa_context_create(kaa_context_p, logger); if (error) { KAA_LOG_FATAL(logger, error, "Failed to create Kaa context"); kaa_log_destroy(logger); *kaa_context_p = NULL; return error; } // Initialize endpoint identity char *pub_key_buffer = NULL; size_t pub_key_buffer_size = 0; bool need_deallocation = false; ext_get_endpoint_public_key(&pub_key_buffer, &pub_key_buffer_size, &need_deallocation); kaa_digest pub_key_hash; error = ext_calculate_sha_hash(pub_key_buffer, pub_key_buffer_size, pub_key_hash); if (need_deallocation && pub_key_buffer_size > 0) { KAA_FREE(pub_key_buffer); } if (error) { KAA_LOG_FATAL(logger, error, "Failed to calculate EP ID"); kaa_context_destroy(*kaa_context_p); *kaa_context_p = NULL; kaa_log_destroy(logger); return error; } error = ext_copy_sha_hash((*kaa_context_p)->status->status_instance->endpoint_public_key_hash, pub_key_hash); if (error) { KAA_LOG_FATAL(logger, error, "Failed to set Endpoint public key"); kaa_context_destroy(*kaa_context_p); *kaa_context_p = NULL; kaa_log_destroy(logger); return error; } return KAA_ERR_NONE; }
kaa_error_t kaa_client_state_process(kaa_client_t *kaa_client) { KAA_RETURN_IF_NIL(kaa_client, KAA_ERR_BADPARAM); kaa_error_t error_code = KAA_ERR_NONE; esp8266_error_t esp8266_error; switch (kaa_client->connection_state) { case KAA_CLIENT_ESP8266_STATE_UNINITED: esp8266_error = esp8266_init(kaa_client->controler); if (esp8266_error == ESP8266_ERR_NONE) { kaa_client->connection_state = KAA_CLIENT_ESP8266_STATE_INIT_OK; KAA_LOG_INFO(kaa_client->kaa_context->logger, KAA_ERR_NONE, "ESP8266 initialized successfully"); } else { KAA_LOG_ERROR(kaa_client->kaa_context->logger, KAA_ERR_NONE, "ESP8266 initialization failed: %d", esp8266_error); esp8266_reset(); } break; case KAA_CLIENT_ESP8266_STATE_INIT_OK: ledOn(); esp8266_error = esp8266_connect_wifi(kaa_client->controler, kaa_client->wifi_ssid, kaa_client->wifi_pswd); if (esp8266_error == ESP8266_ERR_NONE) { kaa_client->connection_state = KAA_CLIENT_WIFI_STATE_CONNECTED; KAA_LOG_INFO(kaa_client->kaa_context->logger, KAA_ERR_NONE, "ESP8266 WiFi to %s network connected", kaa_client->wifi_ssid); } else { KAA_LOG_ERROR(kaa_client->kaa_context->logger, KAA_ERR_NONE, "ESP8266 connect to WiFi %s failed: %d", kaa_client->wifi_ssid, esp8266_error); kaa_client->connection_state = KAA_CLIENT_WIFI_STATE_UNCONNECTED; } ledOff(); break; case KAA_CLIENT_WIFI_STATE_CONNECTED: break; default: kaa_client->connection_state = KAA_CLIENT_ESP8266_STATE_UNINITED; break; } return error_code; }
virtual LogUploadStrategyDecision isUploadNeeded(ILogStorageStatus& status) override { auto currentRecordCount = status.getRecordsCount(); if (currentRecordCount >= uploadCountThreshold_) { KAA_LOG_INFO(boost::format("Need to upload logs - current count: %llu, threshold: %llu") % currentRecordCount % uploadCountThreshold_); return LogUploadStrategyDecision::UPLOAD; } return LogUploadStrategyDecision::NOOP; }
kaa_error_t kaa_client_stop(kaa_client_t *kaa_client) { KAA_RETURN_IF_NIL(kaa_client, KAA_ERR_BADPARAM); kaa_error_t error_code = KAA_ERR_NONE; kaa_client->operate = false; KAA_LOG_INFO(kaa_client->kaa_context->logger, KAA_ERR_NONE, "Stopping Kaa client..."); return error_code; }
/* * Initializes Kaa log collector. */ kaa_error_t kaa_log_collector_init(kaa_client_t *kaa_client) { KAA_RETURN_IF_NIL(kaa_client, KAA_ERR_BADPARAM) kaa_error_t error_code = ext_unlimited_log_storage_create(&kaa_client->log_storage_context , kaa_client->kaa_context->logger); if (error_code) { KAA_LOG_ERROR(kaa_client->kaa_context->logger, error_code, "Failed to create log storage"); return error_code; } error_code = ext_log_upload_strategy_create(kaa_client->kaa_context ,&kaa_client->log_upload_strategy_context , KAA_LOG_UPLOAD_VOLUME_STRATEGY); if (error_code) { KAA_LOG_ERROR(kaa_client->kaa_context->logger, error_code, "Failed to create log upload strategy"); return error_code; } // Due to unknown problems with networking via ESP8266, some server responses are lost. // It leads to log delivery timeouts. error_code = ext_log_upload_strategy_set_upload_timeout(kaa_client->log_upload_strategy_context , KAA_DEMO_TWO_DAYS_UPLOAD_TIMEOUT); if (error_code) { KAA_LOG_ERROR(kaa_client->kaa_context->logger, error_code, "Failed to create log upload strategy by volume set upload timeout to %d", KAA_DEMO_TWO_DAYS_UPLOAD_TIMEOUT); return error_code; } error_code = ext_log_upload_strategy_et_threshold_count(kaa_client->log_upload_strategy_context , KAA_DEMO_UPLOAD_COUNT_THRESHOLD); if (error_code) { KAA_LOG_ERROR(kaa_client->kaa_context->logger, error_code, "Failed to create log upload strategy by volume set threshold count to %d", KAA_DEMO_UPLOAD_COUNT_THRESHOLD); return error_code; } error_code = kaa_logging_init(kaa_client->kaa_context->log_collector , kaa_client->log_storage_context , kaa_client->log_upload_strategy_context); if (error_code) { KAA_LOG_ERROR(kaa_client->kaa_context->logger, error_code,"Failed to logging init"); return error_code; } KAA_LOG_INFO(kaa_client->kaa_context->logger, KAA_ERR_NONE, "Log collector init complete"); return error_code; }
/* * Initializes Kaa log collector. */ kaa_error_t kaa_log_collector_init(kaa_client_t *kaa_client) { KAA_RETURN_IF_NIL(kaa_client, KAA_ERR_BADPARAM); kaa_error_t error_code = ext_unlimited_log_storage_create( &kaa_client->log_storage_context, kaa_client->kaa_context->logger); if (error_code) { KAA_LOG_ERROR(kaa_client->kaa_context->logger, error_code, "Failed to create log storage"); return error_code; } error_code = ext_log_upload_strategy_create(kaa_client->kaa_context ,&kaa_client->log_upload_strategy_context , KAA_LOG_UPLOAD_VOLUME_STRATEGY); if (error_code) { KAA_LOG_ERROR(kaa_client->kaa_context->logger, error_code, "Failed to create log upload strategy"); return error_code; } error_code = ext_log_upload_strategy_set_threshold_count(kaa_client->log_upload_strategy_context , KAA_DEMO_UPLOAD_COUNT_THRESHOLD); if (error_code) { KAA_LOG_ERROR(kaa_client->kaa_context->logger, error_code, "Failed to create log upload strategy by volume set threshold count to %d", KAA_DEMO_UPLOAD_COUNT_THRESHOLD); return error_code; } error_code = kaa_logging_init(kaa_client->kaa_context->log_collector , kaa_client->log_storage_context , kaa_client->log_upload_strategy_context); if (error_code) { KAA_LOG_ERROR(kaa_client->kaa_context->logger, error_code, "Failed to logging init"); return error_code; } KAA_LOG_INFO(kaa_client->kaa_context->logger, KAA_ERR_NONE, "Log collector init complete"); return error_code; }
void ConfigurationManager::loadConfiguration() { if (storage_) { if (state_->isSDKPropertiesUpdated()) { KAA_LOG_INFO("Ignore loading configuration from storage: configuration version updated"); storage_->clearConfiguration(); } else { auto data = storage_->loadConfiguration(); if (!data.empty()) { updateConfiguration(data.data(), data.size()); isConfigurationLoaded_ = true; KAA_LOG_INFO("Loaded configuration from storage"); } } } if (!isConfigurationLoaded_) { const Botan::SecureVector<std::uint8_t>& config = getDefaultConfigData(); updateConfiguration(config.begin(), config.size()); isConfigurationLoaded_ = true; KAA_LOG_INFO("Loaded default configuration"); } }
void LogCollector::setStorage(ILogStoragePtr storage) { if (!storage) { KAA_LOG_ERROR("Failed to set log storage: bad data"); throw KaaException("Bad log storage"); } KAA_MUTEX_LOCKING("storageGuard_"); KAA_MUTEX_UNIQUE_DECLARE(storageGuardLock, storageGuard_); KAA_MUTEX_LOCKED("storageGuard_"); KAA_LOG_INFO("New log storage was set"); storage_ = storage; }
void ClientStatus::checkSDKPropertiesForUpdates() { HashDigest truePropertiesHash = getPropertiesHash(); HashDigest storedPropertiesHash; auto parameter_it = parameters_.find(ClientParameterT::PROPERTIES_HASH); if (parameter_it != parameters_.end()) { storedPropertiesHash = boost::any_cast<HashDigest>(parameter_it->second->getValue()); } if (truePropertiesHash != storedPropertiesHash) { setRegistered(false); auto it = parameters_.find(ClientParameterT::PROPERTIES_HASH); if (it != parameters_.end()) { it->second->setValue(truePropertiesHash); } isSDKPropertiesForUpdated_ = true; KAA_LOG_INFO("SDK properties were updated"); } else { KAA_LOG_INFO("SDK properties are up to date"); } }