Init
This commit is contained in:
commit
950e7b7e2d
350 files changed
+38599
No files matched your search
@@ -0,0 +1,2 @@
|
||||
build/
|
||||
.dir-locals.el
|
||||
@@ -0,0 +1,25 @@
|
||||
cmake_minimum_required(VERSION 3.5)
|
||||
project(spark)
|
||||
|
||||
if (WIN32)
|
||||
include_directories ("c:/externals/include")
|
||||
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} \
|
||||
/MP \
|
||||
/WX /wd4251 /wd4250 /wd4251 /wd4244 /wd4267 /wd4355 /wd4275 /wd4345 \
|
||||
/DCURL_STATICLIB
|
||||
/D_SCL_SECURE_NO_WARNINGS /D_CRT_SECURE_NO_WARNINGS /D_WIN32_WINNT=0x0600")
|
||||
|
||||
set (CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MTd")
|
||||
set (CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_DEBUG} /MT")
|
||||
|
||||
add_subdirectory(src/lib)
|
||||
add_subdirectory(src/client/tools)
|
||||
else()
|
||||
|
||||
set (CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} \
|
||||
-Wall -pedantic -Wextra -Werror -Weffc++ -Wno-missing-braces --std=c++14")
|
||||
|
||||
set (CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_DEBUG} -DNDEBUG -O3")
|
||||
add_subdirectory(src/lib)
|
||||
add_subdirectory(src/server/sparkd)
|
||||
endif()
|
||||
@@ -0,0 +1,30 @@
|
||||
cmake_minimum_required(VERSION 3.5)
|
||||
project(spark_tool)
|
||||
|
||||
# proto sources
|
||||
set (Protos
|
||||
)
|
||||
|
||||
include(${CMAKE_SOURCE_DIR}/tools/Protobuf.cmake)
|
||||
protobuf_generate_cpp( Proto_Srcs PROTO_HDRS ${Protos} )
|
||||
|
||||
# cpp sources
|
||||
set (Spark_Tool_Sources
|
||||
main.cpp
|
||||
)
|
||||
|
||||
# sparkd
|
||||
add_executable(spark_tool ${Spark_Tool_Sources} ${Proto_Srcs})
|
||||
|
||||
#include paths
|
||||
target_include_directories( spark_tool PUBLIC ${CMAKE_SOURCE_DIR}/src ${CMAKE_BINARY_DIR}/src)
|
||||
|
||||
# linking
|
||||
target_link_libraries( spark_tool
|
||||
spark_lib
|
||||
-static-libgcc
|
||||
-static-libstdc++)
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
#include "lib/logging/logging.h"
|
||||
|
||||
int main()
|
||||
{return 0;}
|
||||
@@ -0,0 +1,193 @@
|
||||
cmake_minimum_required(VERSION 3.5)
|
||||
project(spark_lib)
|
||||
|
||||
# config protos
|
||||
set (Config_Protos
|
||||
config/protos/system.proto
|
||||
config/protos/testkeys.proto
|
||||
config/protos/logging.proto
|
||||
config/protos/quickbus_cfg.proto
|
||||
config/protos/jetfix.proto
|
||||
config/protos/MarketData.proto
|
||||
config/protos/Symbols.proto
|
||||
config/protos/Ports.proto
|
||||
)
|
||||
|
||||
# non config/non service protos
|
||||
set (NonConfig_Protos
|
||||
config/invalid/invalid.proto
|
||||
config/extensions/extensions.proto
|
||||
quickbus/network/quickbus_msgs.proto
|
||||
security_model/security.proto
|
||||
api/apicore.proto
|
||||
api/apioptions.proto
|
||||
)
|
||||
|
||||
# service protos
|
||||
set (Service_Protos
|
||||
# api/services/Hello.proto
|
||||
)
|
||||
|
||||
include(${CMAKE_SOURCE_DIR}/tools/Protobuf.cmake)
|
||||
protobuf_generate_cpp( PROTO_SRCS PROTO_HDRS ${NonConfig_Protos} ${Config_Protos})
|
||||
service_compiler_generate_cpp(SERVICE_COMPILER_SRCS SERVICE_COMPILER_HDRS ${Service_Protos})
|
||||
|
||||
# srcs for sparkd
|
||||
set (SparkLib_Sources
|
||||
|
||||
# api
|
||||
api/core/ApiClientInterop.cpp
|
||||
api/core/ApiServerInterop.cpp
|
||||
api/public/ApiServer.cpp
|
||||
api/public/ClientChannel.cpp
|
||||
api/public/QuickbusClientChannel.cpp
|
||||
api/public/ServerChannel.cpp
|
||||
api/public/ServiceContext.cpp
|
||||
# api/test/ApiTests.cpp
|
||||
# api/test/HelloServiceServer.cpp
|
||||
|
||||
# expression
|
||||
expression/BooleanGrammar.cpp
|
||||
expression/ExpressionEvaluator.cpp
|
||||
expression/ParserExceptions.cpp
|
||||
expression/Value.cpp
|
||||
|
||||
# config
|
||||
config/config.cpp
|
||||
config/ConfigDownloader.cpp
|
||||
config/ConfigErrorCollector.cpp
|
||||
config/ConfigLog.cpp
|
||||
config/ConfigPropertyEvaluator.cpp
|
||||
config/ConfigurationException.cpp
|
||||
config/ConfigurationState.cpp
|
||||
config/ConfigValueQueue.cpp
|
||||
config/PreprocessInputStream.cpp
|
||||
config/text_format/text_format.cpp
|
||||
config/tests/config_ref_tests.cpp
|
||||
config/tests/HTTPServer.cpp
|
||||
config/tests/config_tests.cpp
|
||||
|
||||
# quickbus
|
||||
quickbus/core/LocalNode.cpp
|
||||
quickbus/core/Quickbus.cpp
|
||||
quickbus/core/SubscriptionID.cpp
|
||||
quickbus/core/TableID.cpp
|
||||
quickbus/message_model/Update.cpp
|
||||
quickbus/message_model/merge_updates.cpp
|
||||
quickbus/network/QBConnection.cpp
|
||||
quickbus/network/QBConnectionManager.cpp
|
||||
quickbus/network/endpoint_description.cpp
|
||||
quickbus/pubsub/TablePublisher.cpp
|
||||
quickbus/pubsub/TableSubscriber.cpp
|
||||
quickbus/pubsub/tests/qb_pubsub_tests.cpp
|
||||
quickbus/routing/INode.cpp
|
||||
quickbus/routing/NodeID.cpp
|
||||
quickbus/routing/Router.cpp
|
||||
quickbus/rpc/RPCClient.cpp
|
||||
quickbus/rpc/RPCServer.cpp
|
||||
quickbus/rpc/RPCSessionID.cpp
|
||||
quickbus/rpc/rpc_utils.cpp
|
||||
quickbus/rpc/tests/qb_rpc_tests.cpp
|
||||
quickbus/tests/quickbus_tests.cpp
|
||||
|
||||
# OS
|
||||
os/os.cpp
|
||||
|
||||
#logging
|
||||
logging/logging.cpp
|
||||
logging/tests/logging_tests.cpp
|
||||
logging/LoggerHub.cpp
|
||||
logging/Sink.cpp
|
||||
|
||||
# misc utils
|
||||
utils/is_unittest_environment.cpp
|
||||
utils/datetime.cpp
|
||||
utils/PBUtils.cpp
|
||||
utils/Uuid.cpp
|
||||
utils/file_utils.cpp
|
||||
utils/HTTPStream.cpp
|
||||
utils/SharedMemory.cpp
|
||||
utils/Dispatcher.cpp
|
||||
utils/Sqlite_utils.cpp
|
||||
utils/catch_test_runner.cpp
|
||||
|
||||
# security model
|
||||
security_model/SecurityHelper.cpp
|
||||
)
|
||||
|
||||
|
||||
# generate list of config protos
|
||||
set(config_proto_file ${CMAKE_CURRENT_BINARY_DIR}/config_proto_files.h)
|
||||
file(REMOVE ${config_proto_file})
|
||||
file(COPY config/defaults DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
|
||||
file(APPEND ${config_proto_file} "const char * config_proto_files[] = { // generated file\n")
|
||||
foreach(protopath ${Config_Protos})
|
||||
get_filename_component(protoname ${protopath} NAME)
|
||||
file(APPEND ${config_proto_file} "\"${protoname}\",\n")
|
||||
endforeach(protopath)
|
||||
file(APPEND ${config_proto_file} "};\n")
|
||||
|
||||
|
||||
# spark_lib
|
||||
if (WIN32)
|
||||
add_library(spark_lib SHARED
|
||||
${SparkLib_Sources}
|
||||
${PROTO_SRCS}
|
||||
${SERVICE_COMPILER_SRCS}
|
||||
)
|
||||
else ()
|
||||
add_library(spark_lib STATIC
|
||||
${SparkLib_Sources}
|
||||
${PROTO_SRCS}
|
||||
${SERVICE_COMPILER_SRCS}
|
||||
)
|
||||
endif()
|
||||
|
||||
|
||||
#include paths
|
||||
target_include_directories( spark_lib PUBLIC
|
||||
${CMAKE_SOURCE_DIR}/src
|
||||
${CMAKE_BINARY_DIR}/src
|
||||
${Protobuf_INCLUDE_DIRS}
|
||||
${Boost_INCLUDE_DIRS}
|
||||
)
|
||||
|
||||
if (WIN32)
|
||||
|
||||
find_package(Boost REQUIRED COMPONENTS system thread filesystem regex chrono date_time atomic)
|
||||
find_library (FMT NAMES fmt.lib)
|
||||
find_library (SQLITE NAMES sqlite3.lib)
|
||||
|
||||
if(CMAKE_BUILD_TYPE MATCHES "^Debug$" OR NOT DEFINED CMAKE_BUILD_TYPE)
|
||||
target_include_directories (spark_lib PUBLIC "c:/externals/curl-debug/include")
|
||||
target_link_libraries( spark_lib "c:/externals/curl-debug/lib/libcurl_a_debug.lib")
|
||||
else()
|
||||
target_include_directories (spark_lib PUBLIC "c:/externals/curl-release/include")
|
||||
target_link_libraries( spark_lib "c:/externals/curl-release/lib/libcurl_a.lib")
|
||||
endif()
|
||||
|
||||
target_link_libraries( spark_lib
|
||||
${Boost_LIBRARIES}
|
||||
${Protobuf_Static_Lib}
|
||||
${FMT}
|
||||
${SQLITE}
|
||||
)
|
||||
else ()
|
||||
set(Boost_USE_STATIC_LIBS ON)
|
||||
find_package(Boost REQUIRED COMPONENTS system thread filesystem regex chrono date_time atomic)
|
||||
|
||||
target_link_libraries( spark_lib
|
||||
${Boost_LIBRARIES}
|
||||
${Protobuf_Static_Lib}
|
||||
curl.a
|
||||
fmt.a
|
||||
uuid.a
|
||||
sqlite3.a
|
||||
-lrt
|
||||
-ldl
|
||||
-static-libgcc
|
||||
-static-libstdc++
|
||||
-pthread)
|
||||
endif()
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
syntax="proto3";
|
||||
import "lib/api/apioptions.proto";
|
||||
package bts.api;
|
||||
option csharp_namespace="bts.api";
|
||||
|
||||
message PingPong {
|
||||
bytes payload = 1;
|
||||
}
|
||||
|
||||
message RequestHeader {
|
||||
int32 request_id = 1;
|
||||
int32 method = 2;
|
||||
}
|
||||
|
||||
enum ApiError {
|
||||
SUCCESS = 0;
|
||||
NO_SERVER = 1;
|
||||
SERVER_DISCONNECT = 2;
|
||||
MISSING_METHOD = 3;
|
||||
SERVER_FAULT = 4;
|
||||
UNEXPECTED_RESPONSE = 5;
|
||||
}
|
||||
|
||||
message ResponseHeader {
|
||||
int32 request_id = 1;
|
||||
ApiError code = 2;
|
||||
}
|
||||
|
||||
// Some Useful buffers for use as arguments/returns
|
||||
|
||||
message VoidMessage {}
|
||||
message BytesMessage {
|
||||
bytes buffer = 1;
|
||||
}
|
||||
message BoolResultMessage {
|
||||
bool success = 1;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
syntax="proto3";
|
||||
import "google/protobuf/descriptor.proto";
|
||||
package bts.api;
|
||||
option csharp_namespace="bts.api";
|
||||
|
||||
extend google.protobuf.MessageOptions {
|
||||
string message_description = 8500;
|
||||
}
|
||||
extend google.protobuf.ServiceOptions {
|
||||
string service_description = 8501;
|
||||
}
|
||||
extend google.protobuf.FieldOptions {
|
||||
bool key = 8502;
|
||||
string field_description = 8503;
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
#include "ApiClientInterop.h"
|
||||
#include "lib/quickbus/quickbus.h"
|
||||
#include "lib/config/config.h"
|
||||
#include "lib/logging/logging.h"
|
||||
|
||||
#include "../public/ServiceContext.h"
|
||||
#include "../public/Result.h"
|
||||
|
||||
#include "lib/api/apicore.pb.h"
|
||||
#include "lib/config/protos/quickbus_cfg.pb.h"
|
||||
#include "lib/config/protos/system.pb.h"
|
||||
#include "lib/config/protos/Ports.pb.h"
|
||||
|
||||
#ifdef WIN32
|
||||
#include <excpt.h>
|
||||
#endif
|
||||
|
||||
namespace bts {
|
||||
namespace api {
|
||||
|
||||
config::QuickbusNodeCfg get_client_node_cfg()
|
||||
{
|
||||
auto cfg = config::get<config::QuickbusCfg>();
|
||||
config::QuickbusNodeCfg node_cfg;
|
||||
node_cfg.set_reconnect_period_secs(cfg.reconnect_period_secs());
|
||||
node_cfg.set_hb_period_msecs(cfg.hb_period_msecs());
|
||||
node_cfg.set_max_missed_hbs(cfg.max_missed_hbs());
|
||||
node_cfg.set_parent_host(
|
||||
cfg.has_qbus_host() ?
|
||||
cfg.qbus_host() :
|
||||
config::get<config::System>().config_ip()
|
||||
);
|
||||
node_cfg.set_parent_port(
|
||||
cfg.has_qbus_port() ?
|
||||
cfg.qbus_port() :
|
||||
config::get<config::Ports>().qbus_port()
|
||||
);
|
||||
node_cfg.set_my_port(0);
|
||||
return node_cfg;
|
||||
}
|
||||
|
||||
//
|
||||
// Common
|
||||
|
||||
BTS_EXPORT Quickbus* api_create_quickbus(const char* qbconfig, long length) {
|
||||
// If config hasn't been initialized yet do it now and suppress exceptions.
|
||||
// When we're called from a nuget package we may not have defaults which can cause errors
|
||||
config::initialize_nothrow(nullptr, 0);
|
||||
|
||||
config::QuickbusNodeCfg cfg;
|
||||
if (length > 0 && qbconfig != nullptr && cfg.ParseFromArray(qbconfig, length)) {
|
||||
return new Quickbus(cfg);
|
||||
}
|
||||
|
||||
// Note: Eventually api will probably want it's own instance of QB. For now we share
|
||||
auto temp_conf = get_client_node_cfg();
|
||||
LOG(Api,Info,"Created Quickbus");
|
||||
return new Quickbus(temp_conf);
|
||||
}
|
||||
|
||||
BTS_EXPORT void api_destroy_quickbus(Quickbus* qbus) {
|
||||
if (qbus != nullptr) {
|
||||
delete qbus;
|
||||
}
|
||||
}
|
||||
|
||||
std::string base_topic(const char* type_name, const char* service_qualifier) {
|
||||
const std::string topic_base = "api-";
|
||||
if (service_qualifier == nullptr ||
|
||||
strlen(service_qualifier) == 0) {
|
||||
return topic_base + type_name;
|
||||
}
|
||||
return topic_base + type_name + "-" + service_qualifier;
|
||||
}
|
||||
|
||||
qbus::RPCServiceName rpc_topic(const std::string& base_topic) {
|
||||
return qbus::RPCServiceName(base_topic);
|
||||
}
|
||||
|
||||
|
||||
//
|
||||
// Client
|
||||
|
||||
struct ApiClient {
|
||||
ApiClient(Quickbus& qbus, const std::string& topic) :
|
||||
qbus(qbus),
|
||||
service_name(topic),
|
||||
rpc(qbus, rpc_topic(topic)) {}
|
||||
|
||||
Quickbus& qbus;
|
||||
std::string service_name;
|
||||
qbus::RPCClient rpc;
|
||||
};
|
||||
|
||||
BTS_EXPORT ApiClient* api_client_create(Quickbus* pqbus, const char* type_name, const char* service_qualifier) {
|
||||
bts_assert(pqbus);
|
||||
auto service_name = base_topic(type_name, service_qualifier);
|
||||
LOG(Api,Info, "create client: {}",service_name);
|
||||
ApiClient* pclient = new ApiClient(*pqbus, service_name);
|
||||
return pclient;
|
||||
}
|
||||
|
||||
BTS_EXPORT void api_client_destroy(ApiClient* pclient) {
|
||||
if (pclient) {
|
||||
LOG(Api,Info, "destroy client: {}",pclient->service_name);
|
||||
delete pclient;
|
||||
}
|
||||
}
|
||||
|
||||
void reply_error(ApiError error, raw_response_callback cb, void* extra) {
|
||||
ResponseHeader response;
|
||||
response.set_code(error);
|
||||
auto str = response.SerializeAsString();
|
||||
str = (char)(str.size()+1) + str;
|
||||
cb(str.c_str(), str.size(), extra);
|
||||
}
|
||||
|
||||
BTS_EXPORT void api_client_send(ApiClient* pclient, const char* buffer, int buffer_length, raw_response_callback cb, void* extra) {
|
||||
bts_assert(pclient);
|
||||
std::string strbuf(buffer, buffer_length);
|
||||
qbus::RPCRequest request(move(strbuf));
|
||||
pclient->rpc.wait_until_connected(1);
|
||||
LOG(Api,Diag,"send rpc {}",((int64_t)buffer));
|
||||
pclient->rpc.send(std::move(request), [=](qbus::RPCError e, const qbus::RPCReplyPtr& reply) {
|
||||
LOG(Api,Diag,"rpc reply {}",((int64_t)buffer));
|
||||
switch (e) {
|
||||
case qbus::RPCError::RPC_OK:
|
||||
cb(reply->value().c_str(), reply->value().size(), extra);
|
||||
break;
|
||||
case qbus::RPCError::NO_SERVER:
|
||||
reply_error(ApiError::NO_SERVER, cb, extra);
|
||||
break;
|
||||
case qbus::RPCError::SERVER_DISCONNECT:
|
||||
reply_error(ApiError::SERVER_DISCONNECT, cb, extra);
|
||||
break;
|
||||
default:
|
||||
reply_error(ApiError::UNEXPECTED_RESPONSE, cb, extra);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
BTS_EXPORT bool api_client_is_on_qb_thread(ApiClient* pclient) {
|
||||
return pclient->qbus.on_qb_thread();
|
||||
}
|
||||
|
||||
|
||||
void safe_call_subscription_callback(raw_subscription_callback cb, EventType type, const std::vector<StreamUpdate>& updates, void* extra) {
|
||||
#ifdef _MSC_VER
|
||||
__try {
|
||||
#endif
|
||||
if (updates.size() > 0) {
|
||||
cb(type, &updates[0], updates.size(), extra);
|
||||
}
|
||||
#ifdef _MSC_VER
|
||||
}
|
||||
__except(EXCEPTION_EXECUTE_HANDLER) { }
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
bts::qbus::Topic stream_topic(const std::string& base_topic, const char* method_and_qualifier) {
|
||||
return qbus::Topic(base_topic + "-" + method_and_qualifier);
|
||||
}
|
||||
|
||||
BTS_EXPORT TableSubscription api_client_subscribe(ApiClient* pclient, const char* method_and_qualifier, raw_subscription_callback cb, void* extra) {
|
||||
bts_assert(pclient);
|
||||
static_assert((int)qbus::TableEvent::EventType::TABLE_CREATED == EventType::TABLE_CREATED, "Keep these Enums in sync");
|
||||
static_assert((int)qbus::TableEvent::EventType::TABLE_DESTROYED == EventType::TABLE_DESTROYED, "");
|
||||
static_assert((int)qbus::TableEvent::EventType::TABLE_UPDATED == EventType::TABLE_UPDATED, "");
|
||||
static_assert((int)qbus::Change::Type::REMOVE == StreamUpdate::REMOVE, "");
|
||||
static_assert((int)qbus::Change::Type::REPLACE == StreamUpdate::REPLACE, "");
|
||||
static_assert((int)qbus::Change::Type::CREATE == StreamUpdate::CREATE, "");
|
||||
|
||||
auto topic = stream_topic(pclient->service_name, method_and_qualifier);
|
||||
LOG(Api,Info,"api subscribe: {}" ,topic.value());
|
||||
|
||||
auto result = new qbus::TableSubscriber(pclient->qbus, equal_topic(topic), [cb, extra](const qbus::TableEvent& ev) {
|
||||
if (ev.event_type == qbus::TableEvent::EventType::TABLE_CREATED ||
|
||||
ev.event_type == qbus::TableEvent::EventType::TABLE_DESTROYED) {
|
||||
cb((EventType)ev.event_type, nullptr, 0, extra);
|
||||
}
|
||||
else {
|
||||
bts_assert(ev.update != nullptr);
|
||||
size_t update_count = ev.update->size();
|
||||
std::vector<StreamUpdate> bupdates(update_count);
|
||||
// Copy structure for interop
|
||||
for (size_t x = 0; x < update_count; ++x) {
|
||||
const auto& update = (*ev.update)[x];
|
||||
bupdates[x].type = static_cast<StreamUpdate::Type>(update.type);
|
||||
bupdates[x].key = update.key.value();
|
||||
const auto& val = update.value->value();
|
||||
bupdates[x].buffer_len = val.size();
|
||||
bupdates[x].buffer = val.c_str();
|
||||
}
|
||||
safe_call_subscription_callback(cb, (EventType)ev.event_type, bupdates, extra);
|
||||
}
|
||||
}, true);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
BTS_EXPORT void api_client_unsubscribe(ApiClient* pclient, TableSubscription pvtable) {
|
||||
qbus::TableSubscriber* ptable = static_cast<qbus::TableSubscriber*>(pvtable);
|
||||
if (pclient && ptable) {
|
||||
ptable->disconnect();
|
||||
delete ptable;
|
||||
}
|
||||
}
|
||||
|
||||
}}// namespace
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
#include "ApiInteropCommon.h"
|
||||
|
||||
namespace bts {
|
||||
namespace api {
|
||||
|
||||
struct ApiClient;
|
||||
BTS_EXPORT ApiClient* api_client_create(Quickbus*, const char* type_name, const char* service_qualifier);
|
||||
BTS_EXPORT void api_client_destroy(ApiClient*);
|
||||
typedef void(*raw_response_callback)(const char* buffer, size_t length, void* extra);
|
||||
BTS_EXPORT void api_client_send(ApiClient* pclient, const char* buffer, int buffer_length, raw_response_callback cb, void* extra);
|
||||
BTS_EXPORT bool api_client_is_on_qb_thread(ApiClient*);
|
||||
|
||||
enum EventType {
|
||||
TABLE_CREATED,
|
||||
TABLE_UPDATED,
|
||||
TABLE_DESTROYED
|
||||
};
|
||||
|
||||
typedef void* TableSubscription;
|
||||
typedef void(*raw_subscription_callback)(EventType event_type, const StreamUpdate* changes, int count, void* extra);
|
||||
BTS_EXPORT TableSubscription api_client_subscribe(ApiClient* pclient, const char* method_and_qualifier, raw_subscription_callback cb, void* extra);
|
||||
BTS_EXPORT void api_client_unsubscribe(ApiClient* pclient, TableSubscription ptable);
|
||||
|
||||
}}//namespace
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/utils/bts_export.h"
|
||||
#include "lib/api/apicore.pb.h"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace bts {
|
||||
namespace qbus {
|
||||
class Quickbus;
|
||||
}
|
||||
namespace api {
|
||||
|
||||
typedef qbus::Quickbus Quickbus;
|
||||
BTS_EXPORT Quickbus* api_create_quickbus(const char* qbconfig, long length);
|
||||
BTS_EXPORT void api_destroy_quickbus(Quickbus*);
|
||||
|
||||
struct StreamUpdate {
|
||||
enum Type {
|
||||
REMOVE,
|
||||
REPLACE,
|
||||
CREATE
|
||||
};
|
||||
Type type;
|
||||
int key;
|
||||
int buffer_len;
|
||||
const char* buffer;
|
||||
};
|
||||
|
||||
// Internal methods
|
||||
}}
|
||||
@@ -0,0 +1,82 @@
|
||||
#include "ApiServerInterop.h"
|
||||
#include "lib/quickbus/quickbus.h"
|
||||
#include "lib/logging/logging.h"
|
||||
|
||||
namespace bts {
|
||||
namespace api {
|
||||
|
||||
// defined in ApiClientInterop.h
|
||||
std::string base_topic(const char* type_name, const char* service_qualifier);
|
||||
bts::qbus::RPCServiceName rpc_topic(const std::string& base_topic);
|
||||
bts::qbus::Topic stream_topic(const std::string& base_topic, const char* method_and_qualifier);
|
||||
|
||||
struct ApiServerCore {
|
||||
ApiServerCore(Quickbus& qbus, const std::string topic, const qbus::OnRPCRequest& handler) :
|
||||
qbus(qbus),
|
||||
topic(topic),
|
||||
rpc(qbus, rpc_topic(topic), handler)
|
||||
{}
|
||||
|
||||
Quickbus& qbus;
|
||||
std::string topic;
|
||||
qbus::RPCServer rpc;
|
||||
};
|
||||
|
||||
BTS_EXPORT ApiServerCore* api_server_create(Quickbus* pbus, const char* type_name, const char* service_qualifier, raw_rpc_request_callback cb, void* extra) {
|
||||
bts_assert(pbus);
|
||||
// Invalid characters in qualifier: +
|
||||
for (auto ch : { '+', '_' }) {
|
||||
bts_assert(strchr(service_qualifier, ch) == nullptr);
|
||||
}
|
||||
auto service_name = base_topic(type_name, service_qualifier);
|
||||
LOG(Api,Info,"create server: {}",service_name);
|
||||
return new ApiServerCore(*pbus, service_name, [=](qbus::RPCRequestPtr const& req, qbus::ReplyHandler const& reply) {
|
||||
// Extend the lifetime of the ReplyHandler by moving it to the heap
|
||||
qbus::ReplyHandler* phandler = new qbus::ReplyHandler(std::move(reply));
|
||||
LOG(Api,Info,"Received rpc request: {}",reinterpret_cast<intptr_t>(phandler));
|
||||
cb((uint8_t*)(req->value().c_str()), req->value().size(), reinterpret_cast<ReplyHandler*>(phandler), extra);
|
||||
});
|
||||
}
|
||||
|
||||
BTS_EXPORT void api_server_call_callback(ReplyHandler** ppvhandler, const uint8_t* buffer, int length) {
|
||||
bts_assert(ppvhandler);
|
||||
bts_assert(*ppvhandler);
|
||||
LOG(Api,Info,"Send rpc reply: {}",reinterpret_cast<intptr_t>(*ppvhandler));
|
||||
qbus::ReplyHandler** pphandler = reinterpret_cast<qbus::ReplyHandler**>(ppvhandler);
|
||||
std::string reply_buffer((const char*)buffer, length);
|
||||
qbus::RPCReplyPtr replyptr = std::make_shared<qbus::RPCReply>(move(reply_buffer));
|
||||
(**pphandler)(replyptr);
|
||||
delete (*pphandler);
|
||||
*pphandler = nullptr;
|
||||
}
|
||||
|
||||
BTS_EXPORT TableHandle api_server_create_table(ApiServerCore* pserver, const char* method_and_qualifier) {
|
||||
bts_assert(pserver);
|
||||
auto topic = stream_topic(pserver->topic, method_and_qualifier);
|
||||
LOG(Api,Info,"Create table: {}",topic.value());
|
||||
return new qbus::TablePublisher(pserver->qbus, topic);
|
||||
}
|
||||
|
||||
BTS_EXPORT void api_server_update_table(TableHandle htable, StreamUpdate* raw_changes, int change_count) {
|
||||
if (change_count > 0) {
|
||||
bts_assert(htable);
|
||||
qbus::TablePublisher* ptable = reinterpret_cast<qbus::TablePublisher*>(htable);
|
||||
std::vector<qbus::Change> changes(change_count);
|
||||
for (int x = 0; x < change_count; ++x) {
|
||||
StreamUpdate& ch = raw_changes[x];
|
||||
std::string buffer(ch.buffer, ch.buffer_len);
|
||||
qbus::RecordPtr record = std::make_shared<qbus::Record>(std::move(buffer));
|
||||
changes[x] = qbus::Change((qbus::Change::Type)ch.type, qbus::RecordKey(ch.key), record);
|
||||
}
|
||||
ptable->publish(std::move(changes));
|
||||
}
|
||||
}
|
||||
|
||||
BTS_EXPORT void api_server_destroy_table(qbus::TablePublisher* ptable) {
|
||||
if (ptable) {
|
||||
ptable->disconnect();
|
||||
delete ptable;
|
||||
}
|
||||
}
|
||||
|
||||
} }//namespace
|
||||
@@ -0,0 +1,19 @@
|
||||
#pragma once
|
||||
#include "ApiInteropCommon.h"
|
||||
|
||||
namespace bts {
|
||||
namespace api {
|
||||
|
||||
struct ApiServerCore;
|
||||
//struct ReplyHandler;
|
||||
typedef void ReplyHandler;
|
||||
typedef void(*raw_rpc_request_callback)(const uint8_t* buffer, size_t length, ReplyHandler* callback, void* extra);
|
||||
BTS_EXPORT ApiServerCore* api_server_create(Quickbus* pbus, const char* type_name, const char* service_qualifier, raw_rpc_request_callback reply, void* extra);
|
||||
|
||||
BTS_EXPORT void api_server_call_callback(ReplyHandler** pphandler, const uint8_t* buffer, int length);
|
||||
|
||||
typedef void* TableHandle;
|
||||
BTS_EXPORT TableHandle api_server_create_table(ApiServerCore* pserver, const char* method_and_qualifier);
|
||||
BTS_EXPORT void api_server_update_table(TableHandle htable, StreamUpdate* raw_changes, int change_count);
|
||||
|
||||
}}//namespace
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/utils/bts_export.h"
|
||||
#include <exception>
|
||||
#include <string>
|
||||
|
||||
namespace bts {
|
||||
namespace api {
|
||||
|
||||
class ApiException : public std::exception
|
||||
{
|
||||
std::string _what;
|
||||
public:
|
||||
ApiException(const std::string& what) : _what(what) {}
|
||||
~ApiException() {}
|
||||
|
||||
const char* what() const throw() { return _what.c_str(); }
|
||||
};
|
||||
|
||||
}}//namespace
|
||||
@@ -0,0 +1,14 @@
|
||||
#ifndef NO_CPP0X
|
||||
#include "ApiServer.h"
|
||||
#include "ServiceContext.h"
|
||||
namespace bts {
|
||||
namespace api {
|
||||
|
||||
ApiServer::ApiServer(const ServiceContext& ctx, const std::string& type, const std::string& qualifier) :
|
||||
_channel(ctx.publish(*this, type, qualifier))
|
||||
{ }
|
||||
|
||||
ApiServer::~ApiServer() { }
|
||||
|
||||
}}//namespace
|
||||
#endif
|
||||
@@ -0,0 +1,65 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/utils/bts_export.h"
|
||||
#include "../core/ApiClientInterop.h"
|
||||
#include "ApiUtils.h"
|
||||
#include "ServerChannel.h"
|
||||
|
||||
#include "lib/api/apicore.pb.h"
|
||||
|
||||
#include <google/protobuf/io/zero_copy_stream.h>
|
||||
#include <functional>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace bts {
|
||||
namespace api {
|
||||
|
||||
class ServiceContext;
|
||||
class BTS_EXPORT ApiServer
|
||||
{
|
||||
public:
|
||||
ApiServer(const ServiceContext&, const std::string& type, const std::string& qualifier);
|
||||
virtual ~ApiServer();
|
||||
|
||||
typedef std::function<void(const uint8_t*, size_t)> OnResponse;
|
||||
virtual void dispatch(const RequestHeader&, google::protobuf::io::ZeroCopyInputStream&, OnResponse) = 0;
|
||||
virtual const char* name() const = 0;
|
||||
|
||||
protected:
|
||||
ServerChannel _channel;
|
||||
|
||||
template <class T>
|
||||
void respond(int request_id, const T& response, OnResponse onreply) {
|
||||
ResponseHeader header;
|
||||
header.set_code(ApiError::SUCCESS);
|
||||
header.set_request_id(request_id);
|
||||
int header_size = header.ByteSize() + 1;
|
||||
int body_size = response.ByteSize();
|
||||
int total_size = header_size + body_size;
|
||||
if (total_size <= 1024) {
|
||||
uint8_t buffer[1024];
|
||||
serialize(header_size, body_size, header, response, buffer);
|
||||
onreply(buffer, total_size);
|
||||
}
|
||||
else {
|
||||
std::vector<uint8_t> buffer(total_size);
|
||||
serialize(header_size, body_size, header, response, &buffer[0]);
|
||||
onreply(&buffer[0], total_size);
|
||||
}
|
||||
}
|
||||
|
||||
template <class T>
|
||||
static void serialize(int header_size, int body_size, const ResponseHeader& header, const T& response, uint8_t* buffer) {
|
||||
buffer[0] = (uint8_t)header_size;
|
||||
header.SerializePartialToArray(&buffer[1], header_size - 1);
|
||||
response.SerializePartialToArray(&buffer[header_size], body_size);
|
||||
}
|
||||
|
||||
static void serialize(int header_size, const ResponseHeader& header, uint8_t* buffer) {
|
||||
buffer[0] = header_size;
|
||||
header.SerializePartialToArray(&buffer[1], header_size - 1);
|
||||
}
|
||||
};
|
||||
|
||||
}}//namespace
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <algorithm>
|
||||
#include <google/protobuf/util/json_util.h>
|
||||
|
||||
namespace bts {
|
||||
namespace api {
|
||||
|
||||
template <class T>
|
||||
const std::string format_qualifier(const char* type_name, const T& t) {
|
||||
google::protobuf::util::JsonPrintOptions options;
|
||||
options.add_whitespace = false;
|
||||
options.always_print_primitive_fields = true;
|
||||
std::string result;
|
||||
auto status = google::protobuf::util::MessageToJsonString(t, &result, options);
|
||||
assert(status.ok());
|
||||
result.erase( std::remove_if(result.begin(), result.end(), [](char c) {
|
||||
return
|
||||
c == '+' ||
|
||||
c == '_';
|
||||
}), result.end());
|
||||
return type_name + result;
|
||||
}
|
||||
|
||||
|
||||
}}//namespace
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
#ifndef NO_CPP0X
|
||||
#include "ClientChannel.h"
|
||||
namespace bts {
|
||||
namespace api {
|
||||
|
||||
ClientChannel::ClientChannel() : _id(1)
|
||||
{
|
||||
}
|
||||
|
||||
ClientChannel::~ClientChannel() { }
|
||||
|
||||
}}//namespace
|
||||
#endif
|
||||
@@ -0,0 +1,117 @@
|
||||
#pragma once
|
||||
|
||||
#include "../core/ApiClientInterop.h"
|
||||
#include "Result.h"
|
||||
#include "ApiException.h"
|
||||
#include "RawUpdate.h"
|
||||
//#include "Update.h"
|
||||
#include <rxcpp/rx.hpp>
|
||||
#include <functional>
|
||||
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
|
||||
|
||||
namespace bts {
|
||||
namespace api {
|
||||
|
||||
|
||||
class ClientChannel
|
||||
{
|
||||
int _id;
|
||||
public:
|
||||
ClientChannel();
|
||||
virtual ~ClientChannel();
|
||||
|
||||
template <typename Request, typename Response>
|
||||
void send(int method_id, const Request& request, std::function<void(Result<Response>)> on_response) {
|
||||
RequestHeader header;
|
||||
header.set_method(method_id);
|
||||
header.set_request_id(++_id);
|
||||
int header_size = header.ByteSize()+1;
|
||||
assert(header_size < 128);
|
||||
|
||||
std::string request_buffer;
|
||||
request_buffer.reserve(header_size + request.ByteSize());
|
||||
request_buffer += (char)(header_size);
|
||||
bool success = header.AppendToString(&request_buffer);
|
||||
success = success && request.AppendToString(&request_buffer);
|
||||
if (!success) throw ApiException("Failed to serialize request.");
|
||||
|
||||
send_core(request_buffer, [on_response](const char* response_buffer, size_t response_size) {
|
||||
assert(response_size > 1);
|
||||
int header_size = response_buffer[0];
|
||||
assert(header_size > 0);
|
||||
google::protobuf::io::ArrayInputStream header_stream(response_buffer+1, header_size-1);
|
||||
ResponseHeader header;
|
||||
if (header.ParseFromZeroCopyStream(&header_stream)) {
|
||||
if (header.code() == ApiError::SUCCESS) {
|
||||
auto response = std::make_shared<Response>();
|
||||
google::protobuf::io::ArrayInputStream data_stream(response_buffer + header_size, response_size - header_size);
|
||||
if (response->ParseFromZeroCopyStream(&data_stream)) {
|
||||
on_response(Result<Response>(move(response)));
|
||||
return;
|
||||
}
|
||||
}
|
||||
else {
|
||||
on_response(Result<Response>((ApiError)header.code()));
|
||||
}
|
||||
}
|
||||
else {
|
||||
on_response(Result<Response>(ApiError::UNEXPECTED_RESPONSE));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
template <typename T>
|
||||
rxcpp::observable<RawUpdate<std::shared_ptr<const T>>> subscribe(const std::string& method_and_qualifier) {
|
||||
return rxcpp::observable<>::create<RawUpdate<std::shared_ptr<const T>>>([=](rxcpp::subscriber<RawUpdate<std::shared_ptr<const T>>> observer) {
|
||||
bool first_update = true;
|
||||
auto cb = [observer, first_update](EventType event_type, const StreamUpdate* changes, int change_count) mutable {
|
||||
if (event_type == EventType::TABLE_UPDATED) {
|
||||
std::vector<std::shared_ptr<const T>> added_items;
|
||||
std::vector<int> added_keys,
|
||||
removed_keys;
|
||||
for (size_t x = 0; x < change_count; ++x) {
|
||||
const StreamUpdate& change = changes[x];
|
||||
if (change.type != StreamUpdate::REMOVE) {
|
||||
added_keys.reserve(change_count);
|
||||
added_items.reserve(change_count);
|
||||
added_keys.push_back(change.key);
|
||||
google::protobuf::io::ArrayInputStream stream(change.buffer, change.buffer_len);
|
||||
auto item = std::make_shared<T>();
|
||||
if (item->ParseFromZeroCopyStream(&stream)) {
|
||||
added_items.push_back(move(item));
|
||||
}
|
||||
}
|
||||
if (change.type != StreamUpdate::CREATE) {
|
||||
removed_keys.reserve(change_count);
|
||||
removed_keys.push_back(change.key);
|
||||
}
|
||||
}
|
||||
observer.on_next(RawUpdate<std::shared_ptr<const T>>(added_items, added_keys, removed_keys));
|
||||
}
|
||||
else if (event_type == EventType::TABLE_CREATED) {
|
||||
if (!first_update) {
|
||||
observer.on_next(RawUpdate<std::shared_ptr<const T>>::Reset());
|
||||
}
|
||||
first_update = false;
|
||||
}
|
||||
};
|
||||
observer.add(
|
||||
subscribe_core(method_and_qualifier, cb));
|
||||
});
|
||||
}
|
||||
|
||||
virtual bool is_sync_call_ok() = 0;
|
||||
|
||||
protected:
|
||||
typedef std::function<void(const char*, size_t)> OnReply;
|
||||
typedef std::function<void()> Unsubscribe;
|
||||
typedef std::function<void(EventType,const StreamUpdate*,int)> OnSubscriptionCB;
|
||||
virtual void send_core(const std::string& request_buffer, OnReply on_response) = 0;
|
||||
virtual Unsubscribe subscribe_core(const std::string& method_and_qualifier, OnSubscriptionCB cb) = 0;
|
||||
|
||||
private:
|
||||
ClientChannel(const ClientChannel& other);// = delete;
|
||||
};
|
||||
|
||||
}}//namespace
|
||||
@@ -0,0 +1,48 @@
|
||||
#include "QuickbusClientChannel.h"
|
||||
#include "QuickbusClientChannel.h"
|
||||
#include "ClientChannel.h"
|
||||
namespace bts {
|
||||
namespace api {
|
||||
|
||||
QuickbusClientChannel::QuickbusClientChannel(Quickbus& bus, const char* type_name, const char* service_qualifier) :
|
||||
_pclient(api_client_create(&bus, type_name, service_qualifier))
|
||||
{
|
||||
}
|
||||
|
||||
QuickbusClientChannel::~QuickbusClientChannel() {
|
||||
if (_pclient != nullptr) {
|
||||
api_client_destroy(_pclient);
|
||||
_pclient = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void QuickbusClientChannel::send_core(const std::string& request_envalope, OnReply on_response) {
|
||||
raw_response_callback trampoline = [](const char* buffer, size_t length, void* extraptr) {
|
||||
OnReply* on_response = static_cast<OnReply*>(extraptr);
|
||||
assert(on_response != nullptr);
|
||||
(*on_response)(buffer, length);
|
||||
delete on_response;
|
||||
};
|
||||
OnReply* heap_on_response = new OnReply(move(on_response));
|
||||
api_client_send(_pclient, request_envalope.c_str(), request_envalope.size(), trampoline, heap_on_response);
|
||||
}
|
||||
|
||||
ClientChannel::Unsubscribe QuickbusClientChannel::subscribe_core(const std::string & method_and_qualifier, OnSubscriptionCB cb) {
|
||||
raw_subscription_callback trampoline = [](EventType event_type, const StreamUpdate* changes, int count, void* extra) {
|
||||
OnSubscriptionCB* heap_cb = static_cast<OnSubscriptionCB*>(extra);
|
||||
assert(heap_cb != nullptr);
|
||||
(*heap_cb)(event_type, changes, count);
|
||||
};
|
||||
OnSubscriptionCB* heap_cb = new OnSubscriptionCB(cb);
|
||||
auto subscription = api_client_subscribe(_pclient, method_and_qualifier.c_str(), trampoline, heap_cb);
|
||||
return [this,subscription,heap_cb]() {
|
||||
api_client_unsubscribe(_pclient, subscription);
|
||||
delete heap_cb;
|
||||
};
|
||||
}
|
||||
|
||||
bool QuickbusClientChannel::is_sync_call_ok() {
|
||||
return !api_client_is_on_qb_thread(_pclient);
|
||||
}
|
||||
|
||||
}}//namespace
|
||||
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/utils/bts_no_copy.h"
|
||||
#include "ClientChannel.h"
|
||||
|
||||
namespace bts {
|
||||
namespace api {
|
||||
|
||||
class QuickbusClientChannel : public ClientChannel
|
||||
{
|
||||
ApiClient* _pclient;
|
||||
|
||||
public:
|
||||
QuickbusClientChannel(Quickbus&, const char* type_name, const char* service_qualifier);
|
||||
~QuickbusClientChannel();
|
||||
|
||||
private:
|
||||
BTS_NO_COPY(QuickbusClientChannel);
|
||||
|
||||
virtual void send_core(const std::string& request_envalope, OnReply on_response) override;
|
||||
virtual Unsubscribe subscribe_core(const std::string& method_and_qualifier, OnSubscriptionCB cb) override;
|
||||
virtual bool is_sync_call_ok() override;
|
||||
|
||||
};
|
||||
|
||||
}}//namespace
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
namespace bts {
|
||||
namespace api {
|
||||
|
||||
template <typename T>
|
||||
struct RawUpdate {
|
||||
RawUpdate(std::vector<T>& added_items, std::vector<int>& added_keys, std::vector<int>& removed_keys) :
|
||||
is_reset(false),
|
||||
added_items(std::move(added_items)),
|
||||
added_keys(std::move(added_keys)),
|
||||
removed_keys(std::move(removed_keys))
|
||||
{}
|
||||
|
||||
static RawUpdate<T> Reset() {
|
||||
return RawUpdate();
|
||||
}
|
||||
|
||||
bool is_reset;
|
||||
std::vector<T> added_items;
|
||||
std::vector<int> added_keys;
|
||||
std::vector<int> removed_keys;
|
||||
|
||||
private:
|
||||
RawUpdate() :
|
||||
is_reset(true),
|
||||
added_items(), added_keys(), removed_keys()
|
||||
{}
|
||||
};
|
||||
|
||||
} }//ns
|
||||
@@ -0,0 +1,75 @@
|
||||
#pragma once
|
||||
|
||||
#include "ApiException.h"
|
||||
|
||||
#include "lib/api/apicore.pb.h"
|
||||
|
||||
#include <memory>
|
||||
#include <assert.h>
|
||||
#include <functional>
|
||||
|
||||
|
||||
namespace bts {
|
||||
namespace api {
|
||||
|
||||
template <class T>
|
||||
class Result
|
||||
{
|
||||
std::shared_ptr<T> _t;
|
||||
ApiError _code;
|
||||
|
||||
static const char* error_string(ApiError code) {
|
||||
switch (code) {
|
||||
case ApiError::SUCCESS: return "Success";
|
||||
case ApiError::NO_SERVER: return "No server found.";
|
||||
case ApiError::SERVER_DISCONNECT: return "Server disconnected.";
|
||||
case ApiError::MISSING_METHOD: return "Method not found.";
|
||||
case ApiError::SERVER_FAULT: return "Server error.";
|
||||
case ApiError::UNEXPECTED_RESPONSE: return "Internal error";
|
||||
default: return "Unknown error";
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
Result(std::shared_ptr<T>& t):
|
||||
_t(t),
|
||||
_code(ApiError::SUCCESS)
|
||||
{ }
|
||||
Result(std::shared_ptr<T>&& t):
|
||||
_t(t),
|
||||
_code(ApiError::SUCCESS)
|
||||
{ }
|
||||
Result(ApiError code) :
|
||||
_t(),
|
||||
_code(code)
|
||||
{
|
||||
assert(_code != ApiError::SUCCESS);
|
||||
}
|
||||
|
||||
#if _MSC_VER <= 1910
|
||||
// needed for std::future
|
||||
Result() :
|
||||
_t(),
|
||||
_code(ApiError::UNEXPECTED_RESPONSE)
|
||||
{}
|
||||
#endif
|
||||
|
||||
std::shared_ptr<T> result() {
|
||||
if (success()) return _t;
|
||||
else throw ApiException(std::string(error_message()));
|
||||
}
|
||||
|
||||
bool success() { return _code == ApiError::SUCCESS; }
|
||||
ApiError code() { return _code; }
|
||||
const char* error_message() { return error_string(_code); }
|
||||
|
||||
~Result() {}
|
||||
|
||||
// Is not a type??
|
||||
// typedef std::function<void(Result<T>)> OnResponse;
|
||||
};
|
||||
|
||||
//template <typename T>
|
||||
//using OnResponse = std::function<void(Result<T>)>;
|
||||
|
||||
}}//namespace
|
||||
@@ -0,0 +1,63 @@
|
||||
#ifndef NO_CPP0X
|
||||
#include "ServerChannel.h"
|
||||
#include "../core/ApiServerInterop.h"
|
||||
#include "ApiServer.h"
|
||||
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
|
||||
namespace bts {
|
||||
namespace api {
|
||||
|
||||
|
||||
struct ServerChannel::ServerChannelImpl {
|
||||
ServerChannelImpl(Quickbus& qbus, const std::string& service_type, const std::string& qualifier, ApiServer& server):
|
||||
_server(server),
|
||||
_core(api_server_create(&qbus, service_type.c_str(), qualifier.c_str(), dispatch_trampoline, this))
|
||||
{
|
||||
}
|
||||
//Need to guaruntee this object is stationary for the api_server_create trampoline
|
||||
ServerChannelImpl(const ServerChannelImpl& ) = delete;
|
||||
ServerChannelImpl(ServerChannelImpl&&) = delete;
|
||||
|
||||
static void dispatch_trampoline(const uint8_t* buffer, size_t request_size, ReplyHandler* callback, void* extra) {
|
||||
assert(extra != nullptr);
|
||||
ServerChannelImpl* pimpl = static_cast<ServerChannelImpl*>(extra);
|
||||
pimpl->dispatch(buffer, request_size, callback);
|
||||
}
|
||||
|
||||
void dispatch(const uint8_t* request_buffer, size_t request_length, ReplyHandler* callback) {
|
||||
assert(request_buffer != nullptr);
|
||||
assert(request_length > 1);
|
||||
size_t header_length = request_buffer[0];
|
||||
assert(request_length >= header_length);
|
||||
RequestHeader header;
|
||||
if (header.ParsePartialFromArray(request_buffer + 1, header_length - 1)) {
|
||||
google::protobuf::io::ArrayInputStream stream(request_buffer + header_length, request_length - header_length);
|
||||
_server.dispatch(header, stream, [=](const uint8_t* buffer, size_t length) {
|
||||
ReplyHandler* handler = callback;
|
||||
api_server_call_callback(&handler, buffer, (int)length);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
ApiServer& _server;
|
||||
ApiServerCore* _core;
|
||||
};
|
||||
|
||||
|
||||
ServerChannel::ServerChannel(Quickbus& qbus, const std::string& service_type, const std::string& qualifier, ApiServer& server)
|
||||
:_me(new ServerChannelImpl(qbus, service_type, qualifier, server))
|
||||
{ }
|
||||
ServerChannel::ServerChannel(ServerChannel&& other) : _me(std::move(other._me)) {}
|
||||
|
||||
ServerChannel::~ServerChannel() { }
|
||||
|
||||
|
||||
TableHandle ServerChannel::create_table(const std::string& method_and_qualifier) const {
|
||||
return api_server_create_table(_me->_core, method_and_qualifier.c_str());
|
||||
}
|
||||
void ServerChannel::publish(TableHandle table, StreamUpdate* changes, int change_count) const {
|
||||
api_server_update_table(table, changes, change_count);
|
||||
}
|
||||
|
||||
|
||||
}}//namespace
|
||||
#endif
|
||||
@@ -0,0 +1,27 @@
|
||||
#pragma once
|
||||
|
||||
#include "../core/ApiClientInterop.h"
|
||||
#include "../core/ApiServerInterop.h"
|
||||
#include "lib/api/apicore.pb.h"
|
||||
|
||||
namespace bts {
|
||||
namespace api {
|
||||
|
||||
class ApiServer;
|
||||
class ServerChannel
|
||||
{
|
||||
public:
|
||||
ServerChannel(Quickbus& qbus, const std::string& service_type, const std::string& qualifier, ApiServer& server);
|
||||
ServerChannel(ServerChannel&& other);// : _me(std::move(other._me)) {}
|
||||
~ServerChannel();
|
||||
|
||||
TableHandle create_table(const std::string& method_and_qualifier) const;
|
||||
void publish(TableHandle table, StreamUpdate* changes, int change_count) const;
|
||||
|
||||
private:
|
||||
struct ServerChannelImpl;
|
||||
std::unique_ptr<ServerChannelImpl> _me;
|
||||
};
|
||||
|
||||
}}//namespace
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
#ifndef NO_CPP0X
|
||||
#include "ServiceContext.h"
|
||||
#include "QuickbusClientChannel.h"
|
||||
#include "ApiServer.h"
|
||||
#include "lib/logging/logging.h"
|
||||
|
||||
namespace bts {
|
||||
namespace api {
|
||||
|
||||
ServiceContext::ServiceContext(Quickbus* maybe_bus) :
|
||||
_qbus(maybe_bus ? *maybe_bus : *api_create_quickbus(nullptr, 0))
|
||||
{
|
||||
}
|
||||
|
||||
ServiceContext::~ServiceContext()
|
||||
{
|
||||
}
|
||||
|
||||
std::unique_ptr<ClientChannel> ServiceContext::create_channel(const char * type_name, const char * service_qualifier) {
|
||||
LOG(Api,Info,"Locate Service: {}{}",type_name ,service_qualifier);
|
||||
return std::unique_ptr<ClientChannel>(new QuickbusClientChannel(_qbus, type_name, service_qualifier));
|
||||
}
|
||||
|
||||
ServerChannel ServiceContext::publish(ApiServer& service, const std::string& service_type, const std::string& qualifier) const {
|
||||
return ServerChannel(_qbus, service_type, qualifier, service);
|
||||
}
|
||||
|
||||
}}//namespace
|
||||
#endif
|
||||
@@ -0,0 +1,37 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/utils/bts_export.h"
|
||||
|
||||
// client
|
||||
#include "../core/ApiClientInterop.h"
|
||||
#include "../core/ApiServerInterop.h"
|
||||
#include "ClientChannel.h"
|
||||
// server
|
||||
#include "ServerChannel.h"
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
|
||||
namespace bts {
|
||||
namespace api {
|
||||
|
||||
class BTS_EXPORT ServiceContext
|
||||
{
|
||||
Quickbus& _qbus;
|
||||
|
||||
public:
|
||||
ServiceContext(Quickbus* maybe_bus=nullptr);
|
||||
~ServiceContext();
|
||||
|
||||
template <class T>
|
||||
T locate(const char* qualifier="") {
|
||||
return T(create_channel(T::name(), qualifier));
|
||||
}
|
||||
|
||||
private:
|
||||
friend class ApiServer;
|
||||
std::unique_ptr<ClientChannel> create_channel(const char*, const char*);
|
||||
ServerChannel publish(ApiServer& service, const std::string& service_type, const std::string& qualifier) const;
|
||||
};
|
||||
|
||||
}}//namespace
|
||||
@@ -0,0 +1,79 @@
|
||||
#pragma once
|
||||
|
||||
#include "RawUpdate.h"
|
||||
#include <rxcpp/rx.hpp>
|
||||
#include <functional>
|
||||
#include <vector>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace bts {
|
||||
namespace api {
|
||||
|
||||
|
||||
template <typename T, typename TKey, typename ServiceType>
|
||||
struct Update {
|
||||
Update(std::vector<T>& all, std::vector<T>& added, std::vector<T>& removed) :
|
||||
_all_items(std::move(all)),
|
||||
_added_items(std::move(added)),
|
||||
_removed_items(std::move(removed))
|
||||
{}
|
||||
|
||||
Update(const Update& other) = delete;
|
||||
Update(Update&& other) :
|
||||
_all_items(std::move(other._all_items)),
|
||||
_added_items(std::move(other._added_items)),
|
||||
_removed_items(std::move(other._removed_items))
|
||||
{}
|
||||
|
||||
TKey key(const T& t) const { return ServiceType::key(t); }
|
||||
const std::vector<T>& all() const { return _all_items; }
|
||||
const std::vector<T>& added() const { return _added_items; }
|
||||
const std::vector<T>& removed() const { return _removed_items; }
|
||||
|
||||
private:
|
||||
std::vector<T> _all_items;
|
||||
std::vector<T> _added_items;
|
||||
std::vector<T> _removed_items;
|
||||
};
|
||||
|
||||
template <typename T, typename TKey, typename ServiceType>
|
||||
std::function<rxcpp::observable<Update<T,TKey,ServiceType>>(const rxcpp::observable<RawUpdate<T>>&)> reconstitute() {
|
||||
return [](const rxcpp::observable<RawUpdate<T>>& input) {
|
||||
auto state = std::make_shared<std::unordered_map<int, T>>();
|
||||
return input.map([state](RawUpdate<T>& raw) {
|
||||
if (raw.is_reset) {
|
||||
std::vector<T> removed;
|
||||
removed.reserve(state->size());
|
||||
for (auto& t : *state) {
|
||||
removed.push_back(std::move(t.second));
|
||||
}
|
||||
state->clear();
|
||||
std::vector<T> all, added;
|
||||
return Update<T, TKey, ServiceType>(all, added, removed);
|
||||
}
|
||||
else {
|
||||
std::vector<T> removed;
|
||||
removed.reserve(raw.removed_keys.size());
|
||||
for (int key : raw.removed_keys) {
|
||||
auto iter = state->find(key);
|
||||
if (iter != state->end()) {
|
||||
removed.push_back(iter->second);
|
||||
state->erase(iter);
|
||||
}
|
||||
}
|
||||
for (size_t x = 0; x < raw.added_keys.size(); ++x) {
|
||||
(*state)[raw.added_keys[x]] = raw.added_items[x];
|
||||
}
|
||||
std::vector<T> all;
|
||||
all.reserve(state->size());
|
||||
for (const auto& item : *state) {
|
||||
all.push_back(item.second);
|
||||
}
|
||||
return Update<T, TKey, ServiceType>(all, raw.added_items, removed);
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
}}//namespace
|
||||
@@ -0,0 +1,2 @@
|
||||
#pragma once
|
||||
#include "public/ServiceContext.h"
|
||||
@@ -0,0 +1,74 @@
|
||||
# Generated by the protocol buffer compiler. DO NOT EDIT!
|
||||
# source: apioptions.proto
|
||||
|
||||
import sys
|
||||
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
|
||||
from google.protobuf import descriptor as _descriptor
|
||||
from google.protobuf import message as _message
|
||||
from google.protobuf import reflection as _reflection
|
||||
from google.protobuf import symbol_database as _symbol_database
|
||||
from google.protobuf import descriptor_pb2
|
||||
# @@protoc_insertion_point(imports)
|
||||
|
||||
_sym_db = _symbol_database.Default()
|
||||
|
||||
|
||||
from google.protobuf import descriptor_pb2 as google_dot_protobuf_dot_descriptor__pb2
|
||||
|
||||
|
||||
DESCRIPTOR = _descriptor.FileDescriptor(
|
||||
name='apioptions.proto',
|
||||
package='bts.api',
|
||||
syntax='proto3',
|
||||
serialized_pb=_b('\n\x10\x61pioptions.proto\x12\x07\x62ts.api\x1a google/protobuf/descriptor.proto:=\n\x13message_description\x12\x1f.google.protobuf.MessageOptions\x18\xb4\x42 \x01(\t:=\n\x13service_description\x12\x1f.google.protobuf.ServiceOptions\x18\xb5\x42 \x01(\t:+\n\x03key\x12\x1d.google.protobuf.FieldOptions\x18\xb6\x42 \x01(\x08:9\n\x11\x66ield_description\x12\x1d.google.protobuf.FieldOptions\x18\xb7\x42 \x01(\tB\n\xaa\x02\x07\x62ts.apib\x06proto3')
|
||||
,
|
||||
dependencies=[google_dot_protobuf_dot_descriptor__pb2.DESCRIPTOR,])
|
||||
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
|
||||
|
||||
|
||||
MESSAGE_DESCRIPTION_FIELD_NUMBER = 8500
|
||||
message_description = _descriptor.FieldDescriptor(
|
||||
name='message_description', full_name='bts.api.message_description', index=0,
|
||||
number=8500, type=9, cpp_type=9, label=1,
|
||||
has_default_value=False, default_value=_b("").decode('utf-8'),
|
||||
message_type=None, enum_type=None, containing_type=None,
|
||||
is_extension=True, extension_scope=None,
|
||||
options=None)
|
||||
SERVICE_DESCRIPTION_FIELD_NUMBER = 8501
|
||||
service_description = _descriptor.FieldDescriptor(
|
||||
name='service_description', full_name='bts.api.service_description', index=1,
|
||||
number=8501, type=9, cpp_type=9, label=1,
|
||||
has_default_value=False, default_value=_b("").decode('utf-8'),
|
||||
message_type=None, enum_type=None, containing_type=None,
|
||||
is_extension=True, extension_scope=None,
|
||||
options=None)
|
||||
KEY_FIELD_NUMBER = 8502
|
||||
key = _descriptor.FieldDescriptor(
|
||||
name='key', full_name='bts.api.key', index=2,
|
||||
number=8502, type=8, cpp_type=7, label=1,
|
||||
has_default_value=False, default_value=False,
|
||||
message_type=None, enum_type=None, containing_type=None,
|
||||
is_extension=True, extension_scope=None,
|
||||
options=None)
|
||||
FIELD_DESCRIPTION_FIELD_NUMBER = 8503
|
||||
field_description = _descriptor.FieldDescriptor(
|
||||
name='field_description', full_name='bts.api.field_description', index=3,
|
||||
number=8503, type=9, cpp_type=9, label=1,
|
||||
has_default_value=False, default_value=_b("").decode('utf-8'),
|
||||
message_type=None, enum_type=None, containing_type=None,
|
||||
is_extension=True, extension_scope=None,
|
||||
options=None)
|
||||
|
||||
DESCRIPTOR.extensions_by_name['message_description'] = message_description
|
||||
DESCRIPTOR.extensions_by_name['service_description'] = service_description
|
||||
DESCRIPTOR.extensions_by_name['key'] = key
|
||||
DESCRIPTOR.extensions_by_name['field_description'] = field_description
|
||||
|
||||
google_dot_protobuf_dot_descriptor__pb2.MessageOptions.RegisterExtension(message_description)
|
||||
google_dot_protobuf_dot_descriptor__pb2.ServiceOptions.RegisterExtension(service_description)
|
||||
google_dot_protobuf_dot_descriptor__pb2.FieldOptions.RegisterExtension(key)
|
||||
google_dot_protobuf_dot_descriptor__pb2.FieldOptions.RegisterExtension(field_description)
|
||||
|
||||
DESCRIPTOR.has_options = True
|
||||
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\252\002\007bts.api'))
|
||||
# @@protoc_insertion_point(module_scope)
|
||||
Binary file not shown.
Executable
+3
@@ -0,0 +1,3 @@
|
||||
@setlocal
|
||||
@cd %~dp0
|
||||
@python -u plugin.py
|
||||
Executable
+226
@@ -0,0 +1,226 @@
|
||||
#!/usr/bin/python
|
||||
import os, sys
|
||||
|
||||
|
||||
# cd to scripts working directory
|
||||
abspath = os.path.abspath(__file__)
|
||||
dname = os.path.dirname(abspath)
|
||||
os.chdir(dname)
|
||||
|
||||
from google.protobuf.compiler import plugin_pb2 as plugin
|
||||
from google.protobuf.descriptor_pb2 import FieldDescriptorProto
|
||||
from pybars import Compiler, strlist
|
||||
compiler = Compiler()
|
||||
|
||||
## Logging
|
||||
enable_logging = False
|
||||
def log(msg):
|
||||
if enable_logging:
|
||||
from urllib import urlencode
|
||||
import urllib2
|
||||
url = "http://localhost:8080/"
|
||||
data = urlencode(dict(log=msg))
|
||||
req = urllib2.Request(url, data)
|
||||
urllib2.urlopen(req).read()
|
||||
|
||||
# required to resolve custom options
|
||||
# generate with: protoc apioptions.proto --python_out=temp -Id:\blue\external\protobuf\protobuf-3.0.2\src -I.
|
||||
## Note:
|
||||
## If this import fails with something like "'module' object has no attribute 'Default'" you need to
|
||||
## use `aptitude remove python-protobuf` and `pip install protobuf`
|
||||
import apioptions_pb2
|
||||
|
||||
def loadTemplate(lang, name):
|
||||
path = os.path.join("templates", lang, name)
|
||||
text = open(path).read()
|
||||
utext = unicode(text, "utf-8")
|
||||
return compiler.compile(utext)
|
||||
|
||||
def fix_type_name(proto):
|
||||
for service in proto.service:
|
||||
for method in service.method:
|
||||
method.input_type = method.input_type.lstrip('.')
|
||||
method.output_type = method.output_type.lstrip('.')
|
||||
|
||||
def parseParams(params):
|
||||
# log(params)
|
||||
result = dict()
|
||||
if params:
|
||||
parts = params.split(',')
|
||||
for p in parts:
|
||||
a,b = p.split("=")
|
||||
result[a] = b
|
||||
if 'make_filename' in params and not 'package_name' in params:
|
||||
result['package_name'] = result['make_filename'].lstrip('/').split('/')[1]
|
||||
return result
|
||||
|
||||
def generate_insertions(params, request, response):
|
||||
# Include exports definition
|
||||
if os.name == 'posix':
|
||||
for file in request.file_to_generate:
|
||||
f1, f2 = response.file.add(), response.file.add()
|
||||
f1.name = f2.name = os.path.splitext(file)[0] + ".pb.h"
|
||||
f1.insertion_point = "includes"
|
||||
f1.content = """#ifdef __GNUC__
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Weffc++"
|
||||
#endif"""
|
||||
f2.insertion_point = "global_scope"
|
||||
f2.content = "#pragma GCC diagnostic pop"
|
||||
if 'package_name' in params and 'project_name' in params:
|
||||
for file in request.file_to_generate:
|
||||
f = response.file.add()
|
||||
f.name = os.path.splitext(file)[0] + ".pb.h"
|
||||
# log("Inserting into " + f.name)
|
||||
f.insertion_point = "includes"
|
||||
f.content = "#include <{0}/{1}/{1}_exports.h>".format(params["package_name"], params["project_name"])
|
||||
|
||||
def keyfield(proto_file, item):
|
||||
name = item.split('.')[-1:][0]
|
||||
msg = next((x for x in proto_file.message_type if x.name == name), None)
|
||||
key = apioptions_pb2.key
|
||||
if msg != None:
|
||||
field = next ((x for x in msg.field if x.options.HasExtension(key) and x.options.Extensions[key] == True), None)
|
||||
if field != None:
|
||||
return field
|
||||
return None
|
||||
|
||||
def keyname(proto_file, item):
|
||||
result = keyfield(proto_file, item)
|
||||
if result == None: return "id"
|
||||
return result.name
|
||||
|
||||
def camel_case(item):
|
||||
if item.isupper() and not '_' in item: return item
|
||||
return item.title().replace('_', '')
|
||||
|
||||
def stupid_python_dict(o):
|
||||
d = dict()
|
||||
for attr in dir(o):
|
||||
d[attr] = getattr(o, attr)
|
||||
return d
|
||||
|
||||
def field_type(field, parent):
|
||||
try:
|
||||
if field['type'] == FieldDescriptorProto.TYPE_INT32: return "int"
|
||||
elif field['type'] == FieldDescriptorProto.TYPE_BOOL: return "bool"
|
||||
elif field['type'] == FieldDescriptorProto.TYPE_INT64: return "long"
|
||||
elif field['type'] == FieldDescriptorProto.TYPE_SINT32: return "int"
|
||||
elif field['type'] == FieldDescriptorProto.TYPE_SINT64: return "long"
|
||||
elif field['type'] == FieldDescriptorProto.TYPE_UINT64: return "UInt64"
|
||||
elif field['type'] == FieldDescriptorProto.TYPE_UINT32: return "uint"
|
||||
elif field['type'] == FieldDescriptorProto.TYPE_DOUBLE: return "double"
|
||||
elif field['type'] == FieldDescriptorProto.TYPE_FLOAT: return "float"
|
||||
elif field['type'] == FieldDescriptorProto.TYPE_STRING: return "string"
|
||||
elif field['type'] == FieldDescriptorProto.TYPE_ENUM:
|
||||
nested_enums = [x.name for x in parent['enum_type']]
|
||||
full_name = field['type_name'].lstrip('.')
|
||||
short_name = full_name.split('.')[-1:][0]
|
||||
if short_name in nested_enums:
|
||||
full_name = "{0}.Types.{1}".format(parent['name'], short_name)
|
||||
return full_name
|
||||
elif field['type'] == FieldDescriptorProto.TYPE_MESSAGE:
|
||||
map_types = dict([(x.name, x) for x in parent['nested_type'] if x.options.map_entry == True])
|
||||
full_name = field['type_name'].lstrip('.')
|
||||
short_name = full_name.split('.')[-1:][0]
|
||||
immutable_postfix = "Immutable"
|
||||
if full_name.startswith('google'):
|
||||
immutable_postfix = ""
|
||||
full_name = short_name
|
||||
if short_name in map_types:
|
||||
t = map_types[short_name]
|
||||
key_field = [f for f in t.field if f.name == 'key'][0]
|
||||
value_field = [f for f in t.field if f.name == 'value'][0]
|
||||
key_type = field_type(stupid_python_dict(key_field), parent)
|
||||
value_type = field_type(stupid_python_dict(value_field), parent)
|
||||
return "IReadOnlyDictionary<{0},{1}>".format(key_type, value_type)
|
||||
return full_name + immutable_postfix
|
||||
except Exception as e:
|
||||
log(e)
|
||||
log(field)
|
||||
return "???"
|
||||
|
||||
def immutable_field_wrapper(field, parent):
|
||||
type_name = field_type(field, parent)
|
||||
is_repeat = field['label'] == FieldDescriptorProto.LABEL_REPEATED
|
||||
is_dict = 'IReadOnlyDictionary' in type_name
|
||||
field_name = camel_case(field['name'])
|
||||
if is_dict or '???' in type_name: return "// todo dic " + field_name
|
||||
if is_repeat:
|
||||
return "public IEnumerable<{0}> {1} => _impl.{1}.Cast<{0}>();".format(type_name, field_name)
|
||||
return "public {0} {1} => _impl.{1};".format(type_name, field_name)
|
||||
|
||||
def key_type(proto_file, item, lang):
|
||||
# trying to make these the same between c++/c# so we don't have to have 2 methods
|
||||
field = keyfield(proto_file, item)
|
||||
if field == None: return "int"
|
||||
types = FieldDescriptorProto
|
||||
if field.type == types.TYPE_INT32: return "int"
|
||||
elif field.type == types.TYPE_INT64: return "long"
|
||||
elif field.type == types.TYPE_SINT32: return "int"
|
||||
elif field.type == types.TYPE_SINT64: return "long"
|
||||
elif field.type == types.TYPE_UINT32 and lang == 'c++': return "unsigned"
|
||||
elif field.type == types.TYPE_UINT32 and lang == 'c#': return "uint"
|
||||
elif field.type == types.TYPE_DOUBLE: return "double"
|
||||
elif field.type == types.TYPE_FLOAT: return "float"
|
||||
elif field.type == types.TYPE_STRING and lang == 'cpp': return "std::string"
|
||||
elif field.type == types.TYPE_STRING and lang == 'c#': return "string"
|
||||
return "int"
|
||||
|
||||
def has_complex_key(proto_file, this, options, item, lang):
|
||||
kt = key_type(proto_file, item, lang)
|
||||
if kt == 'int' or kt == 'uint' or kt == 'unsigned':
|
||||
return options['inverse'](this)
|
||||
else:
|
||||
return options['fn'](this)
|
||||
|
||||
def generate_code(request, response):
|
||||
params = parseParams(request.parameter)
|
||||
if not "lang" in params:
|
||||
response.error = "You must provide a language for the service generator plugin"
|
||||
return
|
||||
lang = params["lang"]
|
||||
if lang == "cpp": generate_insertions(params, request, response)
|
||||
if not 'no_services' in params:
|
||||
current_proto_file = None
|
||||
templates = [(f, loadTemplate(lang, f)) for f in os.listdir("templates/" + lang)]
|
||||
helpers = { 'upper': lambda this,item: item.upper(),
|
||||
'lower': lambda this,item: item.lower(),
|
||||
'cap': lambda this,item: item[0].upper() + item[1:],
|
||||
'filename': lambda this,item: os.path.splitext(item)[0],
|
||||
'ns-open': lambda this,item: "\n".join(["namespace {0} {{".format(x) for x in item.split('.')]),
|
||||
'ns-close': lambda this,item: "}" * len(item.split('.')),
|
||||
'type': lambda this,item: item.split('.')[-1:][0],
|
||||
#'include_exports': lambda this: strlist("#include <{0}/{1}/{1}_exports.h>".format(params["package_name"], params["project_name"])),
|
||||
#'api': lambda this: (params["project_name"].upper()+ "_API"),
|
||||
'camel': lambda _,f: camel_case(f),
|
||||
'immutable_field_wrapper': immutable_field_wrapper
|
||||
# 'keyfield': * defined below *
|
||||
}
|
||||
for proto_file in request.proto_file:
|
||||
if proto_file.name in request.file_to_generate:
|
||||
fix_type_name(proto_file)
|
||||
helpers['keyfield'] = lambda _,item: keyname(proto_file, item)
|
||||
helpers['keyfield_camelcase'] = lambda _,item: camel_case(keyname(proto_file,item))
|
||||
helpers['key_type'] = lambda _,item: key_type(proto_file, item, lang)
|
||||
helpers['has_complex_key'] = lambda this,options,item: has_complex_key(proto_file, this, options, item, lang)
|
||||
# Path on response.file name is interpreted differently by the c# and c++ code gen
|
||||
filename = ('strip_out_path' in params) and os.path.split(proto_file.name)[1] or proto_file.name
|
||||
source_name = os.path.splitext(filename)[0]
|
||||
for name,template in templates:
|
||||
f = response.file.add()
|
||||
f.name = source_name + "." + name
|
||||
#log("creating: " + f.name)
|
||||
f.content = template(proto_file, helpers)
|
||||
|
||||
#### MAIN #########
|
||||
if __name__ == "__main__":
|
||||
data = sys.stdin.read()
|
||||
request = plugin.CodeGeneratorRequest()
|
||||
#open("data", 'wb').write(data)
|
||||
request.ParseFromString(data)
|
||||
response = plugin.CodeGeneratorResponse()
|
||||
generate_code(request, response)
|
||||
output = response.SerializeToString()
|
||||
sys.stdout.write(output)
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
#region Generated code
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using bts.api.core;
|
||||
|
||||
namespace {{package}} {
|
||||
{{#each service}}
|
||||
public sealed class {{name}} : IApiClient, IDisposable {
|
||||
private readonly ClientChannel _channel;
|
||||
private {{name}}(ClientChannel channel) {
|
||||
_channel = channel;
|
||||
}
|
||||
|
||||
public void Dispose() {
|
||||
_channel.Dispose();
|
||||
}
|
||||
|
||||
{{#each method}}
|
||||
{{#if server_streaming}}
|
||||
public IObservable<Update<{{output_type}},{{key_type output_type}}>> subscribe_{{name}}({{input_type}} qualifier=null) {
|
||||
return _channel.subscribe<{{output_type}}>(ApiServer.format_qualifier("{{name}}",qualifier), {{output_type}}.Parser).reconstitute(key);
|
||||
}
|
||||
private static {{key_type output_type}} key({{output_type}} row) {
|
||||
return row.{{keyfield_camelcase output_type}};
|
||||
}
|
||||
{{else}}
|
||||
public Task<Result<{{output_type}}>> {{name}}_async({{input_type}} request) {
|
||||
return _channel.send<{{input_type}},{{output_type}}>({{@index}}, request);
|
||||
}
|
||||
public {{output_type}} {{name}}({{input_type}} request) {
|
||||
if (_channel.is_sync_call_ok()) {
|
||||
return {{name}}_async(request).Result.result;
|
||||
}
|
||||
else {
|
||||
throw new bts.api.core.ApiException("API blocking call cannot be made on this thread. Please use {{name}}_async instead.");
|
||||
}
|
||||
}
|
||||
{{/if}}
|
||||
{{/each}}
|
||||
}
|
||||
|
||||
{{/each}}
|
||||
}
|
||||
#endregion
|
||||
@@ -0,0 +1,36 @@
|
||||
#region Generated code
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Google.Protobuf;
|
||||
using Google.Protobuf.Reflection;
|
||||
using Google.Protobuf.WellKnownTypes;
|
||||
|
||||
namespace {{package}} {
|
||||
{{#each message_type}}
|
||||
public partial struct {{name}}Immutable {
|
||||
readonly {{name}} _impl;
|
||||
|
||||
public static MessageDescriptor Descriptor => {{name}}.Descriptor;
|
||||
public int CalculateSize() => _impl.CalculateSize();
|
||||
// Cannot implement IMessage because of this method
|
||||
//public void MergeFrom(CodedInputStream input) => _impl.MergeFrom(input);
|
||||
public void WriteTo(CodedOutputStream output) => _impl.WriteTo(output);
|
||||
|
||||
public {{name}}Immutable({{name}} src, bool clone=true) {
|
||||
_impl = clone ? src.Clone() : src;
|
||||
}
|
||||
|
||||
// Implicit conversion operator
|
||||
public static implicit operator {{name}}Immutable({{name}} other) {
|
||||
return new {{name}}Immutable(other, false);
|
||||
}
|
||||
|
||||
{{#each field}}
|
||||
{{{immutable_field_wrapper ../}}}
|
||||
{{/each}}
|
||||
|
||||
}
|
||||
{{/each}}
|
||||
}
|
||||
#endregion
|
||||
@@ -0,0 +1,172 @@
|
||||
#region Generated code
|
||||
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using System.Collections.Generic;
|
||||
using bts.api.core;
|
||||
using System.Linq;
|
||||
using Google.Protobuf;
|
||||
using System.Runtime.InteropServices;
|
||||
using bts.api;
|
||||
|
||||
namespace {{package}}
|
||||
{
|
||||
{{#each service}}
|
||||
|
||||
internal abstract class {{name}}Base : ApiServer, IDisposable {
|
||||
readonly ServerChannel _channel;
|
||||
public {{name}}Base(ServiceContext context, string qualifier="") {
|
||||
_channel = context.publish(this, "{{name}}", qualifier);
|
||||
}
|
||||
|
||||
public virtual void Dispose() {
|
||||
_channel.Dispose();
|
||||
}
|
||||
|
||||
{{#each method}}
|
||||
{{#if server_streaming}}
|
||||
protected struct {{cap name}}Publisher {
|
||||
readonly IntPtr _table;
|
||||
{{#has_complex_key output_type}}
|
||||
int _next_key;
|
||||
Dictionary<{{key_type output_type}}, int> _keys;
|
||||
int hash_key({{key_type output_type}} key) {
|
||||
lock(_keys) {
|
||||
int intkey;
|
||||
if (_keys.TryGetValue(key, out intkey)) {
|
||||
return intkey;
|
||||
}
|
||||
intkey = ++_next_key;
|
||||
_keys[key] = intkey;
|
||||
return intkey;
|
||||
}
|
||||
}
|
||||
{{/has_complex_key}}
|
||||
|
||||
public {{cap name}}Publisher(IntPtr table) {
|
||||
_table = table;
|
||||
{{#has_complex_key output_type}}
|
||||
_next_key = 0;
|
||||
_keys = new Dictionary<{{key_type output_type}}, int>();
|
||||
{{/has_complex_key}}
|
||||
}
|
||||
|
||||
ApiNativeMethods.StreamUpdate pack({{output_type}} item, bool is_change, List<GCHandle> pinned_buffers) {
|
||||
var data = item.ToByteArray();
|
||||
var handle = GCHandle.Alloc(data, GCHandleType.Pinned);
|
||||
pinned_buffers.Add(handle);
|
||||
return new ApiNativeMethods.StreamUpdate() {
|
||||
type = is_change ? ApiNativeMethods.ChangeType.REPLACE : ApiNativeMethods.ChangeType.CREATE,
|
||||
{{#has_complex_key output_type}}
|
||||
key = hash_key({{name}}_key(item)),
|
||||
{{else}}
|
||||
key = (int){{name}}_key(item),
|
||||
{{/has_complex_key}}
|
||||
buffer_len = data.Length,
|
||||
buffer = handle.AddrOfPinnedObject()
|
||||
};
|
||||
}
|
||||
public void publish(
|
||||
List<{{output_type}}> added=null,
|
||||
HashSet<{{key_type output_type}}> removed=null,
|
||||
List<{{output_type}}> changed=null) {
|
||||
int add_count = added == null ? 0 : added.Count;
|
||||
int change_count = changed == null ? 0 : changed.Count;
|
||||
int remove_count = removed == null ? 0 : removed.Count;
|
||||
var changes = new ApiNativeMethods.StreamUpdate[add_count + change_count + remove_count];
|
||||
int change_index = 0;
|
||||
var pinned_buffers = new List<GCHandle>(add_count + change_count);
|
||||
|
||||
try {
|
||||
// Added
|
||||
if (added != null) {
|
||||
foreach (var a in added) {
|
||||
var key = {{name}}_key(a);
|
||||
var is_change = removed == null ? false : removed.Contains(key);
|
||||
if (is_change) { removed.Remove(key); }
|
||||
changes[change_index++] = pack(a, is_change, pinned_buffers);
|
||||
}
|
||||
}
|
||||
// Changed
|
||||
if (changed != null) {
|
||||
foreach(var ch in changed) {
|
||||
changes[change_index++] = pack(ch, true, pinned_buffers);
|
||||
}
|
||||
}
|
||||
// Removed
|
||||
if (removed != null) {
|
||||
foreach(var r in removed) {
|
||||
changes[change_index++] = new ApiNativeMethods.StreamUpdate() {
|
||||
type = ApiNativeMethods.ChangeType.REMOVE,
|
||||
{{#has_complex_key output_type}}
|
||||
key = hash_key(r),
|
||||
{{else}}
|
||||
key = (int)r,
|
||||
{{/has_complex_key}}
|
||||
buffer_len = 0
|
||||
};
|
||||
}
|
||||
}
|
||||
ApiNativeMethods.api_server_update_table(_table, changes, change_index);
|
||||
}
|
||||
finally {
|
||||
foreach (var handle in pinned_buffers) {
|
||||
handle.Free();
|
||||
}
|
||||
}
|
||||
}
|
||||
public void append({{output_type}} single) {
|
||||
publish(added: new List<{{output_type}}> { single });
|
||||
}
|
||||
}
|
||||
|
||||
protected {{cap name}}Publisher make_{{name}}_publisher({{input_type}} qualifier=null) {
|
||||
IntPtr table = _channel.create_table(format_qualifier("{{name}}", qualifier));
|
||||
return new {{cap name}}Publisher(table);
|
||||
}
|
||||
protected static {{key_type output_type}} {{name}}_key({{output_type}} row) {
|
||||
return row.{{keyfield_camelcase output_type}};
|
||||
}
|
||||
{{else}}
|
||||
public abstract Task<{{output_type}}> {{name}}({{input_type}} request);
|
||||
{{/if}}
|
||||
{{/each}}
|
||||
|
||||
enum ServiceMethods {
|
||||
SYS_PING = -1,
|
||||
{{#each method}}
|
||||
{{upper name}} = {{@index}},
|
||||
{{/each}}
|
||||
}
|
||||
|
||||
public override void dispatch(RequestHeader header, System.IO.Stream request_stream, Action<byte[]> on_response) {
|
||||
switch((ServiceMethods)header.Method) {
|
||||
case ServiceMethods.SYS_PING: {
|
||||
var msg = PingPong.Parser.ParseFrom(request_stream);
|
||||
respond(header.RequestId, Task.FromResult(msg), on_response);
|
||||
break;
|
||||
}
|
||||
{{#each method}}
|
||||
{{#unless server_streaming}}
|
||||
case ServiceMethods.{{upper name}}: {
|
||||
var msg = {{input_type}}.Parser.ParseFrom(request_stream);
|
||||
var result = {{name}}(msg);
|
||||
var id = header.RequestId;
|
||||
result.ContinueWith(t => respond(id, t, on_response));
|
||||
break;
|
||||
}
|
||||
{{/unless}}
|
||||
{{/each}}
|
||||
default:
|
||||
var buffer = new ResponseHeader(){
|
||||
RequestId = header.RequestId,
|
||||
Code = ApiError.MissingMethod
|
||||
}.serialize();
|
||||
on_response(buffer); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
{{/each}}
|
||||
}
|
||||
#endregion
|
||||
@@ -0,0 +1,67 @@
|
||||
{{#if service}}
|
||||
#include "{{filename name}}.client.pb.h"
|
||||
#include "lib/api/public/ApiUtils.h"
|
||||
#include <future>
|
||||
|
||||
using namespace rxcpp;
|
||||
using namespace rxcpp::sources;
|
||||
using namespace rxcpp::operators;
|
||||
|
||||
{{ns-open package}}
|
||||
{{#each service}}
|
||||
|
||||
// Constructor
|
||||
{{name}}::{{name}}(std::unique_ptr<bts::api::ClientChannel> pchannel) : _pchannel(move(pchannel)) {}
|
||||
{{name}}::{{name}}({{name}}&& other) : _pchannel(move(other._pchannel)) { }
|
||||
|
||||
{{#each method}}
|
||||
{{#if server_streaming}}
|
||||
rxcpp::observable<{{cap name}}Update> {{../name}}::subscribe_{{name}}(const {{type input_type}}& qualifier) {
|
||||
return
|
||||
_pchannel->subscribe<{{type output_type}}>(format_qualifier("{{name}}", qualifier))
|
||||
| (bts::api::reconstitute<std::shared_ptr<const {{type output_type}}>,const {{key_type output_type}}, {{../name}}>());
|
||||
}
|
||||
rxcpp::observable<{{cap name}}Update> {{../name}}::subscribe_{{name}}() {
|
||||
return
|
||||
_pchannel->subscribe<{{type output_type}}>("{{name}}")
|
||||
| (bts::api::reconstitute<std::shared_ptr<const {{type output_type}}>,const {{key_type output_type}}, {{../name}}>());
|
||||
}
|
||||
|
||||
{{#has_complex_key output_type}}
|
||||
const {{key_type output_type}}& {{../name}}::{{name}}_key(const {{type output_type}}& row) {
|
||||
return row.{{keyfield output_type}}();
|
||||
}
|
||||
{{else}}
|
||||
{{key_type output_type}} {{../name}}::{{name}}_key(const {{type output_type}}& row) {
|
||||
return row.{{keyfield output_type}}();
|
||||
}
|
||||
{{/has_complex_key}}
|
||||
|
||||
{{else}}
|
||||
|
||||
void {{../name}}::{{name}}(const {{type input_type}}& input, std::function<void(Result<{{type output_type}}>)> callback, uint32_t timeout_ms) {
|
||||
_pchannel->send({{@index}}, input, callback);
|
||||
}
|
||||
|
||||
Result<{{type output_type}}> {{../name}}::{{name}}(const {{type input_type}}& input, uint32_t timeout_ms) {
|
||||
if (_pchannel->is_sync_call_ok()) {
|
||||
std::promise<Result<{{type output_type}}>> p;
|
||||
auto future = p.get_future();
|
||||
{{name}}(input, [&](Result<{{type output_type}}> res) {
|
||||
p.set_value(res);
|
||||
}, timeout_ms);
|
||||
future.wait();
|
||||
return future.get();
|
||||
}
|
||||
else {
|
||||
throw bts::api::ApiException("API blocking call cannot be made on this thread. Please use {{name}}_async instead.");
|
||||
}
|
||||
}
|
||||
|
||||
{{/if}}
|
||||
|
||||
{{/each}}
|
||||
|
||||
{{/each}}
|
||||
{{ns-close package}}
|
||||
{{/if}}
|
||||
@@ -0,0 +1,58 @@
|
||||
#pragma once
|
||||
{{include_exports}}
|
||||
#include "{{filename name}}.pb.h"
|
||||
#include "lib/api/public/ServiceContext.h"
|
||||
#include "lib/api/public/ClientChannel.h"
|
||||
#include "lib/api/public/Result.h"
|
||||
#include "lib/api/public/Update.h"
|
||||
#include <rxcpp/rx.hpp>
|
||||
#include <string>
|
||||
#include <functional>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
|
||||
{{ns-open package}}
|
||||
|
||||
// Forward declaractions
|
||||
{{#each message_type}}
|
||||
class {{name}};
|
||||
{{/each}}
|
||||
|
||||
{{#each service}}
|
||||
|
||||
{{#each method}}{{#if server_streaming}}
|
||||
class {{../name}};
|
||||
typedef bts::api::Update<std::shared_ptr<const {{type output_type}}>, const {{key_type output_type}}, {{../name}}> {{cap name}}Update;
|
||||
{{/if}}{{/each}}
|
||||
|
||||
class {{api}} {{name}} {
|
||||
|
||||
std::unique_ptr<bts::api::ClientChannel> _pchannel;
|
||||
friend class bts::api::ServiceContext;
|
||||
{{name}}(std::unique_ptr<bts::api::ClientChannel> pchannel);
|
||||
// Key functions
|
||||
{{#each method}} {{#if server_streaming}}
|
||||
{{#has_complex_key output_type}}
|
||||
static const {{key_type output_type}}& {{name}}_key(const {{type output_type}}& row);
|
||||
{{else}}
|
||||
static {{key_type output_type}} {{name}}_key(const {{type output_type}}& row);
|
||||
{{/has_complex_key}}
|
||||
{{/if}} {{/each}}
|
||||
|
||||
public:
|
||||
{{name}}({{name}}&&);
|
||||
static const char* name() { return "{{name}}"; }
|
||||
|
||||
{{#each method}}
|
||||
{{#if server_streaming}}
|
||||
rxcpp::observable<{{cap name}}Update> subscribe_{{name}}(const {{type input_type}}& qualifier);
|
||||
rxcpp::observable<{{cap name}}Update> subscribe_{{name}}();
|
||||
{{else}}
|
||||
void {{name}}(const {{type input_type}}&, std::function<void(bts::api::Result<{{type output_type}}>)>, uint32_t timeout_ms=0);
|
||||
bts::api::Result<{{type output_type}}> {{name}}(const {{type input_type}}&, uint32_t timeout_ms=0);
|
||||
{{/if}}
|
||||
{{/each}}
|
||||
};
|
||||
{{/each}}
|
||||
|
||||
{{ns-close package}}
|
||||
@@ -0,0 +1,167 @@
|
||||
{{#if service}}
|
||||
#include "{{filename name}}.server.pb.h"
|
||||
#include "lib/api/public/ServiceContext.h"
|
||||
#include "lib/api/public/ApiUtils.h"
|
||||
#include "lib/api/core/ApiServerInterop.h"
|
||||
#include <unordered_map>
|
||||
{{ns-open package}}
|
||||
{{#each service}}
|
||||
|
||||
{{#each method}}{{#if server_streaming}}
|
||||
{{#has_complex_key output_type}}
|
||||
const {{key_type output_type}}& {{name}}_key(const {{type output_type}}& row) {
|
||||
return row.{{keyfield output_type}}();
|
||||
}
|
||||
{{else}}
|
||||
{{key_type output_type}} {{name}}_key(const {{type output_type}}& row) {
|
||||
return row.{{keyfield output_type}}();
|
||||
}
|
||||
{{/has_complex_key}}
|
||||
{{/if}}{{/each}}
|
||||
|
||||
{{name}}Base::{{name}}Base(bts::api::ServiceContext& context, const std::string& qualifier) :
|
||||
bts::api::ApiServer(context, "{{name}}", qualifier)
|
||||
{}
|
||||
|
||||
const char* {{name}}Base::name() const { return "{{name}}"; };
|
||||
|
||||
void {{name}}Base::dispatch(const bts::api::RequestHeader& header, google::protobuf::io::ZeroCopyInputStream& stream, OnResponse on_response) {
|
||||
switch((ServiceMethods)header.method()) {
|
||||
case SYS_PING: {
|
||||
bts::api::PingPong pp;
|
||||
if(pp.ParsePartialFromZeroCopyStream(&stream)) {
|
||||
respond(header.request_id(), pp, on_response);
|
||||
}
|
||||
} break;
|
||||
{{#each method}} {{#unless server_streaming}}
|
||||
case {{upper name}}: {
|
||||
{{type input_type}} msg;
|
||||
if (msg.ParsePartialFromZeroCopyStream(&stream)) {
|
||||
auto id = header.request_id();
|
||||
{{name}}(msg, [this,id,on_response](const {{type output_type}}& result) {
|
||||
respond(id, result, on_response);
|
||||
});
|
||||
}
|
||||
} break;
|
||||
{{/unless}}{{/each}}
|
||||
default: {
|
||||
bts::api::ResponseHeader response;
|
||||
response.set_request_id(header.request_id());
|
||||
response.set_code(ApiError::MISSING_METHOD);
|
||||
uint8_t buffer[64];
|
||||
int header_size = response.ByteSize() + 1;
|
||||
serialize(header_size, response, buffer);
|
||||
on_response(buffer, header_size);
|
||||
} break;
|
||||
}
|
||||
}
|
||||
|
||||
{{#each method}}{{#if server_streaming}}
|
||||
|
||||
{{../name}}Base::{{cap name}}Publisher {{../name}}Base::make_{{name}}_publisher(const {{type input_type}}& qualifier) const {
|
||||
TableHandle handle = _channel.create_table(format_qualifier("{{name}}", qualifier));
|
||||
return make_{{name}}_publisher(handle);
|
||||
}
|
||||
{{../name}}Base::{{cap name}}Publisher {{../name}}Base::make_{{name}}_publisher() const {
|
||||
TableHandle handle = _channel.create_table("{{name}}");
|
||||
return make_{{name}}_publisher(handle);
|
||||
}
|
||||
{{../name}}Base::{{cap name}}Publisher {{../name}}Base::make_{{name}}_publisher(TableHandle handle) const {
|
||||
{{#has_complex_key output_type}}
|
||||
std::unordered_map<{{key_type output_type}}, int> _map;
|
||||
int _next_id;
|
||||
std::shared_ptr<std::mutex> pmutex = std::make_shared<std::mutex>();
|
||||
auto get_key = [=](const {{key_type output_type}}& key) mutable -> int {
|
||||
std::lock_guard<std::mutex> guard(*pmutex);
|
||||
auto iter = _map.find(key);
|
||||
if (iter == _map.end()) {
|
||||
int id = ++_next_id;
|
||||
_map.insert(iter, std::make_pair(key, id));
|
||||
return id;
|
||||
}
|
||||
return iter->second;
|
||||
};
|
||||
{{/has_complex_key}}
|
||||
return [=](
|
||||
const std::vector<{{type output_type}}>* added,
|
||||
const std::vector<{{type output_type}}>* changed,
|
||||
std::set<{{key_type output_type}}>* removed) mutable {
|
||||
|
||||
int add_count = added ? added->size() : 0;
|
||||
int change_count = changed ? changed->size() : 0;
|
||||
int remove_count = removed ? removed->size() : 0;
|
||||
int total_updates = add_count + change_count + remove_count;
|
||||
|
||||
// Optimize small collections
|
||||
StreamUpdate stack_buffer[256];
|
||||
std::vector<StreamUpdate> heap_buffer;
|
||||
StreamUpdate* pupdates = stack_buffer;
|
||||
if (total_updates > 256) {
|
||||
heap_buffer.resize(total_updates);
|
||||
pupdates = &heap_buffer[0];
|
||||
}
|
||||
|
||||
int dest = 0;
|
||||
if (added) {
|
||||
for(const auto& item : *added) {
|
||||
StreamUpdate& update = pupdates[dest++];
|
||||
update.type = StreamUpdate::CREATE;
|
||||
if (removed != nullptr) {
|
||||
auto iter = removed->find({{name}}_key(item));
|
||||
if (iter != removed->end()) {
|
||||
removed->erase(iter);
|
||||
update.type = StreamUpdate::REPLACE;
|
||||
}
|
||||
}
|
||||
{{#has_complex_key output_type}}
|
||||
update.key = get_key({{name}}_key(item));
|
||||
{{else}}
|
||||
update.key = (int)({{name}}_key(item));
|
||||
{{/has_complex_key}}
|
||||
update.buffer_len = item.ByteSize();
|
||||
char* buffer = new char[update.buffer_len];
|
||||
item.SerializePartialToArray(buffer, update.buffer_len);
|
||||
update.buffer =buffer;
|
||||
}
|
||||
}
|
||||
if (changed) {
|
||||
for (const auto& item : *changed) {
|
||||
StreamUpdate& update = pupdates[dest++];
|
||||
update.type = StreamUpdate::REPLACE;
|
||||
{{#has_complex_key output_type}}
|
||||
update.key = get_key({{name}}_key(item));
|
||||
{{else}}
|
||||
update.key = (int)({{name}}_key(item));
|
||||
{{/has_complex_key}}
|
||||
update.buffer_len = item.ByteSize();
|
||||
char* buffer = new char[update.buffer_len];
|
||||
item.SerializePartialToArray(buffer, update.buffer_len);
|
||||
update.buffer =buffer;
|
||||
}
|
||||
}
|
||||
if (removed) {
|
||||
for (const auto& key : *removed) {
|
||||
StreamUpdate& update = pupdates[dest++];
|
||||
update.type = StreamUpdate::REMOVE;
|
||||
{{#has_complex_key output_type}}
|
||||
update.key = get_key(key);
|
||||
{{else}}
|
||||
update.key = (int)(key);
|
||||
{{/has_complex_key}}
|
||||
update.buffer_len = 0;
|
||||
update.buffer = nullptr;
|
||||
}
|
||||
}
|
||||
_channel.publish(handle, pupdates, dest);
|
||||
for (size_t x = 0; x < dest; ++x) {
|
||||
if (pupdates[x].buffer != nullptr) {
|
||||
delete[] pupdates[x].buffer;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
{{/if}} {{/each}}
|
||||
|
||||
{{/each}}
|
||||
{{ns-close package}}
|
||||
{{/if}}
|
||||
@@ -0,0 +1,56 @@
|
||||
#pragma once
|
||||
#include "{{filename name}}.pb.h"
|
||||
#include "lib/api/public/ApiServer.h"
|
||||
{{include_exports}}
|
||||
#include <string>
|
||||
#include <functional>
|
||||
#include <vector>
|
||||
#include <set>
|
||||
#include <memory>
|
||||
|
||||
// #include <iostream>
|
||||
// #include <atomic>
|
||||
namespace bts { namespace api {
|
||||
class ServiceContext;
|
||||
}}
|
||||
|
||||
{{ns-open package}}
|
||||
|
||||
// Forward declaractions
|
||||
{{#each message_type}}
|
||||
class {{name}};{{/each}}
|
||||
|
||||
{{#each service}}
|
||||
|
||||
class {{name}}Base : public bts::api::ApiServer {
|
||||
protected:
|
||||
{{name}}Base(bts::api::ServiceContext& context, const std::string& qualifier="");
|
||||
|
||||
const char* name() const override;
|
||||
|
||||
{{#each method}}
|
||||
{{#if server_streaming}}
|
||||
typedef std::function<void(const std::vector<{{type output_type}}>*, const std::vector<{{type output_type}}>*, std::set<{{key_type output_type}}>*)> {{cap name}}Publisher;
|
||||
{{cap name}}Publisher make_{{name}}_publisher() const;
|
||||
{{cap name}}Publisher make_{{name}}_publisher(const {{type input_type}}& qualifier) const;
|
||||
{{else}}
|
||||
virtual void {{name}}(const {{type input_type}}& request, std::function<void(const {{type output_type}}&)> reply) = 0;
|
||||
{{/if}}
|
||||
{{/each}}
|
||||
|
||||
enum ServiceMethods {
|
||||
SYS_PING = -1,
|
||||
{{#each method}}
|
||||
{{upper name}} = {{@index}},
|
||||
{{/each}}
|
||||
};
|
||||
|
||||
private:
|
||||
void dispatch(const bts::api::RequestHeader&, google::protobuf::io::ZeroCopyInputStream&, OnResponse) override;
|
||||
{{#each method}}{{#if server_streaming}}
|
||||
{{cap name}}Publisher make_{{name}}_publisher(TableHandle) const;
|
||||
{{/if}}{{/each}}
|
||||
};
|
||||
|
||||
{{/each}}
|
||||
{{ns-close package}}
|
||||
@@ -0,0 +1,34 @@
|
||||
syntax="proto3";
|
||||
package bts.api.test;
|
||||
option csharp_namespace="bts.api.test";
|
||||
import "lib/api/apioptions.proto";
|
||||
|
||||
message HelloRequest {
|
||||
string name = 1;
|
||||
}
|
||||
message HelloResponse {
|
||||
string message = 1;
|
||||
}
|
||||
message HelloLog {
|
||||
string myid = 1 [(bts.api.key)=true];
|
||||
string message = 10;
|
||||
}
|
||||
message HelloSubArgs {
|
||||
string name = 1;
|
||||
}
|
||||
service HelloService {
|
||||
rpc say_hello(HelloRequest) returns (HelloResponse);
|
||||
rpc greetings(HelloSubArgs) returns (stream HelloLog);
|
||||
rpc yell_hello(HelloRequest) returns (HelloResponse);
|
||||
}
|
||||
|
||||
message ShoutRequest {
|
||||
string msg = 1;
|
||||
}
|
||||
message ShoutResponse {
|
||||
string MSG = 1;
|
||||
}
|
||||
service ShoutService {
|
||||
option (bts.api.service_description) = "Makes input message louder";
|
||||
rpc upper(ShoutRequest) returns (ShoutResponse);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
#include "../public/ServiceContext.h"
|
||||
#include "../public/ApiUtils.h"
|
||||
#include "lib/utils/bts_export.h"
|
||||
#include "HelloServiceServer.h"
|
||||
|
||||
#include "lib/api/services/ApiUnitTestService.server.pb.h"
|
||||
|
||||
#include <memory>
|
||||
#include <functional>
|
||||
|
||||
using namespace std;
|
||||
|
||||
namespace bts {
|
||||
namespace api {
|
||||
namespace test {
|
||||
|
||||
struct ApiTestServiceServer: ApiTestServiceBase {
|
||||
ServiceContext& _ctx;
|
||||
unique_ptr<HelloServiceServer> _hello;
|
||||
unique_ptr<ShoutServiceServer> _shout;
|
||||
|
||||
ApiTestServiceServer(ServiceContext& ctx) :
|
||||
ApiTestServiceBase(ctx, "cpp"),
|
||||
_ctx(ctx),
|
||||
_hello(),
|
||||
_shout()
|
||||
{}
|
||||
// Inherited via ApiTestServiceBase
|
||||
virtual void format_qualifier(const QualifierArgument & request, function<void(const TestResult&)> reply) override {
|
||||
TestResult result;
|
||||
switch (request.qualifier_case()) {
|
||||
case QualifierArgument::kSimple:
|
||||
result.set_str(
|
||||
bts::api::format_qualifier("format_qualifier", request.simple()));
|
||||
break;
|
||||
case QualifierArgument::kComplex:
|
||||
result.set_str(
|
||||
bts::api::format_qualifier("format_qualifier", request.complex()));
|
||||
break;
|
||||
default:
|
||||
result.set_str("Unknown qualifier test case");
|
||||
break;
|
||||
}
|
||||
reply(result);
|
||||
}
|
||||
|
||||
// Inherited via ApiTestServiceBase
|
||||
virtual void test_empty_reply(const EmptyRequest&, std::function<void(const TestResult&)> reply) override {
|
||||
TestResult result;
|
||||
reply(result);
|
||||
}
|
||||
|
||||
virtual void run_hello_service(const EmptyRequest&, std::function<void(const TestResult&)> reply) {
|
||||
_hello.reset(new HelloServiceServer(_ctx));
|
||||
reply(TestResult());
|
||||
}
|
||||
virtual void stop_hello_service(const EmptyRequest&, std::function<void(const TestResult&)> reply) {
|
||||
_hello.reset();
|
||||
reply(TestResult());
|
||||
}
|
||||
virtual void run_shout_service(const EmptyRequest&, std::function<void(const TestResult&)> reply) {
|
||||
_shout.reset(new ShoutServiceServer(_ctx));
|
||||
reply(TestResult());
|
||||
}
|
||||
virtual void stop_shout_service(const EmptyRequest&, std::function<void(const TestResult&)> reply) {
|
||||
_shout.reset();
|
||||
reply(TestResult());
|
||||
}
|
||||
|
||||
|
||||
};
|
||||
|
||||
struct ApiTestBundle {
|
||||
ApiTestBundle() : ctx(), server() {}
|
||||
unique_ptr<ServiceContext> ctx;
|
||||
unique_ptr<ApiTestServiceServer> server;
|
||||
};
|
||||
|
||||
extern "C" BTS_EXPORT ApiTestBundle* apitest_start_apitest_service(bts::qbus::Quickbus* bus) {
|
||||
ApiTestBundle* pbundle = new ApiTestBundle();
|
||||
pbundle->ctx.reset(new ServiceContext(bus));
|
||||
pbundle->server.reset(new ApiTestServiceServer(*pbundle->ctx));
|
||||
return pbundle;
|
||||
}
|
||||
|
||||
extern "C" BTS_EXPORT void apitest_stop_apitest_service(ApiTestBundle* server) {
|
||||
if (server != nullptr) delete server;
|
||||
}
|
||||
|
||||
}}}//namespace
|
||||
@@ -0,0 +1,66 @@
|
||||
#include "HelloServiceServer.h"
|
||||
#include <boost/algorithm/string.hpp>
|
||||
#include <string>
|
||||
|
||||
namespace bts {
|
||||
namespace api {
|
||||
namespace test {
|
||||
|
||||
HelloServiceServer::HelloServiceServer(bts::api::ServiceContext & context) :
|
||||
HelloServiceBase(context),
|
||||
_id(0),
|
||||
_shouter(context.locate<ShoutService>()),
|
||||
_gpub(make_greetings_publisher())
|
||||
{ }
|
||||
|
||||
void HelloServiceServer::publish(const std::string& msg, int* to_remove) {
|
||||
std::vector<HelloLog> added;
|
||||
HelloLog row;
|
||||
char id[128];
|
||||
sprintf(id, "%i", ++_id);
|
||||
row.set_myid(id);
|
||||
row.set_message(msg);
|
||||
added.push_back(row);
|
||||
std::set<std::string> removed;
|
||||
if (to_remove) {
|
||||
sprintf(id, "%i", *to_remove);
|
||||
removed.insert(id);
|
||||
}
|
||||
_gpub(&added, nullptr, &removed);
|
||||
}
|
||||
|
||||
void HelloServiceServer::say_hello(const HelloRequest & request, std::function<void(const HelloResponse&)> reply) {
|
||||
HelloResponse response;
|
||||
response.set_message("hello " + request.name());
|
||||
publish(response.message());
|
||||
reply(response);
|
||||
}
|
||||
|
||||
void HelloServiceServer::yell_hello(const HelloRequest & request, std::function<void(const HelloResponse&)> reply) {
|
||||
|
||||
HelloResponse response;
|
||||
ShoutRequest sr;
|
||||
sr.set_msg("hello " + request.name());
|
||||
_shouter.upper(sr, [=](Result<ShoutResponse> response) {
|
||||
if (response.success()) {
|
||||
HelloResponse hr;
|
||||
hr.set_message(response.result()->msg());
|
||||
int rmid = _id;
|
||||
publish(hr.message(), &rmid);
|
||||
reply(hr);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
ShoutServiceServer::ShoutServiceServer(bts::api::ServiceContext & context) :
|
||||
ShoutServiceBase(context)
|
||||
{ }
|
||||
void test::ShoutServiceServer::upper(const ShoutRequest & request, std::function<void(const ShoutResponse&)> on_result) {
|
||||
ShoutResponse response;
|
||||
response.set_msg(
|
||||
boost::to_upper_copy(request.msg()));
|
||||
on_result(response);
|
||||
}
|
||||
|
||||
}}}//namespace
|
||||
@@ -0,0 +1,39 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/utils/bts_no_copy.h"
|
||||
#include "lib/utils/bts_export.h"
|
||||
|
||||
#include "lib/api/services/HelloService.server.pb.h"
|
||||
#include "lib/api/services/HelloService.client.pb.h"
|
||||
|
||||
namespace bts {
|
||||
namespace api {
|
||||
namespace test {
|
||||
|
||||
struct BTS_SYS_API HelloServiceServer : public HelloServiceBase
|
||||
{
|
||||
public:
|
||||
HelloServiceServer(bts::api::ServiceContext& context);
|
||||
|
||||
private:
|
||||
BTS_NO_COPY(HelloServiceServer);
|
||||
int _id;
|
||||
ShoutService _shouter;
|
||||
GreetingsPublisher _gpub;
|
||||
|
||||
void publish(const std::string& msg, int * to_remove=nullptr);
|
||||
|
||||
// Inherited via HelloServiceBase
|
||||
virtual void say_hello(const HelloRequest & request, std::function<void(const HelloResponse&)> on_result) override;
|
||||
virtual void yell_hello(const HelloRequest & request, std::function<void(const HelloResponse&)> on_result) override;
|
||||
};
|
||||
|
||||
struct BTS_SYS_API ShoutServiceServer : public ShoutServiceBase
|
||||
{
|
||||
ShoutServiceServer(bts::api::ServiceContext& context);
|
||||
// Inherited via ShoutServiceBase
|
||||
virtual void upper(const ShoutRequest & request, std::function<void(const ShoutResponse&)> on_result) override;
|
||||
};
|
||||
|
||||
}}}//namespace
|
||||
|
||||
Executable
+82
@@ -0,0 +1,82 @@
|
||||
#include "ConfigDownloader.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <boost/algorithm/string.hpp>
|
||||
#include <sstream>
|
||||
|
||||
#include "lib/utils/bts_assert.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
namespace bts {
|
||||
namespace config {
|
||||
namespace internal {
|
||||
|
||||
ConfigDownloader::ConfigDownloader() :
|
||||
_curl(NULL)
|
||||
{
|
||||
curl_global_init(CURL_GLOBAL_DEFAULT);
|
||||
_curl = curl_easy_init();
|
||||
bts_assert(_curl);
|
||||
}
|
||||
|
||||
ConfigDownloader::~ConfigDownloader()
|
||||
{
|
||||
curl_easy_cleanup(_curl);
|
||||
}
|
||||
|
||||
size_t curl_write(char* buffer, size_t size, size_t count, void* stream) {
|
||||
stringstream* out = static_cast<stringstream*>(stream);
|
||||
bts_assert(out);
|
||||
size_t bytes = size * count;
|
||||
out->write(buffer, bytes);
|
||||
return count;
|
||||
}
|
||||
|
||||
bool is_http(const string& url) {
|
||||
return url.substr(0,7) == "http://";
|
||||
}
|
||||
|
||||
int no_linger(void*, curl_socket_t socket, curlsocktype) {
|
||||
linger l;
|
||||
l.l_onoff = 1;
|
||||
l.l_linger = 0;
|
||||
setsockopt(socket, SOL_SOCKET, SO_LINGER, (char*)&l, sizeof(l));
|
||||
return CURL_SOCKOPT_OK;
|
||||
}
|
||||
|
||||
ConfigDownloader::Result ConfigDownloader::get(const string& url, stringstream& out_stream) {
|
||||
curl_easy_setopt(_curl, CURLOPT_URL, url.c_str());
|
||||
curl_easy_setopt(_curl, CURLOPT_WRITEFUNCTION, curl_write);
|
||||
curl_easy_setopt(_curl, CURLOPT_WRITEDATA, &out_stream);
|
||||
curl_easy_setopt(_curl, CURLOPT_VERBOSE, 0);
|
||||
curl_easy_setopt(_curl, CURLOPT_FAILONERROR, 1);
|
||||
curl_easy_setopt(_curl, CURLOPT_CONNECTTIMEOUT, 30);
|
||||
curl_easy_setopt(_curl, CURLOPT_SOCKOPTFUNCTION, no_linger);
|
||||
|
||||
CURLcode res = curl_easy_perform(_curl);
|
||||
|
||||
long http_code = 0;
|
||||
CURLcode r2 = curl_easy_getinfo(_curl, CURLINFO_RESPONSE_CODE, &http_code);
|
||||
bts_assert(r2 == CURLE_OK);
|
||||
|
||||
bool used_http = is_http(url);
|
||||
if (res == CURLE_OK && (http_code == 200 || !used_http)) {
|
||||
return SUCCESS;
|
||||
} else
|
||||
if (res == CURLE_OPERATION_TIMEDOUT
|
||||
|| res == CURLE_COULDNT_RESOLVE_HOST
|
||||
|| res == CURLE_COULDNT_RESOLVE_PROXY
|
||||
|| res == CURLE_COULDNT_CONNECT
|
||||
|| res == CURLE_REMOTE_ACCESS_DENIED
|
||||
|| res == CURLE_FTP_CANT_GET_HOST
|
||||
) {
|
||||
// Cannot rely on logging before config is initialized
|
||||
// LOG(Error, Config) << "Permanent failure loading '" << url << "' - CURL error: " << curl_easy_strerror(res);
|
||||
return PERMANENT_FAILURE;
|
||||
}
|
||||
return FAILURE;
|
||||
}
|
||||
|
||||
}}}//namespace
|
||||
|
||||
Executable
+32
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/utils/bts_no_copy.h"
|
||||
#include <curl/curl.h>
|
||||
#include <string>
|
||||
|
||||
namespace bts {
|
||||
namespace config {
|
||||
namespace internal {
|
||||
|
||||
|
||||
class ConfigDownloader
|
||||
{
|
||||
public:
|
||||
ConfigDownloader();
|
||||
~ConfigDownloader();
|
||||
|
||||
enum Result {
|
||||
FAILURE,
|
||||
SUCCESS,
|
||||
PERMANENT_FAILURE
|
||||
};
|
||||
|
||||
Result get(const std::string& url, std::stringstream& out_stream);
|
||||
|
||||
private:
|
||||
BTS_NO_COPY(ConfigDownloader);
|
||||
CURL* _curl;
|
||||
};
|
||||
|
||||
}}}//namespace
|
||||
|
||||
Executable
+72
@@ -0,0 +1,72 @@
|
||||
#include "ConfigErrorCollector.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace bts {
|
||||
namespace config {
|
||||
namespace internal {
|
||||
|
||||
ConfigErrorCollector::ConfigErrorCollector(IConfigLog& log, const char* file):
|
||||
_log(log),
|
||||
_file(file),
|
||||
_errors()
|
||||
{
|
||||
}
|
||||
|
||||
inline std::string format(const std::string& file, int line, int column, const std::string& message)
|
||||
{
|
||||
std::stringstream buffer;
|
||||
buffer << file.c_str() << ":" << line+1 << ":" << column+1 << ": error: " << message;
|
||||
return buffer.str();
|
||||
}
|
||||
|
||||
void ConfigErrorCollector::AddError(int line, int column, const std::string& message)
|
||||
{
|
||||
_errors.push_back(format(_file, line, column, message));
|
||||
}
|
||||
|
||||
void ConfigErrorCollector::AddWarning(int line, int column, const std::string& message)
|
||||
{
|
||||
_log.warning(format(_file, line, column, message));
|
||||
}
|
||||
|
||||
// For debugging purposes
|
||||
void ConfigErrorCollector::AddError(
|
||||
const std::string& , // File name in which the error occurred.
|
||||
const std::string& , // Full name of the erroneous element.
|
||||
const proto::Message* , // Descriptor of the erroneous element.
|
||||
ErrorLocation , // One of the location constants, above.
|
||||
const std::string& // Human-readable error message.
|
||||
)
|
||||
{
|
||||
//_log.warning(format(filename, 0, 0, message));
|
||||
}
|
||||
|
||||
// For debugging purposes
|
||||
void ConfigErrorCollector::AddWarning(
|
||||
const std::string& , // File name in which the error occurred.
|
||||
const std::string& , // Full name of the erroneous element.
|
||||
const proto::Message* , // Descriptor of the erroneous element.
|
||||
ErrorLocation , // One of the location constants, above.
|
||||
const std::string& // Human-readable error message.
|
||||
)
|
||||
{
|
||||
//_log.warning(format(filename, 0, 0, message));
|
||||
}
|
||||
|
||||
std::string ConfigErrorCollector::ToString()
|
||||
{
|
||||
if (_errors.size() == 0) return "";
|
||||
|
||||
std::string error = _errors.front();
|
||||
for (size_t x = 1; x < _errors.size(); x++)
|
||||
{
|
||||
error += '\n';
|
||||
error += _errors[x];
|
||||
}
|
||||
|
||||
return error;
|
||||
}
|
||||
|
||||
}}}//namespace
|
||||
|
||||
Executable
+53
@@ -0,0 +1,53 @@
|
||||
#pragma once
|
||||
|
||||
#include "ConfigLog.h"
|
||||
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <google/protobuf/io/tokenizer.h>
|
||||
#include <google/protobuf/descriptor.h>
|
||||
|
||||
namespace proto = google::protobuf;
|
||||
|
||||
namespace bts {
|
||||
namespace config {
|
||||
namespace internal {
|
||||
|
||||
class ConfigErrorCollector :
|
||||
public proto::io::ErrorCollector,
|
||||
public proto::DescriptorPool::ErrorCollector
|
||||
{
|
||||
public:
|
||||
ConfigErrorCollector(IConfigLog& log, const char* file);
|
||||
|
||||
void AddError(int line, int column, const std::string& message) override;
|
||||
void AddWarning(int line, int column, const std::string& message) override;
|
||||
|
||||
void AddError(
|
||||
const std::string& filename, // File name in which the error occurred.
|
||||
const std::string& element_name, // Full name of the erroneous element.
|
||||
const proto::Message* descriptor, // Descriptor of the erroneous element.
|
||||
ErrorLocation location, // One of the location constants, above.
|
||||
const std::string& message // Human-readable error message.
|
||||
) override;
|
||||
|
||||
void AddWarning(
|
||||
const std::string& filename, // File name in which the error occurred.
|
||||
const std::string& element_name, // Full name of the erroneous element.
|
||||
const proto::Message* descriptor, // Descriptor of the erroneous element.
|
||||
ErrorLocation location, // One of the location constants, above.
|
||||
const std::string& message // Human-readable error message.
|
||||
) override;
|
||||
|
||||
std::string ToString();
|
||||
|
||||
private:
|
||||
BTS_NO_COPY(ConfigErrorCollector);
|
||||
|
||||
IConfigLog& _log;
|
||||
std::string _file;
|
||||
std::vector<std::string> _errors;
|
||||
};
|
||||
|
||||
}}}//namespace
|
||||
|
||||
Executable
+105
@@ -0,0 +1,105 @@
|
||||
#include "ConfigLog.h"
|
||||
|
||||
#include "lib/logging/logging.h"
|
||||
|
||||
namespace bts {
|
||||
namespace config {
|
||||
namespace internal {
|
||||
|
||||
struct ConfigLog::PImpl {
|
||||
PImpl() :
|
||||
print_errors(true),
|
||||
logger_hub("config_logger"),
|
||||
logger(logger_hub.make_logger())
|
||||
{}
|
||||
|
||||
bool print_errors;
|
||||
log::LoggerHub logger_hub;
|
||||
log::Logger &logger;
|
||||
};
|
||||
|
||||
ConfigLog::ConfigLog() :
|
||||
me (new PImpl())
|
||||
{
|
||||
log::LoggingConfig cfg;
|
||||
cfg.level_names = { {Diag,"Diag"},{Info,"Info"},
|
||||
{Warn,"Warn"},{Error,"Error"},
|
||||
{Fatal,"Fatal"},{Sys,"Sys"} };
|
||||
cfg.subsystem_names = { {Gen,"Gen"},{Log,"Log"} };
|
||||
|
||||
cfg.logger_initial_queue_size = 10;
|
||||
|
||||
log::Filter f;
|
||||
|
||||
f[Cfg.ordinal] = Warn;
|
||||
cfg.sinks["console"] = std::make_pair (log::console_sink(),f);
|
||||
|
||||
f[Cfg.ordinal] = Info;
|
||||
cfg.sinks["syslog"] = std::make_pair (log::syslog_sink(),f);
|
||||
|
||||
me->logger_hub.config(cfg);
|
||||
}
|
||||
|
||||
ConfigLog::~ConfigLog()
|
||||
{
|
||||
me->logger.mark_inactive();
|
||||
}
|
||||
|
||||
bool ConfigLog::print_errors() const {return me->print_errors;}
|
||||
void ConfigLog::set_print_errors(bool value) {me->print_errors = value;}
|
||||
|
||||
void ConfigLog::info(const std::string& msg)
|
||||
{
|
||||
if (me->print_errors)
|
||||
me->logger.enqueue(Cfg,Info,__FILE__,__LINE__,"{0}",msg);
|
||||
}
|
||||
|
||||
void ConfigLog::error(const std::string& msg)
|
||||
{
|
||||
if (me->print_errors)
|
||||
me->logger.enqueue(Cfg,Error,__FILE__,__LINE__,"{0}",msg);
|
||||
}
|
||||
|
||||
void ConfigLog::warning(const std::string& msg)
|
||||
{
|
||||
if (me->print_errors)
|
||||
me->logger.enqueue(Cfg,Warn,__FILE__,__LINE__,"{0}",msg);
|
||||
}
|
||||
|
||||
//
|
||||
// Log Aggregator
|
||||
|
||||
LogAggregator::LogAggregator(IConfigLog& log) :
|
||||
_log(log),
|
||||
_buffer()
|
||||
{
|
||||
}
|
||||
|
||||
void LogAggregator::info(const std::string& msg) {
|
||||
_buffer << msg;
|
||||
#ifdef _WIN32
|
||||
_buffer << std::endl;
|
||||
#else
|
||||
_buffer << " ";
|
||||
#endif
|
||||
}
|
||||
|
||||
void LogAggregator::error(const std::string& msg) {
|
||||
_log.error(msg);
|
||||
}
|
||||
|
||||
void LogAggregator::warning(const std::string& msg) {
|
||||
_log.warning(msg);
|
||||
_buffer << "> Warning: " << msg << std::endl;
|
||||
#ifdef _WIN32
|
||||
_buffer << std::endl;
|
||||
#else
|
||||
_buffer << " ";
|
||||
#endif
|
||||
}
|
||||
|
||||
std::string LogAggregator::text() { return _buffer.str(); }
|
||||
|
||||
|
||||
}}}//namespace
|
||||
|
||||
Executable
+72
@@ -0,0 +1,72 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/utils/bts_no_copy.h"
|
||||
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
#include <memory>
|
||||
|
||||
namespace bts {
|
||||
namespace config {
|
||||
namespace internal {
|
||||
|
||||
class IConfigLog
|
||||
{
|
||||
public:
|
||||
virtual void info(const std::string& msg) = 0;
|
||||
virtual void error(const std::string& msg) = 0;
|
||||
virtual void warning(const std::string& msg) = 0;
|
||||
virtual ~IConfigLog() { }
|
||||
};
|
||||
|
||||
// A back door though the logging system
|
||||
// To allow config diagnostic logging
|
||||
class ConfigLog : public IConfigLog
|
||||
{
|
||||
public:
|
||||
ConfigLog();
|
||||
~ConfigLog();
|
||||
|
||||
void info(const std::string& msg);
|
||||
void error(const std::string& msg);
|
||||
void warning(const std::string& msg);
|
||||
|
||||
bool print_errors() const ;
|
||||
void set_print_errors(bool value) ;
|
||||
|
||||
private:
|
||||
struct PImpl;
|
||||
std::unique_ptr<PImpl> me;
|
||||
};
|
||||
|
||||
// Log aggregator aggregates Info and warning messages into one string
|
||||
// but passes error message through to the log immediately
|
||||
class LogAggregator : public IConfigLog
|
||||
{
|
||||
public:
|
||||
LogAggregator(IConfigLog& real_log);
|
||||
void info(const std::string&);
|
||||
void error(const std::string&);
|
||||
void warning(const std::string&);
|
||||
|
||||
std::string text();
|
||||
|
||||
private:
|
||||
IConfigLog& _log;
|
||||
std::ostringstream _buffer;
|
||||
};
|
||||
|
||||
class ErrorsOnlyLog : public IConfigLog
|
||||
{
|
||||
public:
|
||||
ErrorsOnlyLog(IConfigLog& log) : _log(log) {}
|
||||
~ErrorsOnlyLog() {}
|
||||
void info(const std::string&) {}
|
||||
void error(const std::string& msg) { _log.error(msg); }
|
||||
void warning(const std::string& msg) { _log.error(msg); }
|
||||
private:
|
||||
IConfigLog& _log;
|
||||
};
|
||||
|
||||
}}}//namespace
|
||||
|
||||
Executable
+296
@@ -0,0 +1,296 @@
|
||||
#include "ConfigPropertyEvaluator.h"
|
||||
|
||||
#include "lib/utils/windows_wrapper.h"
|
||||
#include "lib/utils/bts_assert.h"
|
||||
#include "lib/expression/ExpressionEvaluator.h"
|
||||
#include "ConfigurationState.h"
|
||||
|
||||
#include <boost/tokenizer.hpp>
|
||||
#include <google/protobuf/descriptor.h>
|
||||
|
||||
namespace bts {
|
||||
namespace config {
|
||||
namespace internal {
|
||||
|
||||
using namespace bts::expression;
|
||||
using namespace boost;
|
||||
using expression::Value;
|
||||
namespace proto = google::protobuf;
|
||||
|
||||
class ConfigListRuleEvaluatorShim : public expression::IPropertyEvaluator
|
||||
{
|
||||
expression::IPropertyEvaluator& _eval;
|
||||
public:
|
||||
ConfigListRuleEvaluatorShim(expression::IPropertyEvaluator& eval) : _eval(eval) { }
|
||||
virtual ~ConfigListRuleEvaluatorShim() {}
|
||||
virtual bool get_value(const std::string& property, Value* out_value) { return _eval.get_value(property, out_value); }
|
||||
};
|
||||
|
||||
|
||||
ConfigPropertyEvaluator::ConfigPropertyEvaluator(ConfigurationState& config)
|
||||
: _config(config), _rule_engine()
|
||||
{
|
||||
std::shared_ptr<IPropertyEvaluator> ptr(new ConfigListRuleEvaluatorShim(*this));
|
||||
_rule_engine.reset(new expression::ExpressionEvaluator(ptr));
|
||||
}
|
||||
|
||||
ConfigPropertyEvaluator::~ConfigPropertyEvaluator()
|
||||
{
|
||||
}
|
||||
|
||||
void get_field_scalar(const proto::Message& message, const proto::FieldDescriptor* field_desc,
|
||||
Value& out_value)
|
||||
{
|
||||
const proto::Reflection* mirror = message.GetReflection();
|
||||
|
||||
switch(field_desc->cpp_type())
|
||||
{
|
||||
case proto::FieldDescriptor::CPPTYPE_INT32:
|
||||
out_value = Value((double) mirror->GetInt32(message, field_desc));
|
||||
break;
|
||||
case proto::FieldDescriptor::CPPTYPE_INT64:
|
||||
out_value = Value((double) mirror->GetInt64(message, field_desc));
|
||||
break;
|
||||
case proto::FieldDescriptor::CPPTYPE_UINT32:
|
||||
out_value = Value((double) mirror->GetUInt32(message, field_desc));
|
||||
break;
|
||||
case proto::FieldDescriptor::CPPTYPE_UINT64:
|
||||
out_value = Value((double) mirror->GetUInt64(message, field_desc));
|
||||
break;
|
||||
case proto::FieldDescriptor::CPPTYPE_DOUBLE:
|
||||
out_value = Value(mirror->GetDouble(message, field_desc));
|
||||
break;
|
||||
case proto::FieldDescriptor::CPPTYPE_FLOAT:
|
||||
out_value = Value((double) mirror->GetFloat(message, field_desc));
|
||||
break;
|
||||
case proto::FieldDescriptor::CPPTYPE_BOOL:
|
||||
out_value = Value(mirror->GetBool(message, field_desc));
|
||||
break;
|
||||
case proto::FieldDescriptor::CPPTYPE_STRING:
|
||||
out_value = Value(mirror->GetString(message, field_desc));
|
||||
break;
|
||||
case proto::FieldDescriptor::CPPTYPE_ENUM:
|
||||
out_value = Value(mirror->GetEnum(message, field_desc)->name());
|
||||
break;
|
||||
case proto::FieldDescriptor::CPPTYPE_MESSAGE:
|
||||
out_value = Value((void*)&mirror->GetMessage(message, field_desc));
|
||||
break;
|
||||
default:
|
||||
throw std::invalid_argument("Unsupported field type in Config rule");
|
||||
}
|
||||
}
|
||||
|
||||
void get_field_vector(const proto::Message& message, const proto::FieldDescriptor* field_desc, Value& out_value)
|
||||
{
|
||||
const proto::Reflection* mirror = message.GetReflection();
|
||||
size_t field_size = mirror->FieldSize(message, field_desc);
|
||||
|
||||
std::vector<Value> values;
|
||||
|
||||
switch(field_desc->cpp_type())
|
||||
{
|
||||
case proto::FieldDescriptor::CPPTYPE_INT32:
|
||||
for(size_t index = 0; index < field_size; index++)
|
||||
{
|
||||
values.push_back(
|
||||
Value((double) mirror->GetRepeatedInt32(message, field_desc, index)));
|
||||
}
|
||||
break;
|
||||
case proto::FieldDescriptor::CPPTYPE_INT64:
|
||||
for(size_t index = 0; index < field_size; index++)
|
||||
{
|
||||
values.push_back(
|
||||
Value((double) mirror->GetRepeatedInt64(message, field_desc, index)));
|
||||
}
|
||||
break;
|
||||
case proto::FieldDescriptor::CPPTYPE_UINT32:
|
||||
for(size_t index = 0; index < field_size; index++)
|
||||
{
|
||||
values.push_back(
|
||||
Value((double) mirror->GetRepeatedUInt32(message, field_desc, index)));
|
||||
}
|
||||
break;
|
||||
case proto::FieldDescriptor::CPPTYPE_UINT64:
|
||||
for(size_t index = 0; index < field_size; index++)
|
||||
{
|
||||
values.push_back(
|
||||
Value((double) mirror->GetRepeatedUInt64(message, field_desc, index)));
|
||||
}
|
||||
break;
|
||||
case proto::FieldDescriptor::CPPTYPE_DOUBLE:
|
||||
for(size_t index = 0; index < field_size; index++)
|
||||
{
|
||||
values.push_back(
|
||||
Value((double) mirror->GetRepeatedDouble(message, field_desc, index)));
|
||||
}
|
||||
break;
|
||||
case proto::FieldDescriptor::CPPTYPE_FLOAT:
|
||||
for(size_t index = 0; index < field_size; index++)
|
||||
{
|
||||
values.push_back(
|
||||
Value((double) mirror->GetRepeatedFloat(message, field_desc, index)));
|
||||
}
|
||||
break;
|
||||
case proto::FieldDescriptor::CPPTYPE_BOOL:
|
||||
for(size_t index = 0; index < field_size; index++)
|
||||
{
|
||||
values.push_back(
|
||||
Value(mirror->GetRepeatedBool(message, field_desc, index)));
|
||||
}
|
||||
break;
|
||||
case proto::FieldDescriptor::CPPTYPE_STRING:
|
||||
for(size_t index = 0; index < field_size; index++)
|
||||
{
|
||||
values.push_back(
|
||||
Value(mirror->GetRepeatedString(message, field_desc, index)));
|
||||
}
|
||||
break;
|
||||
case proto::FieldDescriptor::CPPTYPE_ENUM:
|
||||
for (size_t index = 0; index < field_size; index++) {
|
||||
values.push_back(
|
||||
Value(mirror->GetRepeatedEnum(message, field_desc, index)->name()));
|
||||
}
|
||||
break;
|
||||
case proto::FieldDescriptor::CPPTYPE_MESSAGE:
|
||||
for (size_t index = 0; index < field_size; index++) {
|
||||
values.push_back(
|
||||
Value((void*)&mirror->GetRepeatedMessage(message, field_desc, index)));
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw std::invalid_argument("Unsupported field type in Config rule");
|
||||
}
|
||||
|
||||
out_value = Value(values);
|
||||
}
|
||||
|
||||
const proto::Message* lookup_key(std::shared_ptr<expression::ExpressionEvaluator> evaluator,
|
||||
const proto::Message* message, const proto::FieldDescriptor* field, const std::string& search_key) {
|
||||
bts_assert(message);
|
||||
bts_assert(field);
|
||||
bts_assert(!search_key.empty());
|
||||
bts_assert(field->is_repeated());
|
||||
bts_assert(field->type() == proto::FieldDescriptor::TYPE_MESSAGE);
|
||||
|
||||
const proto::Reflection* mirror = message->GetReflection();
|
||||
int size = mirror->FieldSize(*message, field);
|
||||
|
||||
const proto::FieldDescriptor* key_field = NULL;
|
||||
const proto::FieldDescriptor* rule_field = NULL;
|
||||
const proto::Reflection* key_reflection = NULL;
|
||||
for (int x = 0; x < size; x++) {
|
||||
// Iterate through the field instances
|
||||
const proto::Message& cur = mirror->GetRepeatedMessage(*message, field, x);
|
||||
if (x == 0) {
|
||||
// Grab the reflection and field descriptor for the repeated type
|
||||
key_reflection = cur.GetReflection();
|
||||
bts_assert(key_reflection);
|
||||
// Use the reflection object to look for a field named "key" or "name"
|
||||
key_field = cur.GetDescriptor()->FindFieldByLowercaseName("key");
|
||||
if (key_field == NULL) {
|
||||
key_field = cur.GetDescriptor()->FindFieldByLowercaseName("name");
|
||||
if (key_field == NULL) {
|
||||
// If there is no key abandon ship
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (key_field->type() != proto::FieldDescriptor::TYPE_STRING) {
|
||||
// To keep things simple the key must be a string
|
||||
break;
|
||||
}
|
||||
rule_field = cur.GetDescriptor()->FindFieldByLowercaseName("rule");
|
||||
}
|
||||
|
||||
std::string key;
|
||||
key = key_reflection->GetStringReference(cur, key_field, &key);
|
||||
if (key == search_key)
|
||||
{
|
||||
if(rule_field != NULL)
|
||||
{
|
||||
std::string rule;
|
||||
rule = key_reflection->GetStringReference(cur, rule_field, &rule);
|
||||
if(rule != "" && !evaluator->eval(rule))
|
||||
return cur.New();
|
||||
}
|
||||
return &cur;
|
||||
}
|
||||
}
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
bool ConfigPropertyEvaluator::get_value(const std::string& property, Value* out_value)
|
||||
{
|
||||
bts_assert(out_value);
|
||||
if (property[0] == '$')
|
||||
{
|
||||
*out_value = _config.get_macro(property);
|
||||
return true;
|
||||
}
|
||||
|
||||
// 1) Get the proto::Message* from config
|
||||
tokenizer<char_separator<char> > tokens(property, char_separator<char>(".[]")); // Note: Split arbitrarily on [], enforcing matching brackets is done in the parser
|
||||
tokenizer<char_separator<char> >::iterator iter = tokens.begin (), end = tokens.end ();
|
||||
|
||||
// The first token is the key name
|
||||
const proto::Message* key = _config.try_get_message(*iter);
|
||||
if (!key) return false;
|
||||
|
||||
// 2) Drill down using reflection to find the named property
|
||||
do
|
||||
{
|
||||
++iter;
|
||||
|
||||
if (iter == end) {
|
||||
// We're asking for a complete Message
|
||||
*out_value = Value((void*)key);
|
||||
return true;
|
||||
}
|
||||
|
||||
const proto::Descriptor* message_desc = key->GetDescriptor();
|
||||
std::string field_name = *iter;
|
||||
const proto::FieldDescriptor* field_desc = message_desc->FindFieldByName(field_name);
|
||||
|
||||
if (field_desc)
|
||||
{
|
||||
if (field_desc->is_repeated())
|
||||
{
|
||||
++iter;
|
||||
if (field_desc->type() == proto::FieldDescriptor::TYPE_MESSAGE && iter != end)
|
||||
{
|
||||
// Treat the next token as a key into the list
|
||||
key = lookup_key(_rule_engine, key, field_desc, *iter);
|
||||
if (key == NULL) return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
get_field_vector(*key, field_desc, *out_value);
|
||||
return (iter == end);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (field_desc->type() != proto::FieldDescriptor::TYPE_MESSAGE)
|
||||
{
|
||||
get_field_scalar(*key, field_desc, *out_value);
|
||||
return (++iter == tokens.end());
|
||||
}
|
||||
else
|
||||
{
|
||||
// continue iterating
|
||||
const proto::Reflection* mirror = key->GetReflection();
|
||||
key = &mirror->GetMessage(*key, field_desc);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
break;
|
||||
}
|
||||
|
||||
} while(key && iter != end);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
}}}//namespace
|
||||
Executable
+31
@@ -0,0 +1,31 @@
|
||||
#ifndef CONFIGPROPERTYEVALUATOR_H_
|
||||
#define CONFIGPROPERTYEVALUATOR_H_
|
||||
|
||||
#include "lib/utils/bts_no_copy.h"
|
||||
#include "lib/expression/Value.h"
|
||||
#include "lib/expression/IPropertyEvaluator.h"
|
||||
|
||||
namespace bts {
|
||||
namespace expression { class ExpressionEvaluator;}
|
||||
namespace config {
|
||||
namespace internal {
|
||||
|
||||
class ConfigurationState;
|
||||
|
||||
class ConfigPropertyEvaluator : public expression::IPropertyEvaluator
|
||||
{
|
||||
public:
|
||||
ConfigPropertyEvaluator(ConfigurationState& config);
|
||||
~ConfigPropertyEvaluator();
|
||||
|
||||
bool get_value(const std::string& property, expression::Value* out_value) override;
|
||||
|
||||
private:
|
||||
BTS_NO_COPY(ConfigPropertyEvaluator);
|
||||
|
||||
ConfigurationState& _config;
|
||||
std::shared_ptr<expression::ExpressionEvaluator> _rule_engine;
|
||||
};
|
||||
|
||||
}}}//namespace
|
||||
#endif
|
||||
Executable
+294
@@ -0,0 +1,294 @@
|
||||
|
||||
#include "ConfigValueQueue.h"
|
||||
#include "ConfigurationException.h"
|
||||
|
||||
#include "lib/utils/proto_helper.h"
|
||||
#include <google/protobuf/descriptor.h>
|
||||
#include <boost/lexical_cast.hpp>
|
||||
#include "config.h"
|
||||
|
||||
namespace bts {
|
||||
namespace config {
|
||||
namespace internal {
|
||||
|
||||
using namespace ::google::protobuf;
|
||||
using namespace bts::expression;
|
||||
using namespace bts::util::proto;
|
||||
|
||||
ConfigValueQueue::ConfigValueQueue(IPropertyEvaluator& evaluator) :
|
||||
_eval(evaluator),
|
||||
_vals(),
|
||||
_current_file()
|
||||
{
|
||||
}
|
||||
|
||||
ConfigValueQueue::~ConfigValueQueue()
|
||||
{
|
||||
}
|
||||
|
||||
void ConfigValueQueue::clear() {
|
||||
_vals.clear();
|
||||
}
|
||||
|
||||
void ConfigValueQueue::process() {
|
||||
try {
|
||||
process_fields();
|
||||
} catch(...) {
|
||||
clear();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
void ConfigValueQueue::defer_value(proto::Message* msg,
|
||||
const proto::Reflection* reflection,
|
||||
const proto::FieldDescriptor* field,
|
||||
int index, int line, int col,
|
||||
const std::string& source,
|
||||
const std::string& destination,
|
||||
const proto::Message* root) {
|
||||
|
||||
bts_assert(msg);
|
||||
bts_assert(reflection);
|
||||
bts_assert(field);
|
||||
bts_assert(!source.empty());
|
||||
//bts_assert(!destination.empty());
|
||||
//bts_assert_d(root != nullptr);
|
||||
DeferredValue dv = {msg, reflection, field, index, line, col, _current_file, source, destination, root};
|
||||
_vals.push_back(dv);
|
||||
}
|
||||
|
||||
void ConfigValueQueue::process_fields() {
|
||||
std::vector<DeferredValue>::iterator iter = _vals.begin();
|
||||
std::vector<DeferredValue> temp;
|
||||
size_t len;
|
||||
do {
|
||||
temp.clear();
|
||||
len = _vals.size();
|
||||
for (size_t x = 0; x < len; ++x) {
|
||||
DeferredValue& dv = _vals[x];
|
||||
if (can_process(dv.sourceval)) {
|
||||
process_field(dv);
|
||||
} else {
|
||||
temp.push_back(dv);
|
||||
}
|
||||
}
|
||||
_vals = temp;
|
||||
// Continue as long as progress is being made
|
||||
} while(_vals.size() > 0 && _vals.size() < len);
|
||||
|
||||
// Error condition
|
||||
if (!_vals.empty()) {
|
||||
std::ostringstream msg;
|
||||
msg << "Unable to processes config value references. " << _vals.size() << " errors detected.\n\n";
|
||||
for (iter = _vals.begin(); iter != _vals.end(); iter++) {
|
||||
msg << "Cannot write " << iter->sourceval << " due to circular reference. ";
|
||||
msg << iter->filename << ":" << iter->line << "," << iter->col << std::endl;
|
||||
}
|
||||
std::string error = msg.str();
|
||||
throw new RecursiveReferenceException(error.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
bool ConfigValueQueue::can_process(const std::string& source) {
|
||||
// Determine if source has a pending write
|
||||
size_t len = _vals.size();
|
||||
for(size_t x = 0; x < len; ++x) {
|
||||
// If there is a destination assignment underneath the source path
|
||||
// Then we cannot copy the value yet
|
||||
const string& dest = _vals[x].dest_key;
|
||||
if (dest.compare(0, source.size(), source) == 0) {
|
||||
if (dest.size() <= source.size() || dest[source.size()] == '.') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool is_relevant(const proto::Message* message) {
|
||||
if (message) {
|
||||
const proto::Descriptor* desc = message->GetDescriptor();
|
||||
bts_assert_d(desc);
|
||||
const proto::Message& result = config::get_message(desc);
|
||||
return &result == message;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void ConfigValueQueue::process_field(const DeferredValue& dv) {
|
||||
Value val;
|
||||
if (_eval.get_value(dv.sourceval, &val)) {
|
||||
assign_value_to_field(dv.message, dv.reflection, dv.field, val, dv.index);
|
||||
} else {
|
||||
if (is_relevant(dv.root_message)) {
|
||||
std::string message = "Error retrieving value for " + dv.sourceval;
|
||||
throw SelfReferenceException(message.c_str(), dv.filename.c_str(), dv.line, dv.col);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <typename TProto, typename TValue>
|
||||
void ConfigValueQueue::assign(
|
||||
proto::Message* message,
|
||||
const proto::Reflection* reflection,
|
||||
const proto::FieldDescriptor* field,
|
||||
const Value& value, int& index) {
|
||||
if (value.which() == ValueType::list) {
|
||||
vector<Value> v = boost::get<vector<Value> >(value);
|
||||
if (field->is_repeated()) {
|
||||
for (vector<Value>::iterator i = v.begin(); i != v.end(); ++i) {
|
||||
int size = reflection->FieldSize(*message, field);
|
||||
add<TProto>(message, reflection, field, (TProto)boost::get<TValue>(*i));
|
||||
if (index != size) {
|
||||
for (int i = index; i < size; ++i) {
|
||||
reflection->SwapElements(message, field, i, size);
|
||||
}
|
||||
}
|
||||
index++;
|
||||
}
|
||||
bump_indexes(message, field, v.size());
|
||||
}
|
||||
else if (field->type() == proto::FieldDescriptor::Type::TYPE_STRING) {
|
||||
reflection->SetString(message, field, value_to_string(value));
|
||||
}
|
||||
else if (field->type() == proto::FieldDescriptor::Type::TYPE_BOOL) {
|
||||
reflection->SetBool(message, field, value_to_bool(value));
|
||||
}
|
||||
else {
|
||||
string error = "Invalid type conversion in assignment to " + message->GetTypeName() + "." + field->name();
|
||||
throw ConfigurationException(error.c_str());
|
||||
}
|
||||
} else {
|
||||
set_field<TProto>(message, reflection, field, (TProto)boost::get<TValue>(value), index);
|
||||
if (field->is_repeated()) {
|
||||
bump_indexes(message, field, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <typename TProto, typename TValue>
|
||||
void ConfigValueQueue::lexical_assign(
|
||||
proto::Message* message,
|
||||
const proto::Reflection* reflection,
|
||||
const proto::FieldDescriptor* field,
|
||||
const Value& value, int& index) {
|
||||
if (value.which() == ValueType::list) {
|
||||
vector<Value> v = boost::get<vector<Value> >(value);
|
||||
bts_assert(field->is_repeated());
|
||||
for (vector<Value>::iterator i = v.begin(); i != v.end(); ++i) {
|
||||
int size = reflection->FieldSize(*message, field);
|
||||
TProto result = boost::lexical_cast<TProto>(boost::get<TValue>(*i));
|
||||
add<TProto>(message, reflection, field, result);
|
||||
if (index != size) {
|
||||
for (int i = index; i < size; ++i) {
|
||||
reflection->SwapElements(message, field, i, size);
|
||||
}
|
||||
}
|
||||
index++;
|
||||
}
|
||||
bump_indexes(message, field, v.size());
|
||||
} else {
|
||||
TProto result = boost::lexical_cast<TProto>(boost::get<TValue>(value));
|
||||
set_field<TProto>(message, reflection, field, result, index);
|
||||
if (field->is_repeated()) {
|
||||
bump_indexes(message, field, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ConfigValueQueue::assign_value_to_field(proto::Message* message,
|
||||
const proto::Reflection* reflection,
|
||||
const proto::FieldDescriptor* field,
|
||||
const Value& value, int index) throw() {
|
||||
#define MY_ARGS message, reflection, field, value, index
|
||||
|
||||
// Note: ConfigPropertyEvaluator puts every numeric type in as double so the right hand side must be double
|
||||
switch(field->type()) {
|
||||
case FieldDescriptor::TYPE_DOUBLE:
|
||||
assign<double>(MY_ARGS); break;
|
||||
case FieldDescriptor::TYPE_FLOAT:
|
||||
assign<float, double>(MY_ARGS); break;
|
||||
case FieldDescriptor::TYPE_FIXED64:
|
||||
case FieldDescriptor::TYPE_INT64:
|
||||
assign<int64_t, double>(MY_ARGS); break;
|
||||
case FieldDescriptor::TYPE_UINT64:
|
||||
assign<uint64_t, double>(MY_ARGS); break;
|
||||
case FieldDescriptor::TYPE_FIXED32:
|
||||
case FieldDescriptor::TYPE_INT32:
|
||||
if (value.which() == ValueType::string) {
|
||||
lexical_assign<int, string>(MY_ARGS);
|
||||
}
|
||||
else {
|
||||
assign<int, double>(MY_ARGS);
|
||||
}
|
||||
break;
|
||||
case FieldDescriptor::TYPE_UINT32:
|
||||
assign<uint32_t, double>(MY_ARGS); break;
|
||||
case FieldDescriptor::TYPE_BOOL:
|
||||
assign<bool>(MY_ARGS); break;
|
||||
case FieldDescriptor::TYPE_STRING:
|
||||
if (value.which() == ValueType::integer || value.which() == ValueType::real) {
|
||||
lexical_assign<string, double>(MY_ARGS);
|
||||
}
|
||||
else {
|
||||
assign<string>(MY_ARGS);
|
||||
}
|
||||
break;
|
||||
case FieldDescriptor::TYPE_MESSAGE:
|
||||
assign<const Message*, void*>(MY_ARGS); break;
|
||||
case FieldDescriptor::TYPE_ENUM: {
|
||||
if (value.which() == ValueType::list) {
|
||||
vector<Value> v = boost::get<vector<Value> >(value);
|
||||
for (vector<Value>::iterator iter = v.begin(); iter != v.end(); iter++) {
|
||||
int size = reflection->FieldSize(*message, field);
|
||||
const EnumDescriptor* enum_type = field->enum_type();
|
||||
const EnumValueDescriptor* enum_value = enum_type->FindValueByName(boost::get<string>(value));
|
||||
reflection->AddEnum(message, field, enum_value);
|
||||
if (index != size) {
|
||||
for (int i = index; i < size; ++i) {
|
||||
reflection->SwapElements(message, field, i, size);
|
||||
}
|
||||
}
|
||||
index++;
|
||||
}
|
||||
bump_indexes(message, field, v.size());
|
||||
}
|
||||
else {
|
||||
const EnumDescriptor* enum_type = field->enum_type();
|
||||
const EnumValueDescriptor* enum_value = enum_type->FindValueByName(boost::get<string>(value));
|
||||
set_field(message, reflection, field, enum_value, index);
|
||||
if (field->is_repeated()) {
|
||||
bump_indexes(message, field, 1);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case FieldDescriptor::TYPE_SFIXED32:
|
||||
case FieldDescriptor::TYPE_SFIXED64:
|
||||
case FieldDescriptor::TYPE_SINT32:
|
||||
case FieldDescriptor::TYPE_SINT64:
|
||||
case FieldDescriptor::TYPE_BYTES:
|
||||
case FieldDescriptor::TYPE_GROUP:
|
||||
default:
|
||||
bts_assert_msg(false, "Unsupported assignment destination");
|
||||
}
|
||||
|
||||
#undef MY_ARGS
|
||||
}
|
||||
|
||||
void ConfigValueQueue::bump_indexes(proto::Message* message,
|
||||
const proto::FieldDescriptor* field,
|
||||
int count)
|
||||
{
|
||||
std::vector<DeferredValue>::iterator iter = _vals.begin();
|
||||
for (;iter != _vals.end(); iter++) {
|
||||
DeferredValue& dv = *iter;
|
||||
if (dv.message == message && dv.field == field) {
|
||||
dv.index += count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}}}//namespace
|
||||
|
||||
Executable
+101
@@ -0,0 +1,101 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/utils/bts_no_copy.h"
|
||||
#include "lib/expression/Value.h"
|
||||
#include "lib/expression/IPropertyEvaluator.h"
|
||||
#include "text_format/text_format.h"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace bts {
|
||||
namespace config {
|
||||
namespace internal {
|
||||
namespace proto = ::google::protobuf;
|
||||
|
||||
|
||||
#ifdef __GNUC__
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Weffc++"
|
||||
#endif
|
||||
struct DeferredValue {
|
||||
proto::Message* message;
|
||||
const proto::Reflection* reflection;
|
||||
const proto::FieldDescriptor* field;
|
||||
int index;
|
||||
int line;
|
||||
int col;
|
||||
std::string filename;
|
||||
std::string sourceval;
|
||||
std::string dest_key;
|
||||
const proto::Message* root_message;
|
||||
};
|
||||
#ifdef __GNUC__
|
||||
#pragma GCC diagnostic pop
|
||||
#endif
|
||||
|
||||
class ConfigValueQueue : public google::protobuf::IDeferValueLookup
|
||||
{
|
||||
public:
|
||||
ConfigValueQueue(expression::IPropertyEvaluator& evaluator);
|
||||
~ConfigValueQueue();
|
||||
|
||||
// Process the queue of deferred values
|
||||
void process();
|
||||
void clear();
|
||||
|
||||
// Add a lookup value
|
||||
virtual void defer_value(proto::Message*,
|
||||
const proto::Reflection* reflection,
|
||||
const proto::FieldDescriptor* field,
|
||||
int index, int line, int col,
|
||||
const std::string& value,
|
||||
const std::string& key_name, const proto::Message* root) override;
|
||||
|
||||
void set_filename(const std::string& filename) { _current_file = filename; }
|
||||
|
||||
private: // fields
|
||||
expression::IPropertyEvaluator& _eval;
|
||||
std::vector<DeferredValue> _vals;
|
||||
std::string _current_file;
|
||||
BTS_NO_COPY(ConfigValueQueue);
|
||||
|
||||
private: //methods
|
||||
void process_fields();
|
||||
bool can_process(const std::string& key_name);
|
||||
void process_field(const DeferredValue&);
|
||||
|
||||
void assign_value_to_field(proto::Message* message,
|
||||
const proto::Reflection* reflection,
|
||||
const proto::FieldDescriptor* field,
|
||||
const expression::Value& value, int insert_index=0) throw();
|
||||
void bump_indexes(proto::Message* message,
|
||||
const proto::FieldDescriptor* field,
|
||||
int count);
|
||||
|
||||
template <typename TProto, typename TValue>
|
||||
void assign(
|
||||
proto::Message* message,
|
||||
const proto::Reflection* reflection,
|
||||
const proto::FieldDescriptor* field,
|
||||
const expression::Value& value, int& index);
|
||||
|
||||
template <typename TProto, typename TValue>
|
||||
void lexical_assign(
|
||||
proto::Message* message,
|
||||
const proto::Reflection* reflection,
|
||||
const proto::FieldDescriptor* field,
|
||||
const expression::Value& value, int& index);
|
||||
|
||||
template <typename T>
|
||||
void assign(
|
||||
proto::Message* message,
|
||||
const proto::Reflection* reflection,
|
||||
const proto::FieldDescriptor* field,
|
||||
const expression::Value& value, int& index) {
|
||||
assign<T, T>(message, reflection, field, value, index);
|
||||
}
|
||||
};
|
||||
|
||||
}}}//namespace
|
||||
|
||||
Executable
+37
@@ -0,0 +1,37 @@
|
||||
#include "ConfigurationException.h"
|
||||
|
||||
namespace bts {
|
||||
namespace config {
|
||||
|
||||
//
|
||||
// ConfigurationException
|
||||
//
|
||||
ConfigurationException::ConfigurationException(const char* what)
|
||||
: std::logic_error(""), _what(what)
|
||||
{
|
||||
}
|
||||
|
||||
ConfigurationException::ConfigurationException(const std::string& what)
|
||||
: std::logic_error(""), _what(what)
|
||||
{
|
||||
}
|
||||
|
||||
ConfigurationException::ConfigurationException(const ConfigurationException& other)
|
||||
: std::logic_error(""), _what(other._what)
|
||||
{
|
||||
}
|
||||
|
||||
ConfigurationException& ConfigurationException::operator=(const ConfigurationException& other)
|
||||
{
|
||||
_what = other._what;
|
||||
return *this;
|
||||
}
|
||||
|
||||
const char* ConfigurationException::what() const throw()
|
||||
{
|
||||
return _what.c_str();
|
||||
}
|
||||
|
||||
ConfigurationException::~ConfigurationException() throw() {}
|
||||
|
||||
}}//namespace
|
||||
Executable
+75
@@ -0,0 +1,75 @@
|
||||
#ifndef BADCONFIGURATIONEXCEPTION_H_
|
||||
#define BADCONFIGURATIONEXCEPTION_H_
|
||||
|
||||
#include <string>
|
||||
#include <stdexcept>
|
||||
#include <sstream>
|
||||
#include "lib/utils/bts_export.h"
|
||||
|
||||
namespace bts {
|
||||
namespace config {
|
||||
|
||||
class ConfigurationException : public std::logic_error
|
||||
{
|
||||
public:
|
||||
ConfigurationException(const char* what);
|
||||
ConfigurationException(const std::string& what);
|
||||
ConfigurationException(const ConfigurationException& other);
|
||||
ConfigurationException& operator=(const ConfigurationException& other);
|
||||
virtual ~ConfigurationException() throw();
|
||||
|
||||
BTS_EXPORT const char* what() const throw() override;
|
||||
|
||||
protected:
|
||||
std::string _what;
|
||||
};
|
||||
|
||||
class InvalidDescriptorException : public ConfigurationException
|
||||
{
|
||||
public:
|
||||
InvalidDescriptorException(const char* what)
|
||||
: ConfigurationException(what)
|
||||
{
|
||||
_what += " was not compiled in to config.";
|
||||
}
|
||||
};
|
||||
|
||||
class InvalidKeyException : public ConfigurationException
|
||||
{
|
||||
public:
|
||||
InvalidKeyException(const char* what)
|
||||
: ConfigurationException(what)
|
||||
{
|
||||
_what += " is not a valid config type.";
|
||||
}
|
||||
};
|
||||
|
||||
class SelfReferenceException : public ConfigurationException
|
||||
{
|
||||
public:
|
||||
SelfReferenceException(const char* what, const char* file, int line, int col) : ConfigurationException(what) {
|
||||
std::ostringstream out;
|
||||
out << what;
|
||||
out << " Location: " << file << ":" << line << "," << col;
|
||||
_what = out.str();
|
||||
}
|
||||
};
|
||||
|
||||
class RecursiveReferenceException : public ConfigurationException
|
||||
{
|
||||
public:
|
||||
RecursiveReferenceException(const char* what) : ConfigurationException(what) { }
|
||||
};
|
||||
|
||||
class ServerUnreachableException : public ConfigurationException
|
||||
{
|
||||
public:
|
||||
ServerUnreachableException(const char* what) : ConfigurationException(what)
|
||||
{
|
||||
_what = "Unable to reach server ";
|
||||
_what += what;
|
||||
}
|
||||
};
|
||||
|
||||
}}
|
||||
#endif
|
||||
Executable
+944
@@ -0,0 +1,944 @@
|
||||
|
||||
#include "lib/os/os.h"
|
||||
|
||||
#include "ConfigurationState.h"
|
||||
#include "ConfigurationException.h"
|
||||
#include "ConfigPropertyEvaluator.h"
|
||||
#include "ConfigErrorCollector.h"
|
||||
#include "PreprocessInputStream.h"
|
||||
#include "ConfigValueQueue.h"
|
||||
#include "lib/os/os.h"
|
||||
#include "lib/utils/bts_assert.h"
|
||||
#include "lib/utils/is_unittest_environment.h"
|
||||
#include "lib/utils/bts_array_size.h"
|
||||
#include "config.h"
|
||||
|
||||
#include "lib/config/protos/system.pb.h"
|
||||
|
||||
#include <boost/algorithm/string.hpp> // iequals
|
||||
#include <boost/filesystem.hpp>
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include <tuple>
|
||||
|
||||
#define URDL_HEADER_ONLY 1
|
||||
#define URDL_DISALE_SSL 1
|
||||
#include <urdl/url.hpp>
|
||||
|
||||
#ifdef WIN32
|
||||
#include <Winsock2.h>
|
||||
#include <d2d1.h>
|
||||
#else
|
||||
#include <netdb.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <arpa/inet.h>
|
||||
#endif
|
||||
|
||||
#include "lib/config_proto_files.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
namespace bts {
|
||||
namespace config {
|
||||
namespace internal {
|
||||
|
||||
const char* MESSAGE_STRING_RULE = "rule";
|
||||
const char* MESSAGE_STRING_VALUE = "value";
|
||||
const char* MESSAGE_STRING_INCLUDE = "include";
|
||||
const char* MESSAGE_STRING_INCLUDE_BACKUP = "fallback";
|
||||
const char* MESSAGE_STRING_MACRO_TYPE = "MacroType";
|
||||
const char* MESSAGE_STRING_MACRO = "macro";
|
||||
|
||||
const char* CONFIG_SERVER_ENV_VAR = "BTSConfig";
|
||||
|
||||
inline tuple<string,uint32_t> hostname(const std::string& path);
|
||||
|
||||
ConfigurationState::ConfigurationState(void) :
|
||||
_is_initialized(false),
|
||||
_initialization_mutex(),
|
||||
_dynamic_pool(),
|
||||
_prototype_factory(),
|
||||
_prototype(nullptr),
|
||||
_config_chain(),
|
||||
_defaults(),
|
||||
_properties(new ConfigPropertyEvaluator(*this)),
|
||||
_rule_engine(_properties),
|
||||
_macros(),
|
||||
_deferred_queue(new ConfigValueQueue(*_properties.get())),
|
||||
_log(),
|
||||
_host(),
|
||||
_port(80)
|
||||
{
|
||||
}
|
||||
|
||||
ConfigurationState::~ConfigurationState(void)
|
||||
{
|
||||
}
|
||||
|
||||
std::string ConfigurationState::defaults_path()
|
||||
{
|
||||
std::string appdir = os::get_install_path();
|
||||
return appdir + "/defaults/";
|
||||
}
|
||||
|
||||
std::string get_command_argument(const char* key)
|
||||
{
|
||||
std::vector<std::string> cmd_line = os::get_command_line();
|
||||
std::vector<std::string>::iterator begin = cmd_line.begin(), end = cmd_line.end();
|
||||
for (; begin != end; begin++)
|
||||
{
|
||||
if (boost::iequals(*begin, key))
|
||||
{
|
||||
begin++;
|
||||
if (begin == end) {
|
||||
break;
|
||||
}
|
||||
else {
|
||||
os::setenv(CONFIG_SERVER_ENV_VAR, begin->c_str());
|
||||
return *begin;
|
||||
}
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
string ConfigurationState::settings_path()
|
||||
{
|
||||
// Look for the -ConfigServer option on the command line
|
||||
std::string cmd_arg = get_command_argument("-ConfigServer");
|
||||
if (!cmd_arg.empty()) return cmd_arg;
|
||||
|
||||
const char* env_server = getenv(CONFIG_SERVER_ENV_VAR);
|
||||
if (env_server) return env_server;
|
||||
|
||||
std::string path = os::get_install_path() + "/conf/";
|
||||
if (boost::filesystem::exists(path))
|
||||
{
|
||||
return path;
|
||||
}
|
||||
else
|
||||
{
|
||||
path = os::bts_user_path() + "conf/";
|
||||
if (boost::filesystem::exists(path))
|
||||
{
|
||||
return path;
|
||||
}
|
||||
else
|
||||
{
|
||||
path = os::bts_system_path();
|
||||
if (os::is_windows()) path += "conf/";
|
||||
if (boost::filesystem::exists(path))
|
||||
{
|
||||
return path;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Cannot bts_assert during config initialization
|
||||
const char* error_message = "Local configuration path does not exist. This machine is not configured.";
|
||||
std::cout << error_message << std::endl;
|
||||
throw ConfigurationException(error_message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ConfigurationState::initialize_defaults()
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(_initialization_mutex);
|
||||
if (_is_initialized) return;
|
||||
|
||||
generate_all_config_proto();
|
||||
|
||||
std::shared_ptr<proto::Message> new_message(_prototype->New());
|
||||
ErrorsOnlyLog log(_log);
|
||||
load_message(defaults_path(), *new_message.get(), log, *_deferred_queue.get());
|
||||
_defaults = new_message;
|
||||
|
||||
// If defaults has an include process that now
|
||||
// FEATURE: Unlike settings loaded from ~/.bts/ these includes
|
||||
// take precedence over the settings in the file which includes them.
|
||||
// While this seems backwards it is always the behavior you want
|
||||
std::string include = get_include(*_defaults.get());
|
||||
if (!include.empty())
|
||||
{
|
||||
load(include, "");
|
||||
}
|
||||
|
||||
_is_initialized = true;
|
||||
}
|
||||
|
||||
|
||||
std::string get_installation(const std::string& path)
|
||||
{
|
||||
// "Installation" is defined as the directory where we are installed
|
||||
// "bin" is special cased to "" as a backwards compatibility for developers
|
||||
bts_assert(!path.empty());
|
||||
std::string parent_path = boost::filesystem::path(path).parent_path().string();
|
||||
size_t last = parent_path.find_last_of("/\\");
|
||||
if (last + 1 >= parent_path.size())
|
||||
return "";
|
||||
std::string installation = parent_path.substr(last + 1, parent_path.size() - last);
|
||||
if (installation == "bin")
|
||||
return "";
|
||||
return installation;
|
||||
}
|
||||
|
||||
void ConfigurationState::initialize_builtins()
|
||||
{
|
||||
System sys;
|
||||
|
||||
sys.set_host_name(os::host_name());
|
||||
sys.set_process_name(os::get_application_name());
|
||||
sys.set_process_path(os::get_application_path());
|
||||
sys.set_platform(os::platform_name());
|
||||
sys.set_qualifier(os::get_qualifier());
|
||||
sys.set_unittest_environment(utils::internal::is_unittest_environment());
|
||||
sys.set_data_path(os::bts_data_path());
|
||||
sys.set_installation(get_installation(sys.process_path()));
|
||||
sys.set_installation_specific_data_path(sys.data_path() + sys.installation() + "/");
|
||||
// sys.set_build_number(BUILD_NUMBER);
|
||||
sys.set_build_number(0);
|
||||
sys.set_os_user(os::username());
|
||||
#ifdef DEBUG
|
||||
sys.set_build_type("debug");
|
||||
#endif
|
||||
sys.set_config_host(_host);
|
||||
sys.set_config_port(_port);
|
||||
if (!_host.empty()) {
|
||||
hostent* host_entry = gethostbyname(_host.c_str());
|
||||
bts_assert_msg(host_entry != NULL, "Unable to resolve host name " + _host);
|
||||
in_addr* address = (in_addr*) host_entry->h_addr_list[0];
|
||||
string ip_address = inet_ntoa(*address);
|
||||
sys.set_config_ip(ip_address);
|
||||
}
|
||||
#ifdef _WIN32
|
||||
sys.set_is_remote_app(GetSystemMetrics(SM_REMOTESESSION) == 1);
|
||||
|
||||
// Screen dpi, Assumes screen dpi is uniform in x and y
|
||||
// Computes 2 different ratios depending - one will be right depending on whether the process calls SetDPIAware()
|
||||
HDC screen = GetDC(0);
|
||||
int log_pixels_x = GetDeviceCaps(screen, LOGPIXELSX);
|
||||
auto ratio2 = log_pixels_x / 96.0;
|
||||
int virtual_width = GetDeviceCaps(screen, HORZRES);
|
||||
int physical_width = GetDeviceCaps(screen, DESKTOPHORZRES);
|
||||
double ratio = (double)physical_width / (double)virtual_width;
|
||||
sys.set_dpi(log_pixels_x * ratio);
|
||||
sys.set_dpi_ratio(max(ratio, ratio2));
|
||||
ReleaseDC(0, screen);
|
||||
|
||||
#endif
|
||||
|
||||
std::vector<std::string> args = os::get_command_line();
|
||||
for (std::vector<std::string>::iterator iter = args.begin(); iter != args.end(); iter++)
|
||||
{
|
||||
sys.add_cmd_args(*iter);
|
||||
}
|
||||
|
||||
// Version string
|
||||
std::string install_path = os::get_install_path();
|
||||
std::string app_version_file = install_path + "/edge.version";
|
||||
if (!boost::filesystem::exists(app_version_file))
|
||||
{
|
||||
app_version_file = install_path + "/blue2.version";
|
||||
}
|
||||
if (boost::filesystem::exists(app_version_file))
|
||||
{
|
||||
std::ifstream input(app_version_file.c_str(), std::ifstream::in);
|
||||
if (!input.fail())
|
||||
{
|
||||
// Read the last line of the file
|
||||
std::string version;
|
||||
while(!input.eof())
|
||||
{
|
||||
std::string temp;
|
||||
std::getline(input, temp);
|
||||
if (!temp.empty()) version = temp;
|
||||
}
|
||||
|
||||
sys.set_version(version);
|
||||
input.close();
|
||||
}
|
||||
}
|
||||
|
||||
sys.set_num_cores(os::num_cores());
|
||||
|
||||
//
|
||||
// Add the System value to the defaults
|
||||
const proto::FieldDescriptor* field_desc = _defaults->GetDescriptor()->FindFieldByName("System");
|
||||
const proto::Descriptor* message_desc = field_desc->message_type();
|
||||
|
||||
// Create a meta message
|
||||
proto::Message* new_message = _defaults->GetReflection()->AddMessage(_defaults.get(), field_desc);
|
||||
const proto::FieldDescriptor* value_desc = message_desc->FindFieldByName("value");
|
||||
new_message->GetReflection()->MutableMessage(new_message, value_desc)->CopyFrom(sys);
|
||||
|
||||
initialize_introspection();
|
||||
}
|
||||
|
||||
void ConfigurationState::initialize_introspection() {
|
||||
// With this config can be self describing enough
|
||||
// that another language can request "all" of config
|
||||
ConfigIntrospection ci;
|
||||
proto::DescriptorPool::generated_pool();
|
||||
for (size_t x = 0; x < BTS_ARRAYSIZE(config_proto_files); x++) {
|
||||
std::string proto_path = "core/bts_core/config/";
|
||||
proto_path += config_proto_files[x];
|
||||
const proto::FileDescriptor* file_desc = proto::DescriptorPool::generated_pool()->FindFileByName(proto_path);
|
||||
if (file_desc != nullptr) {
|
||||
ConfigIntrospection::ConfigProto* config_proto = ci.add_config();
|
||||
bts_assert(config_proto);
|
||||
config_proto->set_name(file_desc->name());
|
||||
for (int y=0; y < file_desc->message_type_count(); y++) {
|
||||
const proto::Descriptor* message_desc = file_desc->message_type(y);
|
||||
if (message_desc != nullptr) {
|
||||
config_proto->add_type(message_desc->full_name());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Add to defaults
|
||||
const proto::FieldDescriptor* field_desc = _defaults->GetDescriptor()->FindFieldByName("ConfigIntrospection");
|
||||
const proto::Descriptor* message_desc = field_desc->message_type();
|
||||
proto::Message* new_message = _defaults->GetReflection()->AddMessage(_defaults.get(), field_desc);
|
||||
const proto::FieldDescriptor* value_desc = message_desc->FindFieldByName("value");
|
||||
new_message->GetReflection()->MutableMessage(new_message, value_desc)->CopyFrom(ci);
|
||||
}
|
||||
|
||||
void ConfigurationState::initialize_macros()
|
||||
{
|
||||
std::vector<std::shared_ptr<proto::Message> > :: iterator iter;
|
||||
for (iter = _config_chain.begin(); iter != _config_chain.end(); ++iter)
|
||||
{
|
||||
const proto::Message* message = (*iter).get();
|
||||
add_macro(message);
|
||||
}
|
||||
add_macro(_defaults.get());
|
||||
}
|
||||
|
||||
void ConfigurationState::add_macro(const proto::Message* message)
|
||||
{
|
||||
bts_assert(message);
|
||||
const proto::FieldDescriptor* field_desc = message->GetDescriptor()->FindFieldByName(MESSAGE_STRING_MACRO);
|
||||
if (field_desc)
|
||||
{
|
||||
int size = message->GetReflection()->FieldSize(*message, field_desc);
|
||||
for (int index = 0; index < size; index++)
|
||||
{
|
||||
// read "name" and "expression" fields
|
||||
const proto::Message& meta_message = message->GetReflection()->GetRepeatedMessage(*message, field_desc, index);
|
||||
const proto::FieldDescriptor* name_desc = meta_message.GetDescriptor()->FindFieldByName("name");
|
||||
const std::string name = '$' + meta_message.GetReflection()->GetString(meta_message, name_desc);
|
||||
|
||||
const proto::FieldDescriptor* exp_desc = meta_message.GetDescriptor()->FindFieldByName("expression");
|
||||
const std::string expression = meta_message.GetReflection()->GetString(meta_message, exp_desc);
|
||||
|
||||
if (_macros.find(name) == _macros.end())
|
||||
{
|
||||
// eval expression to Value
|
||||
//expression::Value result = _rule_engine.eval_to_value(expression);
|
||||
_macros[name] = expression;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expression::Value ConfigurationState::get_macro(const std::string& name)
|
||||
{
|
||||
map<string, string>::iterator iter = _macros.find(name);
|
||||
if (iter == _macros.end()) {
|
||||
std::string error = std::string("Macro '") + name + "' is undefined";
|
||||
throw ConfigurationException(error);
|
||||
}
|
||||
return _rule_engine.eval_to_value(iter->second);
|
||||
}
|
||||
|
||||
std::string ConfigurationState::get_macro_string(const std::string& name) {
|
||||
try {
|
||||
expression::Value result = get_macro(name);
|
||||
return expression::value_to_string(result);
|
||||
}
|
||||
catch (const ConfigurationException& e) { return e.what(); }
|
||||
}
|
||||
|
||||
void check_rule(proto::Message* message, expression::ExpressionEvaluator& rule_engine) {
|
||||
const proto::Reflection* reflection = message->GetReflection();
|
||||
const proto::Descriptor* descriptor = message->GetDescriptor();
|
||||
for (int findex = 0; findex < descriptor->field_count(); ++findex) {
|
||||
const proto::FieldDescriptor* field = descriptor->field(findex);
|
||||
if (field->is_repeated()) {
|
||||
int field_size = reflection->FieldSize(*message, field);
|
||||
for (int index = 0; index < field_size; ++index) {
|
||||
const proto::Message& field_message = reflection->GetRepeatedMessage(*message, field, index);
|
||||
const proto::FieldDescriptor* rule_descriptor = field_message.GetDescriptor()->FindFieldByName(MESSAGE_STRING_RULE);
|
||||
if (rule_descriptor) { // Macros don't have rules
|
||||
const std::string rule = field_message.GetReflection()->GetString(field_message, rule_descriptor);
|
||||
rule_engine.eval(rule);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ConfigurationState::check_rules() {
|
||||
initialize();
|
||||
std::vector<std::shared_ptr<proto::Message> > :: iterator iter;
|
||||
for (iter = _config_chain.begin(); iter != _config_chain.end(); ++iter)
|
||||
{
|
||||
proto::Message* message = (*iter).get();
|
||||
check_rule(message, _rule_engine);
|
||||
}
|
||||
check_rule(_defaults.get(), _rule_engine);
|
||||
}
|
||||
|
||||
void ConfigurationState::initialize_settings()
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(_initialization_mutex);
|
||||
if (_is_initialized) return;
|
||||
|
||||
initialize_defaults();
|
||||
|
||||
std::string settings = settings_path();
|
||||
std::string fallback = get_command_argument("-ConfigFallback");
|
||||
load(settings, fallback);
|
||||
|
||||
initialize_builtins();
|
||||
initialize_macros();
|
||||
_deferred_queue->process();
|
||||
}
|
||||
|
||||
void ConfigurationState::reset()
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(_initialization_mutex);
|
||||
|
||||
_config_chain.clear();
|
||||
_prototype = nullptr;
|
||||
_defaults.reset();
|
||||
_prototype_factory.reset();
|
||||
_dynamic_pool.reset();
|
||||
_macros.clear();
|
||||
_deferred_queue->clear();
|
||||
_is_initialized = false;
|
||||
_host.clear();
|
||||
_port = 80;
|
||||
set_print_errors(true);
|
||||
}
|
||||
|
||||
int ConfigurationState::load(const std::string& url, const std::string& fallback_url)
|
||||
{
|
||||
std::shared_ptr<proto::Message> new_message(_prototype->New());
|
||||
|
||||
bool loaded = false;
|
||||
try {
|
||||
loaded = load_message(url, *new_message.get(), _log, *_deferred_queue.get());
|
||||
}
|
||||
catch(ServerUnreachableException&) {
|
||||
if (fallback_url.empty()) {
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
if (!loaded && !fallback_url.empty())
|
||||
{
|
||||
std::string message = "Failed to load: " + url + " using fallback.";
|
||||
_log.warning(message);
|
||||
loaded = load_message(fallback_url, *new_message.get(), _log, *_deferred_queue.get());
|
||||
if (_host.empty() || _host == "localhost") { tie(_host, _port) = hostname(fallback_url); }
|
||||
}
|
||||
if (!loaded) return 0;
|
||||
|
||||
if (_host.empty() || _host == "localhost") { tie(_host, _port) = hostname(url); }
|
||||
|
||||
std::string include = get_include(*new_message.get());
|
||||
std::string fallback = get_fallback(*new_message.get());
|
||||
|
||||
// insert at front?
|
||||
_config_chain.push_back(new_message);
|
||||
|
||||
// Recursively load includes
|
||||
if (!include.empty())
|
||||
{
|
||||
return 1 + load(include, fallback);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
int ConfigurationState::load_string(const std::string& values)
|
||||
{
|
||||
initialize_defaults();
|
||||
|
||||
std::shared_ptr<proto::Message> new_message(_prototype->New());
|
||||
|
||||
proto::io::ArrayInputStream input_stream(values.c_str(), (int)values.length());
|
||||
parse_stream("test string", input_stream, *new_message.get(), _log, *_deferred_queue.get());
|
||||
|
||||
std::string include = get_include(*new_message.get());
|
||||
std::string fallback = get_fallback(*new_message.get());
|
||||
|
||||
_config_chain.push_back(new_message);
|
||||
|
||||
int count = 0;
|
||||
if (!include.empty())
|
||||
{
|
||||
count += load(include, fallback);
|
||||
}
|
||||
|
||||
if (_host.empty()) {
|
||||
_host = "localhost";
|
||||
}
|
||||
|
||||
initialize_builtins();
|
||||
initialize_macros();
|
||||
_deferred_queue->process();
|
||||
return 1 + count;
|
||||
}
|
||||
|
||||
void ConfigurationState::add_metadata_field(proto::FileDescriptorProto* file_dp, proto::DescriptorProto* message_dp, const proto::Descriptor* base_field, int index)
|
||||
{
|
||||
// Create the metadata message
|
||||
proto::DescriptorProto* meta_message = file_dp->add_message_type();
|
||||
std::string meta_name = base_field->name() + "meta";
|
||||
meta_message->set_name(meta_name);
|
||||
|
||||
// Add 'rule'
|
||||
proto::FieldDescriptorProto* rule_field = meta_message->add_field();
|
||||
rule_field->set_name(MESSAGE_STRING_RULE);
|
||||
rule_field->set_number(1);
|
||||
rule_field->set_type(proto::FieldDescriptorProto_Type_TYPE_STRING);
|
||||
rule_field->set_label(proto::FieldDescriptorProto_Label_LABEL_OPTIONAL);
|
||||
rule_field->set_default_value("true");
|
||||
|
||||
// Add 'value'
|
||||
proto::FieldDescriptorProto* value_field = meta_message->add_field();
|
||||
value_field->set_name(MESSAGE_STRING_VALUE);
|
||||
value_field->set_number(2);
|
||||
value_field->set_type_name(base_field->full_name());
|
||||
value_field->set_label(proto::FieldDescriptorProto_Label_LABEL_REQUIRED);
|
||||
|
||||
// Now add a field to message_dp of that type
|
||||
proto::FieldDescriptorProto* field_desc = message_dp->add_field();
|
||||
field_desc->set_name(base_field->name());
|
||||
field_desc->set_number(index);
|
||||
field_desc->set_type_name(meta_name);
|
||||
field_desc->set_label(proto::FieldDescriptorProto_Label_LABEL_REPEATED);
|
||||
}
|
||||
|
||||
// Construct a new Message that describes the save file format
|
||||
// This can then be used with google::protobuf::TextFormat to load and save files
|
||||
void ConfigurationState::generate_all_config_proto()
|
||||
{
|
||||
const char* bts_config_classname = "__BTSConfig";
|
||||
int field_number = 0;
|
||||
|
||||
proto::FileDescriptorProto bts_config_dp;
|
||||
bts_config_dp.set_name("config.proto");
|
||||
proto::DescriptorProto* config_message = bts_config_dp.add_message_type();
|
||||
config_message->set_name(bts_config_classname);
|
||||
|
||||
// Add the 'include' field
|
||||
proto::FieldDescriptorProto* include_field = config_message->add_field();
|
||||
include_field->set_name(MESSAGE_STRING_INCLUDE);
|
||||
include_field->set_number(++field_number);
|
||||
include_field->set_type(proto::FieldDescriptorProto_Type_TYPE_STRING);
|
||||
include_field->set_label(proto::FieldDescriptorProto_Label_LABEL_OPTIONAL);
|
||||
|
||||
// Add the 'fallback' field
|
||||
proto::FieldDescriptorProto* backup_field = config_message->add_field();
|
||||
backup_field->set_name(MESSAGE_STRING_INCLUDE_BACKUP);
|
||||
backup_field->set_number(++field_number);
|
||||
backup_field->set_type(proto::FieldDescriptorProto_Type_TYPE_STRING);
|
||||
backup_field->set_label(proto::FieldDescriptorProto_Label_LABEL_OPTIONAL);
|
||||
|
||||
// Add 'macro' message type
|
||||
proto::DescriptorProto* macro_message = bts_config_dp.add_message_type();
|
||||
macro_message->set_name(MESSAGE_STRING_MACRO_TYPE);
|
||||
proto::FieldDescriptorProto* name_field = macro_message->add_field();
|
||||
name_field->set_name("name");
|
||||
name_field->set_number(1);
|
||||
name_field->set_type(proto::FieldDescriptorProto_Type_TYPE_STRING);
|
||||
name_field->set_label(proto::FieldDescriptorProto_Label_LABEL_REQUIRED);
|
||||
proto::FieldDescriptorProto* expression_field = macro_message->add_field();
|
||||
expression_field->set_name("expression");
|
||||
expression_field->set_number(2);
|
||||
expression_field->set_type(proto::FieldDescriptorProto_Type_TYPE_STRING);
|
||||
expression_field->set_label(proto::FieldDescriptorProto_Label_LABEL_REQUIRED);
|
||||
|
||||
// add 'macro' message field
|
||||
proto::FieldDescriptorProto* macro_field = config_message->add_field();
|
||||
macro_field->set_name(MESSAGE_STRING_MACRO);
|
||||
macro_field->set_number(++field_number);
|
||||
macro_field->set_type(proto::FieldDescriptorProto_Type_TYPE_MESSAGE);
|
||||
macro_field->set_type_name(MESSAGE_STRING_MACRO_TYPE);
|
||||
macro_field->set_label(proto::FieldDescriptorProto_Label_LABEL_REPEATED);
|
||||
|
||||
// add a meta type and field for each generated message
|
||||
proto::DescriptorPool::generated_pool();
|
||||
for (size_t x = 0; x < BTS_ARRAYSIZE(config_proto_files); x++)
|
||||
{
|
||||
std::string proto_path = "config/protos/";
|
||||
proto_path += config_proto_files[x];
|
||||
const proto::FileDescriptor* file_desc = proto::DescriptorPool::generated_pool()->FindFileByName(proto_path);
|
||||
if (file_desc != nullptr)
|
||||
{
|
||||
bts_config_dp.add_dependency(file_desc->name());
|
||||
for (int y=0; y < file_desc->message_type_count(); y++)
|
||||
{
|
||||
const proto::Descriptor* message_desc = file_desc->message_type(y);
|
||||
add_metadata_field(&bts_config_dp, config_message, message_desc, ++field_number);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
throw InvalidDescriptorException(config_proto_files[x]);
|
||||
}
|
||||
}
|
||||
|
||||
// Generate a proper FileDesctiptor from the FileDescriptorProto
|
||||
// The newly created descriptors live in the pool
|
||||
_dynamic_pool.reset(new proto::DescriptorPool(proto::DescriptorPool::generated_pool()));
|
||||
ConfigErrorCollector errors(_log, "");
|
||||
const proto::FileDescriptor* file_desc = _dynamic_pool->BuildFileCollectingErrors(bts_config_dp, &errors);
|
||||
if (!file_desc) {
|
||||
std::string error_message = errors.ToString();
|
||||
if (!error_message.empty()) {
|
||||
bts_assert_msg(file_desc, error_message);
|
||||
} else {
|
||||
bts_assert_msg(false, "Config: error building parser message. No errors logged by protobuf library.\n This could mean you have defined 2 config keys with the same name. Unfortunately that's all I know.");
|
||||
}
|
||||
}
|
||||
const proto::Descriptor* bts_config_desc = file_desc->FindMessageTypeByName(bts_config_classname);
|
||||
|
||||
_prototype_factory.reset(new proto::DynamicMessageFactory());
|
||||
_prototype_factory->SetDelegateToGeneratedFactory(true);
|
||||
_prototype = _prototype_factory->GetPrototype(bts_config_desc);
|
||||
}
|
||||
|
||||
bool is_valid_key_descriptor(const proto::Descriptor* property_desc)
|
||||
{
|
||||
std::string file_name = property_desc->file()->name();
|
||||
size_t file_name_start = file_name.find_last_of('/') + 1;
|
||||
file_name = file_name.substr(file_name_start);
|
||||
for (size_t x = 0; x < BTS_ARRAYSIZE(config_proto_files); x++)
|
||||
{
|
||||
std::string proto_name = config_proto_files[x];
|
||||
if (boost::iequals(file_name, proto_name))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const proto::Message* ConfigurationState::try_get_message(const std::string& property_name)
|
||||
{
|
||||
initialize_settings();
|
||||
|
||||
const proto::Message* message;
|
||||
|
||||
// Iterate through the loaded files
|
||||
|
||||
std::vector<std::shared_ptr<proto::Message> > :: iterator iter;
|
||||
for (iter = _config_chain.begin(); iter != _config_chain.end(); ++iter)
|
||||
{
|
||||
message = try_get_value(property_name, **iter);
|
||||
if (message)
|
||||
{
|
||||
return message;
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to defaults
|
||||
message = try_get_value(property_name, *_defaults.get());
|
||||
if (message)
|
||||
{
|
||||
return message;
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const proto::Message& ConfigurationState::get_message(const proto::Descriptor* property_desc)
|
||||
{
|
||||
if (!is_valid_key_descriptor(property_desc))
|
||||
{
|
||||
throw InvalidKeyException(property_desc->name().c_str());
|
||||
}
|
||||
|
||||
const proto::Message* message = try_get_message(property_desc->name());
|
||||
if (!message)
|
||||
{
|
||||
// Get the message prototype - will only have compiled in defaults
|
||||
message = proto::MessageFactory::generated_factory()->GetPrototype(property_desc);
|
||||
}
|
||||
|
||||
return *message;
|
||||
}
|
||||
|
||||
const proto::Message* ConfigurationState::try_get_value(const std::string& field_name, const proto::Message& message) const
|
||||
{
|
||||
// 1) Get the metadata descriptor
|
||||
const proto::Descriptor* message_desc = message.GetDescriptor();
|
||||
const proto::FieldDescriptor* meta_desc = message_desc->FindFieldByName(field_name);
|
||||
if (meta_desc)
|
||||
{
|
||||
// 2) Get the repeated metadata
|
||||
int meta_size = message.GetReflection()->FieldSize(message, meta_desc);
|
||||
for (int index = 0; index < meta_size; index++)
|
||||
{
|
||||
// 3) Iterate over repeated field and check rule
|
||||
const proto::Message& meta_message = message.GetReflection()->GetRepeatedMessage(message, meta_desc, index);
|
||||
const proto::FieldDescriptor* rule_desc = meta_message.GetDescriptor()->FindFieldByName(MESSAGE_STRING_RULE);
|
||||
const std::string rule = meta_message.GetReflection()->GetString(meta_message, rule_desc);
|
||||
|
||||
if (_rule_engine.eval(rule))
|
||||
{
|
||||
// 4) return value
|
||||
const proto::FieldDescriptor* value_desc = meta_message.GetDescriptor()->FindFieldByName(MESSAGE_STRING_VALUE);
|
||||
const proto::Message& message_value = meta_message.GetReflection()->GetMessage(meta_message, value_desc, proto::MessageFactory::generated_factory());
|
||||
return &message_value;
|
||||
}
|
||||
else
|
||||
{
|
||||
// TODO: Consider a rule result cache
|
||||
// pro: faster lookups after first parse
|
||||
// con: right now config is read only and perfectly parallel after load
|
||||
}
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const google::protobuf::Descriptor* ConfigurationState::get_descriptor_by_name(const std::string& name) {
|
||||
const proto::Message* pmsg = _defaults.get();
|
||||
if (pmsg) {
|
||||
// Get the metadata descriptor (Meta = rule+value fields)
|
||||
const proto::Descriptor* desc = pmsg->GetDescriptor();
|
||||
const proto::FieldDescriptor* meta_desc = desc->FindFieldByName(name);
|
||||
if (meta_desc) {
|
||||
// Find the "value" field descriptor
|
||||
const proto::Descriptor* pmsg_desc = meta_desc->message_type();
|
||||
const proto::FieldDescriptor* value_desc = pmsg_desc->FindFieldByName(MESSAGE_STRING_VALUE);
|
||||
if (value_desc) {
|
||||
// return it's type
|
||||
return value_desc->message_type();
|
||||
}
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
PathType::type get_path_type(std::string path)
|
||||
{
|
||||
if (path.find("://") != std::string::npos)
|
||||
{
|
||||
return PathType::directory;
|
||||
//const char last_char = path.at(path.length()-1);
|
||||
//return last_char == '/' ? PathType::directory : PathType::file;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (boost::filesystem::is_directory(path))
|
||||
{
|
||||
return PathType::directory;
|
||||
}
|
||||
else if (boost::filesystem::exists(path))
|
||||
{
|
||||
return PathType::file;
|
||||
}
|
||||
else
|
||||
{
|
||||
return PathType::not_found;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
urdl::url url_from_string(std::string& path, bool required)
|
||||
{
|
||||
boost::system::error_code ec;
|
||||
// attempt to parse the path as a URL - if that fails assume it is an absolute file path and append file:///
|
||||
urdl::url url = urdl::url::from_string(path, ec);
|
||||
if (ec)
|
||||
{
|
||||
std::string file_prefix = "file:///";
|
||||
std::string abs_path = boost::filesystem::absolute(path).string();
|
||||
url = urdl::url::from_string(file_prefix + os::normalize_path(abs_path), ec);
|
||||
}
|
||||
bts_assert_msg(!required || !ec, ec.message().c_str());
|
||||
|
||||
return url;
|
||||
}
|
||||
|
||||
inline tuple<string,uint32_t> hostname(const std::string& path) {
|
||||
boost::system::error_code ec;
|
||||
string host;
|
||||
uint32_t port = 80;
|
||||
// Try to parse a url with urdl
|
||||
urdl::url url = urdl::url::from_string(path, ec);
|
||||
if (!ec) {
|
||||
host = url.host();
|
||||
port = url.port();
|
||||
} else {
|
||||
// Check for a UNC path
|
||||
string norm_path = path;
|
||||
os::normalize_path(norm_path);
|
||||
if (norm_path[0] == '/' && norm_path[1] == '/') {
|
||||
size_t host_len = norm_path.find_first_of('/', 2) - 2;
|
||||
if (host_len > 0) {
|
||||
host = norm_path.substr(2, host_len);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we are still empty return "localhost"
|
||||
if (host.empty()) host = "localhost";
|
||||
|
||||
return std::make_tuple(host, port);
|
||||
}
|
||||
|
||||
// Loads a single message file or directory
|
||||
bool load_message(std::string url, proto::Message& out_message, IConfigLog& log, ConfigValueQueue& lookup)
|
||||
{
|
||||
ConfigDownloader downloader;
|
||||
|
||||
bool result = false;
|
||||
switch(get_path_type(url))
|
||||
{
|
||||
case PathType::directory:
|
||||
result = load_directory(url, downloader, out_message, log, lookup) > 0;
|
||||
break;
|
||||
case PathType::file:
|
||||
result = load_file(url, downloader, out_message, log, lookup) == ConfigDownloader::SUCCESS;
|
||||
break;
|
||||
default:
|
||||
std::ostringstream error;
|
||||
error << "Error '" << url << "' is not a valid configuration path";
|
||||
std::string err_str = error.str();
|
||||
log.error(err_str);
|
||||
throw ConfigurationException(err_str.c_str());
|
||||
break;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
int load_directory(std::string url, ConfigDownloader& downloader, proto::Message& out_message, IConfigLog& log, ConfigValueQueue& lookup)
|
||||
{
|
||||
LogAggregator aggregate_log(log);
|
||||
aggregate_log.info("URL: " + url);
|
||||
|
||||
const char last_char = url.at(url.length()-1);
|
||||
if (last_char != '/') {
|
||||
url = url + '/';
|
||||
}
|
||||
|
||||
// If a file called "all" exists in the config directory we can short circuit ~60 http requests
|
||||
ConfigDownloader::Result all_result = load_file(url + ".all", downloader, out_message, aggregate_log, lookup, false);
|
||||
if (all_result == ConfigDownloader::SUCCESS) {
|
||||
log.info(aggregate_log.text());
|
||||
return 1;
|
||||
}
|
||||
|
||||
// load edge.conf
|
||||
int load_count = 0;
|
||||
ConfigDownloader::Result result = load_file(url + "edge.conf", downloader, out_message, aggregate_log, lookup, false);
|
||||
if (result == ConfigDownloader::SUCCESS)
|
||||
{
|
||||
load_count++;
|
||||
}
|
||||
else if (result == ConfigDownloader::PERMANENT_FAILURE) {
|
||||
// If the server is down it doesn't make sense to suffer though the timeouts for the other files
|
||||
throw ServerUnreachableException(url.c_str());
|
||||
}
|
||||
|
||||
bool edge_has_include = !get_include(out_message).empty();
|
||||
|
||||
for(const char* proto_file: config_proto_files)
|
||||
{
|
||||
std::string config_file(proto_file);
|
||||
if (config_file == "system.proto") continue;
|
||||
if (config_file == "edge.proto") continue;
|
||||
|
||||
const char proto_ext[] = ".proto";
|
||||
const char conf_ext[] = ".conf";
|
||||
size_t extension_pos = config_file.rfind(proto_ext);
|
||||
// path_to_config_proto/foo.proto => foo.conf
|
||||
config_file.replace(extension_pos, sizeof(proto_ext), conf_ext, sizeof(conf_ext));
|
||||
boost::filesystem::path p (config_file);
|
||||
config_file = p.filename ().string ();
|
||||
if (load_file(url + config_file, downloader, out_message, aggregate_log, lookup, false))
|
||||
{
|
||||
load_count++;
|
||||
if (!edge_has_include) {
|
||||
bts_assert_msg(get_include(out_message).empty(), "Includes may only be specified in edge.conf");
|
||||
}
|
||||
|
||||
// NOTE: This code allows any config key to go in any .conf file
|
||||
// If this becomse a problem we could iterate over the loaded messages
|
||||
// and ensure they came from the correct location.
|
||||
}
|
||||
}
|
||||
|
||||
log.info(aggregate_log.text());
|
||||
|
||||
return load_count;
|
||||
}
|
||||
|
||||
ConfigDownloader::Result load_file(std::string path, ConfigDownloader& downloader, proto::Message& out_message, IConfigLog& log, ConfigValueQueue& lookup, bool required)
|
||||
{
|
||||
stringstream url_stream;
|
||||
string url = url_from_string(path, required).to_string();
|
||||
ConfigDownloader::Result result = downloader.get(url, url_stream);
|
||||
if (!(result == ConfigDownloader::SUCCESS)) {
|
||||
bts_assert_msg(!required || url_stream, (path + " not found.").c_str());
|
||||
return result;
|
||||
}
|
||||
|
||||
log.info("Loaded: " + path);
|
||||
|
||||
proto::io::IstreamInputStream proto_stream(&url_stream);
|
||||
parse_stream(path, proto_stream, out_message, log, lookup);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void parse_stream(const std::string& file, proto::io::ZeroCopyInputStream& input_stream, proto::Message& out_message, IConfigLog& log, ConfigValueQueue& lookup)
|
||||
{
|
||||
ConfigErrorCollector error_collector(log, file.c_str());
|
||||
bts::google::protobuf::TextFormat::Parser parser;
|
||||
parser.RecordErrorsTo(&error_collector);
|
||||
parser.SetValueLookup(&lookup);
|
||||
lookup.set_filename(file);
|
||||
parser.AllowPartialMessage(true);
|
||||
bool success = parser.Parse(&input_stream, &out_message);
|
||||
if (!success)
|
||||
{
|
||||
std::string error_message = error_collector.ToString();
|
||||
log.error(error_message);
|
||||
throw ConfigurationException(error_message);
|
||||
}
|
||||
}
|
||||
|
||||
std::string get_field(const proto::Message& message, const char* name)
|
||||
{
|
||||
const proto::Descriptor* message_descriptor = message.GetDescriptor();
|
||||
const proto::FieldDescriptor* include_field = message_descriptor->FindFieldByName(name);
|
||||
const std::string include = message.GetReflection()->GetString(message, include_field);
|
||||
|
||||
return include;
|
||||
}
|
||||
|
||||
std::string get_include(const proto::Message& message)
|
||||
{
|
||||
return get_field(message, MESSAGE_STRING_INCLUDE);
|
||||
}
|
||||
|
||||
std::string get_fallback(const proto::Message& message)
|
||||
{
|
||||
return get_field(message, MESSAGE_STRING_INCLUDE_BACKUP);
|
||||
}
|
||||
|
||||
}}}//end namespaces
|
||||
Executable
+123
@@ -0,0 +1,123 @@
|
||||
#ifndef CONFIGURATIONSTATE_H_
|
||||
#define CONFIGURATIONSTATE_H_
|
||||
|
||||
#include "ConfigurationException.h"
|
||||
#include "ConfigLog.h"
|
||||
#include "lib/expression/ExpressionEvaluator.h"
|
||||
#include "lib/expression/Value.h"
|
||||
#include "ConfigDownloader.h"
|
||||
|
||||
#include <google/protobuf/descriptor.h>
|
||||
#include "text_format/text_format.h"
|
||||
#include <google/protobuf/dynamic_message.h>
|
||||
#include <google/protobuf/descriptor.pb.h>
|
||||
#include <google/protobuf/io/zero_copy_stream_impl.h>
|
||||
|
||||
#include <boost/utility.hpp>
|
||||
#include <boost/scoped_ptr.hpp>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
class Message;
|
||||
class DescriptorPool;
|
||||
class DynamicMessageFactory;
|
||||
class Descriptor;
|
||||
class FileDescriptorProto;
|
||||
class DescriptorProto;
|
||||
}
|
||||
}
|
||||
|
||||
namespace bts {
|
||||
namespace config {
|
||||
class System;
|
||||
}}
|
||||
|
||||
namespace proto = google::protobuf;
|
||||
|
||||
namespace bts {
|
||||
namespace config {
|
||||
namespace internal {
|
||||
|
||||
class ConfigPropertyEvaluator;
|
||||
class ConfigValueQueue;
|
||||
|
||||
class ConfigurationState
|
||||
{
|
||||
public:
|
||||
ConfigurationState(void);
|
||||
~ConfigurationState(void);
|
||||
|
||||
void initialize_defaults();
|
||||
void initialize_settings();
|
||||
|
||||
int load(const std::string& url, const std::string& fallback);
|
||||
int load_string(const std::string& values);
|
||||
void reset();
|
||||
|
||||
const proto::Message& get_message(const proto::Descriptor* property_desc);
|
||||
const proto::Message* try_get_message(const std::string& property_name);
|
||||
|
||||
bool is_initialized() { return _is_initialized; }
|
||||
|
||||
bool print_errors() { return _log.print_errors(); }
|
||||
void set_print_errors(bool value) { _log.set_print_errors(value); }
|
||||
expression::Value get_macro(const std::string& name);
|
||||
std::string get_macro_string(const std::string& name);
|
||||
|
||||
void check_rules();
|
||||
|
||||
const google::protobuf::Descriptor* get_descriptor_by_name(const std::string& name);
|
||||
|
||||
private:
|
||||
BTS_NO_COPY(ConfigurationState);
|
||||
|
||||
void initialize_builtins();
|
||||
void initialize_introspection();
|
||||
void initialize_macros();
|
||||
void add_macro(const proto::Message*);
|
||||
void add_metadata_field(proto::FileDescriptorProto* file_dp, proto::DescriptorProto* message_dp, const proto::Descriptor* base_field, int index);
|
||||
void generate_all_config_proto();
|
||||
const proto::Message* try_get_value(const std::string& field_name, const proto::Message& message) const;
|
||||
|
||||
std::string defaults_path();
|
||||
std::string settings_path();
|
||||
|
||||
bool _is_initialized;
|
||||
std::recursive_mutex _initialization_mutex;
|
||||
|
||||
boost::scoped_ptr<proto::DescriptorPool> _dynamic_pool;
|
||||
boost::scoped_ptr<proto::DynamicMessageFactory> _prototype_factory;
|
||||
const proto::Message* _prototype; // owned by prototype_factory
|
||||
std::vector<std::shared_ptr<proto::Message> > _config_chain;
|
||||
std::shared_ptr<proto::Message> _defaults;
|
||||
|
||||
std::shared_ptr<ConfigPropertyEvaluator> _properties;
|
||||
expression::ExpressionEvaluator _rule_engine;
|
||||
std::map<std::string, std::string> _macros;
|
||||
std::shared_ptr<ConfigValueQueue> _deferred_queue;
|
||||
|
||||
ConfigLog _log;
|
||||
std::string _host;
|
||||
uint32_t _port;
|
||||
};
|
||||
|
||||
std::string get_include(const proto::Message& messages);
|
||||
std::string get_fallback(const proto::Message& message);
|
||||
|
||||
struct PathType {
|
||||
enum type { not_found, file, directory };
|
||||
};
|
||||
PathType::type get_path_type(std::string path);
|
||||
|
||||
// Loads a file or directory and merges the values into one Message.
|
||||
// Caller is responsible for processing includes
|
||||
bool load_message(std::string url, proto::Message& out_message, IConfigLog&, ConfigValueQueue&);
|
||||
int load_directory(std::string url, ConfigDownloader&, proto::Message& out_message, IConfigLog&, ConfigValueQueue&);
|
||||
ConfigDownloader::Result load_file(std::string url, ConfigDownloader&, proto::Message& out_message, IConfigLog&, ConfigValueQueue&, bool required = true);
|
||||
void parse_stream(const std::string& file, proto::io::ZeroCopyInputStream& stream, proto::Message& out_message, IConfigLog&, ConfigValueQueue& lookup);
|
||||
|
||||
}}}
|
||||
#endif
|
||||
Executable
+70
@@ -0,0 +1,70 @@
|
||||
#include "PreprocessInputStream.h"
|
||||
|
||||
#include <string>
|
||||
#include <boost/algorithm/string.hpp>
|
||||
|
||||
using namespace std;
|
||||
|
||||
namespace bts {
|
||||
namespace config {
|
||||
|
||||
void replace_all(string& line, const string& before, const string& after) {
|
||||
|
||||
string::const_iterator end = line.end();
|
||||
string::const_iterator current = line.begin();
|
||||
string::const_iterator next = search(current, end, before.begin(), before.end());
|
||||
|
||||
if (next != end) {
|
||||
std::string result;
|
||||
while(next != end) {
|
||||
result.append(current, next);
|
||||
result.append(after);
|
||||
current = next + before.size();
|
||||
next = search(current, end, before.begin(), before.end());
|
||||
}
|
||||
result.append(current, next);
|
||||
line = result;
|
||||
}
|
||||
}
|
||||
|
||||
PreprocessInputStream::PreprocessInputStream(std::istream& input, map<string, string> replacements) :
|
||||
_buffer(),
|
||||
_stream()
|
||||
{
|
||||
char temp[4096];
|
||||
while(input.read(temp, sizeof(temp))) {
|
||||
_buffer.append(temp, sizeof(temp));
|
||||
}
|
||||
_buffer.append(temp, input.gcount());
|
||||
|
||||
for (map<string, string>::iterator iter = replacements.begin(); iter != replacements.end(); iter++) {
|
||||
const string& key = iter->first;
|
||||
const string& value = iter->second;
|
||||
replace_all(_buffer, key, value);
|
||||
}
|
||||
|
||||
_stream.reset(new proto::io::ArrayInputStream(_buffer.c_str(), _buffer.size()));
|
||||
}
|
||||
|
||||
PreprocessInputStream::~PreprocessInputStream()
|
||||
{
|
||||
}
|
||||
|
||||
bool PreprocessInputStream::Next(const void** data, int* size) {
|
||||
return _stream->Next(data, size);
|
||||
}
|
||||
|
||||
void PreprocessInputStream::BackUp(int count) {
|
||||
_stream->BackUp(count);
|
||||
}
|
||||
|
||||
bool PreprocessInputStream::Skip(int count) {
|
||||
return _stream->Skip(count);
|
||||
}
|
||||
|
||||
proto::int64 PreprocessInputStream::ByteCount() const {
|
||||
return _stream->ByteCount();
|
||||
}
|
||||
|
||||
}}//namespace
|
||||
|
||||
Executable
+34
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
|
||||
#include <google/protobuf/io/zero_copy_stream_impl.h>
|
||||
#include <boost/scoped_ptr.hpp>
|
||||
#include "lib/utils/bts_no_copy.h"
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <memory>
|
||||
|
||||
namespace bts {
|
||||
namespace config {
|
||||
|
||||
namespace proto = google::protobuf;
|
||||
|
||||
class PreprocessInputStream : public proto::io::ZeroCopyInputStream
|
||||
{
|
||||
public:
|
||||
PreprocessInputStream(std::istream& input, std::map<std::string, std::string> replacements);
|
||||
~PreprocessInputStream();
|
||||
|
||||
bool Next(const void** data, int* size) override;
|
||||
void BackUp(int count) override;
|
||||
bool Skip(int count) override;
|
||||
proto::int64 ByteCount() const override;
|
||||
|
||||
private:
|
||||
std::string _buffer;
|
||||
boost::scoped_ptr<proto::io::ArrayInputStream> _stream;
|
||||
BTS_NO_COPY(PreprocessInputStream);
|
||||
};
|
||||
|
||||
}}//namespace
|
||||
|
||||
Executable
+129
@@ -0,0 +1,129 @@
|
||||
#ifndef CONFIG_H_
|
||||
#define CONFIG_H_
|
||||
|
||||
#include "config.h"
|
||||
#include "../os/os.h"
|
||||
#include "ConfigurationState.h"
|
||||
|
||||
#include <google/protobuf/descriptor.h>
|
||||
#include <google/protobuf/text_format.h>
|
||||
#include <google/protobuf/dynamic_message.h>
|
||||
#include <google/protobuf/descriptor.pb.h>
|
||||
|
||||
//#include <boost/thread.hpp>
|
||||
|
||||
namespace proto = google::protobuf;
|
||||
|
||||
namespace bts {
|
||||
namespace config {
|
||||
|
||||
internal::ConfigurationState config_state;
|
||||
|
||||
//////////////////////////////////////////
|
||||
// Public API
|
||||
//////////////////////////////////////////
|
||||
|
||||
extern "C" BTS_EXPORT void initialize()
|
||||
{
|
||||
config_state.initialize_settings();
|
||||
}
|
||||
|
||||
extern "C" BTS_EXPORT bool initialize_nothrow(char* error_message, size_t len)
|
||||
{
|
||||
try
|
||||
{
|
||||
initialize();
|
||||
}
|
||||
catch(std::exception& e)
|
||||
{
|
||||
std::string msg = e.what();
|
||||
if (msg.size() < len)
|
||||
{
|
||||
os::strncpy(error_message, msg.c_str(), len);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
//extern "C"
|
||||
const proto::Message& get_message(const google::protobuf::Descriptor* descriptor)
|
||||
{
|
||||
return config_state.get_message(descriptor);
|
||||
}
|
||||
|
||||
namespace interop {
|
||||
|
||||
//////////////////////////////////////////////////
|
||||
// Functions used for interop to other languages
|
||||
/////////////////////////////////////////////////
|
||||
|
||||
|
||||
std::string getbuffer_serialized_buffer;
|
||||
extern "C" BTS_EXPORT const char* get_buffer(const char* key_name, int& out_length)
|
||||
{
|
||||
google::protobuf::DescriptorPool const* pool = google::protobuf::DescriptorPool::generated_pool();
|
||||
const proto::Descriptor* message_desc = pool->FindMessageTypeByName(key_name);
|
||||
|
||||
const proto::Message& message = get_message(message_desc);
|
||||
|
||||
getbuffer_serialized_buffer.clear();
|
||||
message.SerializePartialToString(&getbuffer_serialized_buffer);
|
||||
|
||||
out_length = getbuffer_serialized_buffer.size();
|
||||
return getbuffer_serialized_buffer.c_str();
|
||||
}
|
||||
|
||||
extern "C" BTS_EXPORT const proto::Message* get_named(const char* key_name)
|
||||
{
|
||||
const auto* pmessage = config_state.try_get_message(key_name);
|
||||
if (pmessage) {
|
||||
return pmessage;
|
||||
}
|
||||
// If we can't find a value we should return a default instance
|
||||
const auto* descriptor = config_state.get_descriptor_by_name(key_name);
|
||||
if (descriptor) {
|
||||
return proto::MessageFactory::generated_factory()->GetPrototype(descriptor);
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
BTS_EXPORT std::string get_macro_string(const char* name) { return config_state.get_macro_string(name); }
|
||||
|
||||
}
|
||||
|
||||
namespace internal {
|
||||
|
||||
//////////////////////////////////////////
|
||||
// Functions used in testing
|
||||
//////////////////////////////////////////
|
||||
|
||||
extern "C" BTS_EXPORT void initialize_for_test(const std::string& values, bool print_errors)
|
||||
{
|
||||
config_state.reset();
|
||||
config_state.set_print_errors(print_errors);
|
||||
config_state.load_string(values);
|
||||
}
|
||||
|
||||
extern "C" BTS_EXPORT void reset()
|
||||
{
|
||||
config_state.reset();
|
||||
}
|
||||
|
||||
extern "C" BTS_EXPORT bool check_rules(char* error_msg, size_t len) {
|
||||
try {
|
||||
config_state.check_rules();
|
||||
}
|
||||
catch(std::exception& e) {
|
||||
std::string msg = e.what();
|
||||
if (msg.size() < len)
|
||||
{
|
||||
os::strncpy(error_msg, msg.c_str(), len);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}}} // end namespaces
|
||||
#endif
|
||||
Executable
+70
@@ -0,0 +1,70 @@
|
||||
#ifndef BTS_CONFIG_H_
|
||||
#define BTS_CONFIG_H_
|
||||
|
||||
#include "lib/utils/bts_export.h"
|
||||
#include "lib/utils/checked_cast.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
class Descriptor;
|
||||
class Message;
|
||||
}
|
||||
}
|
||||
|
||||
// Config
|
||||
// This API is intentionally kept flat and C-style to make interop from other languages simpler.
|
||||
|
||||
namespace bts {
|
||||
namespace config {
|
||||
|
||||
// Load and initialize config.
|
||||
// This will be automatically called on the first key request but since loading config
|
||||
// can result in network requests this function is available for applications that want to
|
||||
// manage pauses in execution.
|
||||
// Ex: initialize() on a background thread so that config::get<T>() is fast on a UI thread
|
||||
extern "C" BTS_EXPORT void initialize();
|
||||
|
||||
// Calls initialize() but catches any thrown exception and copies it to the provided buffer
|
||||
extern "C" BTS_EXPORT bool initialize_nothrow(char* error_msg, size_t length);
|
||||
|
||||
// Gets a raw message pointer from config for the given descriptor
|
||||
//extern "C"
|
||||
BTS_EXPORT const google::protobuf::Message& get_message(const google::protobuf::Descriptor* descriptor);
|
||||
|
||||
template<typename T>
|
||||
const T& get()
|
||||
{
|
||||
const google::protobuf::Descriptor* descriptor = T::descriptor();
|
||||
const google::protobuf::Message& message = get_message(descriptor);
|
||||
const T& retval = utils::checked_cast<const T&>(message);
|
||||
return retval;
|
||||
}
|
||||
|
||||
namespace interop
|
||||
{
|
||||
// Returns a serialized protocol buffer of the given type
|
||||
// The memory that this is serialized to may be re-used so you
|
||||
// should imediately deserialize and copy the data.
|
||||
extern "C" BTS_EXPORT const char* get_buffer(const char* key_name, int& out_length);
|
||||
|
||||
extern "C" BTS_EXPORT const google::protobuf::Message* get_named(const char* key_name);
|
||||
}
|
||||
|
||||
namespace internal
|
||||
{
|
||||
// Initialize configuration state from a string instead of from the filesystem. defaults.conf will still be loaded.
|
||||
// Calling this a second time clears all values from previous initialization
|
||||
extern "C" BTS_EXPORT void initialize_for_test(const std::string& configuration, bool print_errors=true);
|
||||
|
||||
// Releases all resources and returns config to factory defaults
|
||||
extern "C" BTS_EXPORT void reset();
|
||||
|
||||
extern "C" BTS_EXPORT bool check_rules(char* error_msg, size_t length);
|
||||
}
|
||||
}}
|
||||
|
||||
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,3 @@
|
||||
//GENERATED FILE
|
||||
const char * config_proto_files[] = {
|
||||
};
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
# This file 'catchall' configuration file
|
||||
# If *every* site must include a specific url that should be listed here
|
||||
# otherwise this file should be mostly empty.
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
Logging
|
||||
{
|
||||
value
|
||||
{
|
||||
console { default_level: "Warn" }
|
||||
syslog { default_level: "Info" }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
Foo {
|
||||
rule: "true"
|
||||
value {
|
||||
email: "default@example.com"
|
||||
}
|
||||
}
|
||||
Executable
+40
@@ -0,0 +1,40 @@
|
||||
Structure:
|
||||
|
||||
|
||||
To add a new config key
|
||||
1) Do you want to add a new logical grouping of config keys?
|
||||
If you do goto 2, otherwise goto 5.
|
||||
2) Create a new file with the .proto extension and define the package (namespace)
|
||||
to which your new keys should belong and import the common extensions.proto.
|
||||
Then define your new keys using the protocol buffer message format - see
|
||||
http://code.google.com/p/protobuf/
|
||||
|
||||
ex:
|
||||
package bts.config.keys;
|
||||
import "extensions.proto";
|
||||
|
||||
message MyNewExchange {
|
||||
// Suggested: include a namespace to group your keys in the editor
|
||||
option(name_space) = "MyKeys"
|
||||
// Suggested: write a doc string for this key so you remember what it's for
|
||||
option(doc_string) = "This key holds all the values that we need to know about when connecting to NewExchange"
|
||||
|
||||
// Example of a string field with a default value
|
||||
optional string login_name = 1 [default = "bts"];
|
||||
// example of a string field without a default value
|
||||
optional string password = 2;
|
||||
}
|
||||
3) Open config_proto_file_list.h and add your new .profo file to the list. This is the list of
|
||||
protobuf files that are considered config keys.
|
||||
4) Add your new file to config.bs and run "bt update" to update the msbuild project.
|
||||
You may also, optionally, add it as a 'document' or 'None' to the visual studio project so it is
|
||||
displayed in the solution explorer.
|
||||
5) Your message name is now a generated c++ type. If you added it to MyKeys.proto you can now #include "gen/core/config/mykeys.pb.h".
|
||||
To request the value from config use the GetValue() method. Make multiple calls for multiple key values.
|
||||
MyNewExchange* value = bts::config::GetValue<MyNewExchange>();
|
||||
std::string login_name = value->login_name();
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
syntax='proto2';
|
||||
import "google/protobuf/descriptor.proto";
|
||||
|
||||
// Custom protobuf fields - Every other config proto file should include this
|
||||
|
||||
extend google.protobuf.MessageOptions {
|
||||
//optional string name_space = 50100;
|
||||
optional string doc_string = 50101;
|
||||
}
|
||||
|
||||
//extend google.protobuf.FieldOptions {
|
||||
// Consider allowing certain fields to be sent along with the HTTP request
|
||||
//}
|
||||
|
||||
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
syntax='proto2';
|
||||
|
||||
// This protocol buffer is not considered a config key so requesting it from
|
||||
// config is not allowed.
|
||||
|
||||
package bts.config.test;
|
||||
|
||||
message InvalidMessageType {
|
||||
}
|
||||
|
||||
Executable
+248
@@ -0,0 +1,248 @@
|
||||
syntax='proto2';
|
||||
package bts.md;
|
||||
import "lib/security_model/security.proto";
|
||||
|
||||
//
|
||||
// Properties that help the market data engine determine
|
||||
// which platform should be used.
|
||||
//
|
||||
message PlatformMap
|
||||
{
|
||||
message PlatformProps
|
||||
{
|
||||
repeated bts.security_model.Exchange.type exchange = 2;
|
||||
}
|
||||
optional PlatformProps sim = 1;
|
||||
optional PlatformProps SRLabs = 2;
|
||||
optional PlatformProps Spryware = 3;
|
||||
optional PlatformProps CSM = 4;
|
||||
optional PlatformProps CME = 5;
|
||||
optional PlatformProps ICE = 6;
|
||||
optional PlatformProps Replay = 7;
|
||||
optional PlatformProps ACTIV = 8;
|
||||
optional PlatformProps MDP3 = 9;
|
||||
optional PlatformProps CSM_ONIXS = 10;
|
||||
optional PlatformProps BLUE = 11;
|
||||
}
|
||||
|
||||
//
|
||||
// Options that apply to market data server
|
||||
//
|
||||
message Channel {
|
||||
enum type {
|
||||
SECURITY = 1;
|
||||
BBO = 2;
|
||||
DEPTH = 3;
|
||||
TRADE = 4;
|
||||
MISC = 5;
|
||||
STATUS = 6;
|
||||
TRADELOG = 7;
|
||||
RFQ = 8;
|
||||
}
|
||||
}
|
||||
|
||||
message PublisherOptions
|
||||
{
|
||||
// removed 2
|
||||
optional string network_interface = 3 [default = "0.0.0.0"];
|
||||
// Supply either network_interface -or- network_interface_[a,b]
|
||||
optional string network_interface_a = 30;
|
||||
optional string network_interface_b = 31;
|
||||
// removed 4,5
|
||||
// removed 6,7,8
|
||||
optional string channel_prefix = 9 [default = ""];
|
||||
|
||||
// Co2 options
|
||||
|
||||
// How old can the heartbeat be before it's considered dead
|
||||
optional uint32 heartbeat_ms = 10 [default = 5000];
|
||||
optional bool disable_heartbeat = 11 [default = false];
|
||||
optional uint32 heartbeat_boot_seconds = 12 [default = 60]; // 1 minute grace period from shm creation
|
||||
}
|
||||
|
||||
message PlatformConfig
|
||||
{
|
||||
required string platform = 1;
|
||||
optional bts.security_model.Exchange.type exchange = 2 [default = TESTEXCHANGE];
|
||||
optional bts.security_model.SecurityType.type type = 3 [default = UNSET];
|
||||
}
|
||||
|
||||
message StreamOptions
|
||||
{
|
||||
optional uint32 trade_log_stream_size = 2 [default = 1024];
|
||||
}
|
||||
|
||||
message PublisherNamespace {
|
||||
optional string shared_memory_namespace = 1;
|
||||
}
|
||||
|
||||
//
|
||||
// CBOE CSM options
|
||||
//
|
||||
|
||||
message CSMOptions
|
||||
{
|
||||
optional bool use_backup_channels = 1 [default = false];
|
||||
optional bool always_run_security_feed = 2 [default = true];
|
||||
optional bool ignore_sequence_gap = 3 [default = false];
|
||||
|
||||
optional bool enable_gc = 4 [default = true];
|
||||
optional uint32 minimum_gc_cycle_seconds = 5 [default = 120];
|
||||
optional uint32 gc_after_cycles = 6 [default = 1];
|
||||
|
||||
optional uint32 udp_socket_buffer_size = 14 [default = 16777216]; // 16 mb
|
||||
|
||||
}
|
||||
|
||||
message CSMChannels
|
||||
{
|
||||
message Feed
|
||||
{
|
||||
required string address = 2;
|
||||
required uint32 port = 3;
|
||||
}
|
||||
|
||||
message Channel
|
||||
{
|
||||
optional string name = 1;
|
||||
optional Feed A = 2;
|
||||
optional Feed B = 3;
|
||||
}
|
||||
|
||||
optional Channel security_definition = 2;
|
||||
repeated Channel market_data = 3;
|
||||
}
|
||||
|
||||
message CSMTests
|
||||
{
|
||||
optional bool enabled = 1 [default = false];
|
||||
}
|
||||
|
||||
//
|
||||
// CME Options
|
||||
//
|
||||
message CMEOptions
|
||||
{
|
||||
enum OnixSLogMode {
|
||||
Disabled = 0;
|
||||
Important = 1;
|
||||
Regular = 2;
|
||||
Debug = 3;
|
||||
}
|
||||
enum OnixSLogAdvanced {
|
||||
LogNothing = 0;
|
||||
LogFixMessages = 1;
|
||||
LogFullBooks = 2;
|
||||
LogEverything = 3;
|
||||
}
|
||||
message FeedEngineSettings {
|
||||
optional string name = 1;
|
||||
// If num_threads is set it will use that - otherwise it will use channels_per_thread and the number of threads configured for this channel to determine the number of threads
|
||||
optional uint32 num_threads = 2 [default = 1];
|
||||
// Defines amount of time Feed Engine spends on socket waiting for I/O while running master processing loop.
|
||||
optional uint32 data_wait = 3 [default = 10];
|
||||
// Defines amount of time Feed Engine keeps cycling before going to sleep when no useful activity can be done
|
||||
optional uint32 spin_time = 4 [default = 1];
|
||||
optional uint32 channels_per_thread = 5 [default = 3];
|
||||
repeated uint32 affinity = 10;
|
||||
}
|
||||
message CMEChannel {
|
||||
repeated string id = 2;
|
||||
optional string feed_engine = 3 [default = "default"];
|
||||
|
||||
optional uint32 udp_socket_buffer_size = 10 [default = 33554432]; //32mb
|
||||
optional uint32 max_gap_recovery_cache_size = 11 [default = 6];
|
||||
optional uint32 lost_packet_wait_timeout_ms = 12 [default = 10];
|
||||
optional OnixSLogMode onixs_log_mode = 13 [default = Disabled];
|
||||
optional OnixSLogAdvanced onixs_log_advanced = 14 [default = LogNothing];
|
||||
optional bool prefer_backup_feeds = 15 [default = false];
|
||||
|
||||
optional bool use_tcp_replay = 20 [default = true];
|
||||
optional string tcp_replay_username = 21 [default = "MDPFFBLUE"];
|
||||
optional string tcp_replay_password = 22 [default = "password01"];
|
||||
optional int32 tcp_replay_connect_attempts = 23 [default = 3];
|
||||
optional int32 tcp_replay_reconnect_interval_ms = 24 [default = 30000];
|
||||
optional int32 tcp_replay_timeout_s = 25 [default = 10];
|
||||
|
||||
// New settings
|
||||
}
|
||||
optional string onixs_license = 1 [default = "{default}"];
|
||||
optional string onixs_log_path = 2 [default = "/var/log/bts/onixs"];
|
||||
repeated CMEChannel channel = 3;
|
||||
repeated FeedEngineSettings feed_engine = 5;
|
||||
|
||||
// Prevents parsing trades/rfqs/doing anything not required for quoting
|
||||
optional bool quoter_mode = 6;
|
||||
}
|
||||
|
||||
message RecordOptions {
|
||||
optional string output_path = 2 [default = "/home/bts/md/today"];
|
||||
optional bool enable_depth = 3 [default = false];
|
||||
optional bool enable_future_depth = 4 [default = true];
|
||||
}
|
||||
|
||||
//
|
||||
// Replay options
|
||||
//
|
||||
message ReplayOptions {
|
||||
optional string host = 1 [default = "mdreplay"];
|
||||
optional string base_path = 2 [default = "/md"];
|
||||
optional string file_name = 3 [default = "options.coconut"];
|
||||
|
||||
// 2.0 = double speed, 0.5 = half speed
|
||||
optional double speed = 11 [default = 1.0];
|
||||
|
||||
optional bool interactive = 12 [default = false];
|
||||
}
|
||||
|
||||
|
||||
//
|
||||
// Activ options
|
||||
//
|
||||
message ActivOptions {
|
||||
optional string username = 1;
|
||||
optional string password = 2;
|
||||
optional string gateway = 3;
|
||||
optional string serviceid = 4 [default = "Service.ContentGateway"];
|
||||
optional string network = 5;
|
||||
optional string protocol = 6 [default="ams"];
|
||||
optional bool enable_intra_day_security_add = 7 [default = true];
|
||||
|
||||
optional int32 entitlement_check_interval_s = 10 [default = 300];
|
||||
repeated string child_user = 11;
|
||||
|
||||
optional bool enable_depth = 12 [default = true];
|
||||
optional int32 tz_offset = 13 [default = 0];
|
||||
}
|
||||
|
||||
message ActivSpreadMap {
|
||||
message Entry {
|
||||
optional string symbol = 1;
|
||||
optional bts.security_model.Exchange.type exchange = 2 [default = TESTEXCHANGE];
|
||||
optional string pattern = 3;
|
||||
}
|
||||
repeated Entry entry = 1;
|
||||
}
|
||||
|
||||
message RelayOptions {
|
||||
optional uint32 naggle_ms = 1 [default = 100];
|
||||
optional uint32 security_scan_interval = 2 [default = 500];
|
||||
optional uint32 recovery_interval = 3 [default = 30000];
|
||||
}
|
||||
|
||||
//
|
||||
// Some strike thing
|
||||
//
|
||||
message NewExpStrikeInfo
|
||||
{
|
||||
required string symbol = 1;
|
||||
required double low_strike = 2;
|
||||
required double hi_strike = 3;
|
||||
required double increment = 4;
|
||||
}
|
||||
|
||||
message NewExpStrikes
|
||||
{
|
||||
repeated NewExpStrikeInfo add_strike_info = 1;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
syntax='proto2';
|
||||
package bts.config;
|
||||
|
||||
message Ports {
|
||||
// quickbus (this is a tcp port)
|
||||
optional int32 qbus_port = 245 [default=8000];
|
||||
|
||||
// REDUNDANT with executor.cfg
|
||||
optional int32 fix_simulator_port = 290 [default=9999];
|
||||
optional int32 fix_simulator_port_2 = 300 [default=9998];
|
||||
|
||||
// Port 80 will be default for Apache config server
|
||||
optional int32 config_port = 430 [default = 80];
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
syntax='proto2';
|
||||
package bts.config;
|
||||
import "security_model/security.proto";
|
||||
|
||||
message Security {
|
||||
required string symbol = 1;
|
||||
required security_model.Exchange.type exchange = 10;
|
||||
required security_model.SecurityType.type type = 20;
|
||||
}
|
||||
|
||||
message Securities {
|
||||
repeated Security security = 10;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
syntax='proto2';
|
||||
package bts.config;
|
||||
import "lib/security_model/security.proto";
|
||||
|
||||
message Symbol {
|
||||
required string symbol = 1;
|
||||
required security_model.Exchange.type exchange = 10;
|
||||
required security_model.SecurityType.type type = 20;
|
||||
}
|
||||
|
||||
message Symbols {
|
||||
repeated Symbol symbol = 10;
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
syntax='proto2';
|
||||
package bts.config;
|
||||
|
||||
message JetFIX {
|
||||
message Connection {
|
||||
// a friendly name used to represent this session in the UI
|
||||
required string name = 10;
|
||||
|
||||
enum JetFIXPlatform {
|
||||
GLBX = 1;
|
||||
CBOE = 6;
|
||||
}
|
||||
optional JetFIXPlatform platform = 15 [default = GLBX];
|
||||
|
||||
// the ip address to connect to
|
||||
required string socket_connect_host_ip = 30;
|
||||
|
||||
// the port to connect to
|
||||
required uint32 socket_connect_port = 40;
|
||||
|
||||
// time in seconds before reconnect attempt
|
||||
optional int32 reconnect_interval = 20 [default = 60];
|
||||
|
||||
// time of day the FIX session becomes activated (UTC)
|
||||
optional string start_time = 50 [default = "00:30:00"];
|
||||
|
||||
// time of day the FIX session become deactiviated (UTC)
|
||||
optional string end_time = 60 [ default = "23:30:00"];
|
||||
|
||||
// time in seconds between heartbeat messages (typically 30)
|
||||
optional int32 seconds_between_hbs = 70 [default = 30];
|
||||
|
||||
// maximum number of incoming hbs we can miss before we close
|
||||
// the connection
|
||||
optional int32 max_missed_hbs = 75 [default = 2];
|
||||
|
||||
// time of day the FIX session becomes activated (UTC)
|
||||
optional string start_day = 80;
|
||||
|
||||
// time of day the FIX session become deactiviated (UTC)
|
||||
optional string end_day = 90;
|
||||
|
||||
optional string sender_compid = 100 [default = ""];
|
||||
optional string target_compid = 110 [default = ""];
|
||||
optional string sender_subid = 120 [default = ""];
|
||||
optional string target_subid = 130 [default = ""];
|
||||
optional string sender_locationid = 135 [default = "US,NC"];
|
||||
optional string raw_data = 136 [default =""];
|
||||
optional string self_match_prevention_id = 140 [default="bluestream"];
|
||||
optional string cti_code = 145 [default="1"];
|
||||
optional string mm_account = 150 [default = ""];
|
||||
|
||||
optional int32 quote_entries_per_message = 160 [default = 15];
|
||||
optional int32 registered_instrument_group_count = 170 [default = 100];
|
||||
optional int32 seconds_to_pause = 180 [default = 35];
|
||||
optional int32 seconds_to_logon = 185 [default = 5];
|
||||
optional int32 seconds_to_logout = 190 [default = 5];
|
||||
optional int32 seconds_between_syncs = 200 [default = 3];
|
||||
|
||||
optional uint32 max_qps = 210 [default = 750];
|
||||
|
||||
optional uint32 max_spt = 214 [default = 100];
|
||||
optional uint32 max_spt_window_secs = 217 [default = 3];
|
||||
|
||||
optional uint32 max_msgs_in_resend_req = 220 [default = 2499];
|
||||
|
||||
optional uint32 msg_buffer_sz = 230 [default = 10000000];
|
||||
optional uint32 msg_high_water_mark = 240 [default = 2048];
|
||||
optional uint32 seconds_to_replay = 250 [default = 30];
|
||||
optional bool log_fix_stream = 260 [default=false];
|
||||
optional bool use_persisted_quote_ids = 270 [default=true];
|
||||
optional uint32 quote_id_reservation_size = 290 [default=100000];
|
||||
optional uint32 poll_period_ms = 300 [default=100];
|
||||
optional bool use_dedicated_core = 310 [default=false];
|
||||
optional uint32 cme_market_segment_id = 320 [default=0];
|
||||
|
||||
optional string trading_session_id = 330 [default=""];
|
||||
optional int32 udf_support_indicator = 340 [default=1];
|
||||
}
|
||||
|
||||
repeated Connection connection = 10;
|
||||
}
|
||||
|
||||
message JetFIXSimConnections {
|
||||
required JetFIX.Connection glbx_quoter = 10;
|
||||
required JetFIX.Connection glbx_eye = 30;
|
||||
required JetFIX.Connection cboe_eye = 40;
|
||||
required JetFIX.Connection glbx_hedger = 50;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
syntax='proto2';
|
||||
|
||||
package bts.config;
|
||||
|
||||
message Logging {
|
||||
message SubsystemConfig {
|
||||
required string name = 1;
|
||||
required string level = 2;
|
||||
}
|
||||
message SinkConfig {
|
||||
optional string default_level = 2 [default="Info"];
|
||||
repeated SubsystemConfig subsystem = 3;
|
||||
}
|
||||
required SinkConfig console = 1;
|
||||
required SinkConfig syslog = 2;
|
||||
|
||||
optional uint32 initial_queue_size = 3 [default=12000000];
|
||||
optional uint32 max_queue_growth = 4 [default=4];
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
syntax='proto2';
|
||||
package bts.config;
|
||||
|
||||
message QuickbusNodeCfg {
|
||||
optional uint32 reconnect_period_secs = 1 [default=5];
|
||||
optional string parent_host = 2 [default=""];
|
||||
optional uint32 parent_port = 3 [default=0];
|
||||
optional uint32 my_port = 4 [default=0];
|
||||
optional uint32 hb_period_msecs = 5 [default=15000];
|
||||
optional uint32 max_missed_hbs = 6 [default=3];
|
||||
}
|
||||
|
||||
message QuickbusCfg {
|
||||
optional uint32 reconnect_period_secs = 1 [default=5];
|
||||
optional string qbus_host = 2 [default=""];
|
||||
optional uint32 qbus_port = 3 [default=0];
|
||||
optional uint32 hb_period_msecs = 5 [default=15000];
|
||||
optional uint32 max_missed_hbs = 6 [default=3];
|
||||
}
|
||||
|
||||
Executable
+38
@@ -0,0 +1,38 @@
|
||||
syntax='proto2';
|
||||
|
||||
package bts.config;
|
||||
|
||||
message System
|
||||
{
|
||||
required string host_name = 1;
|
||||
required string process_name = 3;
|
||||
required string process_path = 4;
|
||||
required string platform = 5;
|
||||
required string qualifier = 6;
|
||||
required bool unittest_environment = 7;
|
||||
required string data_path = 8;
|
||||
optional string version = 9 [default = "private"];
|
||||
repeated string cmd_args = 10;
|
||||
required string installation = 11;
|
||||
required string installation_specific_data_path = 12;
|
||||
required int32 build_number = 13 [default = 0];
|
||||
required string build_type = 14 [default = "release"];
|
||||
required string config_host = 15;
|
||||
required string config_ip = 16 [default = "127.0.0.1"];
|
||||
optional bool is_remote_app = 17 [default = false];
|
||||
required string os_user = 18;
|
||||
optional int32 dpi = 19 [default = 96];
|
||||
optional double dpi_ratio = 20 [default = 1.0];
|
||||
optional int32 num_cores = 21;
|
||||
optional int32 config_port = 22 [default = 80];
|
||||
}
|
||||
|
||||
message ConfigIntrospection {
|
||||
message ConfigProto {
|
||||
required string name = 1;
|
||||
repeated string type = 2;
|
||||
}
|
||||
repeated ConfigProto config = 1;
|
||||
}
|
||||
|
||||
|
||||
Executable
+84
@@ -0,0 +1,84 @@
|
||||
syntax='proto2';
|
||||
|
||||
import "lib/config/extensions/extensions.proto";
|
||||
|
||||
package bts.config.test;
|
||||
|
||||
// This is a comment about Foo
|
||||
message Foo {
|
||||
option(doc_string) = "This is a test key. Don't use it for real data";
|
||||
|
||||
optional string name = 1 [default = "Blue Foo"];
|
||||
optional int32 id = 2 [default = 1234];
|
||||
repeated string email = 3;
|
||||
optional string url = 4;
|
||||
}
|
||||
|
||||
message FooGroup {
|
||||
required string group = 1;
|
||||
required Foo foo = 2;
|
||||
}
|
||||
|
||||
message NamedFoo {
|
||||
optional string key = 1;
|
||||
optional Foo foo = 2;
|
||||
repeated Foo foox = 3;
|
||||
optional string rule = 4;
|
||||
}
|
||||
|
||||
message FooList {
|
||||
repeated NamedFoo item = 1;
|
||||
repeated Foo foo = 2;
|
||||
}
|
||||
|
||||
message StringTable {
|
||||
repeated string entries = 1;
|
||||
}
|
||||
|
||||
message RuleRef {
|
||||
option(doc_string) = "This contains properties of various types which we can use as test cases for self-referenential rules";
|
||||
|
||||
optional string a_string = 1;
|
||||
optional int32 a_int = 2;
|
||||
repeated string list_string = 3;
|
||||
repeated int32 list_int = 4;
|
||||
repeated Foo foox = 6;
|
||||
|
||||
optional RuleRef nested = 5;
|
||||
|
||||
}
|
||||
|
||||
// For Config demo
|
||||
message ConsoleColor {
|
||||
enum Colors {
|
||||
DarkBlue = 1;
|
||||
DarkGreen = 2;
|
||||
DarkTeel = 3;
|
||||
DarkRed = 4;
|
||||
DarkPink = 5;
|
||||
DarkYellow = 6;
|
||||
Gray = 7;
|
||||
DarkGray = 8;
|
||||
Blue = 9;
|
||||
Green = 10;
|
||||
Teal = 11;
|
||||
Red = 12;
|
||||
Pink = 13;
|
||||
Yellow = 14;
|
||||
White = 15;
|
||||
}
|
||||
required Colors color = 1;
|
||||
}
|
||||
|
||||
message ConsoleColors {
|
||||
optional ConsoleColor.Colors color = 1;
|
||||
repeated ConsoleColor.Colors colors = 2;
|
||||
}
|
||||
|
||||
message TestSite {
|
||||
required string name = 1 [default="NO NAME!"];
|
||||
}
|
||||
|
||||
message Ports {
|
||||
optional int32 config_port = 1;
|
||||
}
|
||||
Executable
+104
@@ -0,0 +1,104 @@
|
||||
|
||||
#include "HTTPServer.h"
|
||||
|
||||
using boost::asio::ip::tcp;
|
||||
|
||||
namespace bts {
|
||||
namespace config {
|
||||
namespace internal {
|
||||
|
||||
HTTPServer::HTTPServer()
|
||||
: _io_service(),
|
||||
_acceptor(_io_service, tcp::endpoint(boost::asio::ip::address_v4::loopback(), 0)),
|
||||
_cur_socket(),
|
||||
_request_response_pairs(),
|
||||
_thread(),
|
||||
_done(false)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
unsigned int HTTPServer::port() const
|
||||
{
|
||||
return _acceptor.local_endpoint().port();
|
||||
}
|
||||
|
||||
void HTTPServer::add_response(const std::string& path, const std::string& response, const std::string& content)
|
||||
{
|
||||
_request_response_pairs[path] = response + content;
|
||||
}
|
||||
|
||||
void HTTPServer::start()
|
||||
{
|
||||
_thread.reset(new boost::thread(boost::bind(&HTTPServer::worker, this)));
|
||||
}
|
||||
|
||||
void HTTPServer::stop()
|
||||
{
|
||||
_done = true;
|
||||
_io_service.stop();
|
||||
|
||||
if (_thread) {
|
||||
_thread->join();
|
||||
_thread.reset();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void HTTPServer::worker()
|
||||
{
|
||||
start_accept();
|
||||
|
||||
_io_service.run();
|
||||
}
|
||||
|
||||
void HTTPServer::start_accept()
|
||||
{
|
||||
_cur_socket.reset(new boost::asio::ip::tcp::socket(_io_service));
|
||||
_acceptor.async_accept(*_cur_socket.get(), boost::bind(&HTTPServer::handle_accept, this, _cur_socket.get(), boost::asio::placeholders::error));
|
||||
}
|
||||
|
||||
void HTTPServer::handle_accept(boost::asio::ip::tcp::socket* socket, const boost::system::error_code& error)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
handle_connect(socket);
|
||||
}
|
||||
start_accept();
|
||||
}
|
||||
|
||||
void HTTPServer::handle_connect(boost::asio::ip::tcp::socket* socket)
|
||||
{
|
||||
boost::asio::streambuf buffer;
|
||||
size_t size = boost::asio::read_until(*socket, buffer, "\r\n\r\n");
|
||||
std::string request(size, 0);
|
||||
buffer.sgetn(&request[0], size);
|
||||
|
||||
size_t start = request.find("GET ") + 4;
|
||||
size_t end = request.find(" HTTP/1.1\r\n");
|
||||
size_t url_args = request.find("?");
|
||||
if (url_args != std::string::npos)
|
||||
end = std::min(end, url_args);
|
||||
std::string request_path = request.substr(start, end-start);
|
||||
|
||||
std::map<std::string, std::string>::iterator request_match =
|
||||
_request_response_pairs.find(request_path);
|
||||
|
||||
if (request_match == _request_response_pairs.end())
|
||||
{
|
||||
std::string response = "HTTP/1.0 404 NOT FOUND\r\n"
|
||||
"Content-Type: text/plain\r\n\r\n"
|
||||
"not found\r\n";
|
||||
boost::asio::write(*socket, boost::asio::buffer(response));
|
||||
}
|
||||
else
|
||||
{
|
||||
boost::asio::write(*socket, boost::asio::buffer(request_match->second));
|
||||
}
|
||||
|
||||
boost::system::error_code ec;
|
||||
socket->shutdown(tcp::socket::shutdown_both, ec);
|
||||
socket->close(ec);
|
||||
}
|
||||
|
||||
}}}
|
||||
Executable
+53
@@ -0,0 +1,53 @@
|
||||
#ifndef HTTP_TEST_SERVER_H_
|
||||
#define HTTP_TEST_SERVER_H_
|
||||
|
||||
#include <boost/asio/buffer.hpp>
|
||||
#include <boost/asio/deadline_timer.hpp>
|
||||
#include <boost/asio/io_service.hpp>
|
||||
#include <boost/asio/ip/tcp.hpp>
|
||||
#include <boost/asio/read_until.hpp>
|
||||
#include <boost/asio/streambuf.hpp>
|
||||
#include <boost/asio/write.hpp>
|
||||
#include <boost/bind.hpp>
|
||||
#include <boost/lexical_cast.hpp>
|
||||
#include <boost/scoped_ptr.hpp>
|
||||
#include <boost/thread.hpp>
|
||||
|
||||
#include <boost/asio.hpp>
|
||||
#include <boost/asio/connect.hpp>
|
||||
#include <boost/scoped_ptr.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <map>
|
||||
|
||||
namespace bts {
|
||||
namespace config {
|
||||
namespace internal {
|
||||
|
||||
class HTTPServer
|
||||
{
|
||||
public:
|
||||
HTTPServer();
|
||||
unsigned int port() const;
|
||||
|
||||
void start();
|
||||
void add_response(const std::string& path, const std::string& response, const std::string& content);
|
||||
void stop();
|
||||
|
||||
private:
|
||||
void worker();
|
||||
void start_accept();
|
||||
void handle_accept(boost::asio::ip::tcp::socket*, const boost::system::error_code& error);
|
||||
void handle_connect(boost::asio::ip::tcp::socket*);
|
||||
|
||||
boost::asio::io_service _io_service;
|
||||
boost::asio::ip::tcp::acceptor _acceptor;
|
||||
boost::scoped_ptr<boost::asio::ip::tcp::socket> _cur_socket;
|
||||
std::map<std::string, std::string> _request_response_pairs;
|
||||
boost::scoped_ptr<boost::thread> _thread;
|
||||
bool _done;
|
||||
|
||||
};
|
||||
|
||||
}}} // end namespace
|
||||
#endif
|
||||
Executable
+932
@@ -0,0 +1,932 @@
|
||||
#include "lib/utils/TempFile.h"
|
||||
#include "lib/utils/TempDir.h"
|
||||
|
||||
#include "../config.h"
|
||||
#include "../ConfigurationState.h"
|
||||
#include "../ConfigurationException.h"
|
||||
#include "lib/expression/ParserExceptions.h"
|
||||
#include "lib/config/protos/testkeys.pb.h"
|
||||
#include "lib/config/invalid/invalid.pb.h"
|
||||
|
||||
#include "HTTPServer.h"
|
||||
#include "catch/catch.h"
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
|
||||
using namespace bts::config;
|
||||
using namespace bts::config::internal;
|
||||
namespace proto = google::protobuf;
|
||||
|
||||
using bts::config::test::Foo;
|
||||
using bts::config::test::FooGroup;
|
||||
using bts::config::test::FooList;
|
||||
|
||||
namespace bts {
|
||||
TEST_CASE ("Configuration Reference Tests", "[config]") {
|
||||
|
||||
SECTION("basic_value")
|
||||
{
|
||||
initialize_for_test(
|
||||
"TestSite {"
|
||||
" value {"
|
||||
" name: 'ref value'"
|
||||
" }"
|
||||
"}"
|
||||
"Foo { \n"
|
||||
" value {\n"
|
||||
" name: @TestSite.name"
|
||||
" }\n"
|
||||
"}\n"
|
||||
);
|
||||
|
||||
const Foo& foo = get<Foo>();
|
||||
REQUIRE(foo.name() == "ref value");
|
||||
}
|
||||
|
||||
SECTION("scalar_to_repeat") {
|
||||
initialize_for_test(
|
||||
"TestSite {"
|
||||
" value {"
|
||||
" name: 'a@example.com' "
|
||||
" }"
|
||||
"}"
|
||||
"Foo { \n"
|
||||
" value {\n"
|
||||
" email: \"before@example.com\" \n"
|
||||
" email: @TestSite.name \n"
|
||||
" email: \"after@example.com\" \n"
|
||||
" }\n"
|
||||
"}\n"
|
||||
);
|
||||
|
||||
const Foo& foo = get<Foo>();
|
||||
|
||||
REQUIRE(foo.email_size() == 3);
|
||||
REQUIRE(foo.email(0) == "before@example.com");
|
||||
REQUIRE(foo.email(1) == "a@example.com");
|
||||
REQUIRE(foo.email(2) == "after@example.com");
|
||||
}
|
||||
|
||||
SECTION("repeat_to_repeat ") {
|
||||
initialize_for_test(
|
||||
"StringTable {"
|
||||
" value {"
|
||||
" entries: 'a@example.com' "
|
||||
" entries: 'b@example.com' "
|
||||
" }"
|
||||
"}"
|
||||
"TestSite {"
|
||||
" value {"
|
||||
" name: 'c@example.com' "
|
||||
" }"
|
||||
"}"
|
||||
"Foo { \n"
|
||||
" value {\n"
|
||||
" email: \"before@example.com\" \n"
|
||||
" email: @StringTable.entries \n"
|
||||
" email: @TestSite.name \n"
|
||||
" email: \"after@example.com\" \n"
|
||||
" }\n"
|
||||
"}\n"
|
||||
);
|
||||
|
||||
const Foo& foo = get<Foo>();
|
||||
|
||||
REQUIRE(foo.email_size() == 5);
|
||||
REQUIRE(foo.email(0) == "before@example.com");
|
||||
REQUIRE(foo.email(1) == "a@example.com");
|
||||
REQUIRE(foo.email(2) == "b@example.com");
|
||||
REQUIRE(foo.email(3) == "c@example.com");
|
||||
REQUIRE(foo.email(4) == "after@example.com");
|
||||
}
|
||||
|
||||
SECTION("message_value") {
|
||||
initialize_for_test(
|
||||
"Foo { \n"
|
||||
" rule: 'false'"
|
||||
" value {\n"
|
||||
" name: \"bad\"\n"
|
||||
" }\n"
|
||||
"}\n"
|
||||
"Foo { \n"
|
||||
" value {\n"
|
||||
" name: \"good\"\n"
|
||||
" }\n"
|
||||
"}\n"
|
||||
"FooGroup {"
|
||||
" value { "
|
||||
" group: @Foo.name "
|
||||
" foo: @Foo "
|
||||
" }"
|
||||
"}"
|
||||
);
|
||||
|
||||
const FooGroup& g = get<FooGroup>();
|
||||
REQUIRE(g.group() == "good");
|
||||
REQUIRE(g.foo().name() == "good");
|
||||
}
|
||||
|
||||
SECTION("nested_message_value") {
|
||||
initialize_for_test(
|
||||
"NamedFoo { \n"
|
||||
" value {\n"
|
||||
" key: 'good foo' "
|
||||
" foo { "
|
||||
" name: \"good\"\n"
|
||||
" }"
|
||||
" }\n"
|
||||
"}\n"
|
||||
"FooGroup {"
|
||||
" value { "
|
||||
" group: @NamedFoo.key "
|
||||
" foo: @NamedFoo.foo "
|
||||
" }"
|
||||
"}"
|
||||
);
|
||||
|
||||
const FooGroup& g = get<FooGroup>();
|
||||
REQUIRE(g.group() == "good foo");
|
||||
REQUIRE(g.foo().name() == "good");
|
||||
}
|
||||
|
||||
SECTION("macro_value") {
|
||||
initialize_for_test(
|
||||
"macro {"
|
||||
" name: 'macro1' "
|
||||
" expression: \"'m1'\" "
|
||||
"}"
|
||||
"Foo { \n"
|
||||
" value {\n"
|
||||
" name: $macro1"
|
||||
" }\n"
|
||||
"}\n"
|
||||
);
|
||||
|
||||
const Foo& foo = get<Foo>();
|
||||
REQUIRE(foo.name() == "m1");
|
||||
}
|
||||
|
||||
SECTION("enum_value") {
|
||||
initialize_for_test(
|
||||
"ConsoleColor {"
|
||||
" value {"
|
||||
" color: Blue "
|
||||
" }"
|
||||
"}"
|
||||
"ConsoleColors {"
|
||||
" value {"
|
||||
" color: @ConsoleColor.color"
|
||||
" colors: Green"
|
||||
" colors: @ConsoleColor.color"
|
||||
" colors: DarkRed"
|
||||
" colors: @ConsoleColor.color"
|
||||
" }"
|
||||
"}"
|
||||
);
|
||||
|
||||
const test::ConsoleColor& c1 = get<test::ConsoleColor>();
|
||||
const test::ConsoleColors& c2 = get<test::ConsoleColors>();
|
||||
REQUIRE(c2.color() == c1.color());
|
||||
REQUIRE(c2.colors_size() == 4);
|
||||
REQUIRE(c2.colors(0) == test::ConsoleColor::Green);
|
||||
REQUIRE(c2.colors(1) == c1.color());
|
||||
REQUIRE(c2.colors(2) == test::ConsoleColor::DarkRed);
|
||||
REQUIRE(c2.colors(3) == c1.color());
|
||||
}
|
||||
|
||||
SECTION("named_key") {
|
||||
initialize_for_test(
|
||||
"Foo { \n"
|
||||
" value {\n"
|
||||
" name: @FooList.item[foo2].foo.name "
|
||||
" }\n"
|
||||
"}\n"
|
||||
"FooList { \n"
|
||||
" value {\n"
|
||||
" item { "
|
||||
" key: 'foo1' "
|
||||
" foo { "
|
||||
" name: 'foo1' "
|
||||
" }"
|
||||
" }"
|
||||
" item { "
|
||||
" key: 'foo2' "
|
||||
" foo { "
|
||||
" name: 'foo2' "
|
||||
" }"
|
||||
" }"
|
||||
" item { "
|
||||
" key: 'foo3' "
|
||||
" foo { "
|
||||
" name: 'foo3' "
|
||||
" }"
|
||||
" }"
|
||||
" }\n"
|
||||
"}\n"
|
||||
);
|
||||
|
||||
REQUIRE(get<Foo>().name() == "foo2");
|
||||
}
|
||||
|
||||
SECTION("named_key_rule") {
|
||||
initialize_for_test(
|
||||
"Foo { \n"
|
||||
" value {\n"
|
||||
" name: @FooList.item[foo2].foo.name "
|
||||
" }\n"
|
||||
"}\n"
|
||||
"FooList { \n"
|
||||
" value {\n"
|
||||
" item { "
|
||||
" key: 'foo1' "
|
||||
" foo { "
|
||||
" name: 'foo1' "
|
||||
" }"
|
||||
" }"
|
||||
" item { "
|
||||
" key: 'foo2' "
|
||||
" rule: '1=0' "
|
||||
" foo { "
|
||||
" name: 'foo2' "
|
||||
" }"
|
||||
" }"
|
||||
" item { "
|
||||
" key: 'foo3' "
|
||||
" foo { "
|
||||
" name: 'foo3' "
|
||||
" }"
|
||||
" }"
|
||||
" }\n"
|
||||
"}\n"
|
||||
);
|
||||
|
||||
//NOTE that a false rule will still create a message with defaults, so the list contains the same number of elements
|
||||
REQUIRE(get<Foo>().name() == "Blue Foo");
|
||||
REQUIRE(get<FooList>().item_size() == 3);
|
||||
}
|
||||
|
||||
SECTION("named_key2") {
|
||||
initialize_for_test(
|
||||
"Foo { \n"
|
||||
" value: @FooList.foo[foo2] "
|
||||
"}\n"
|
||||
"FooList { \n"
|
||||
" value {\n"
|
||||
" foo { "
|
||||
" name: 'foo1' "
|
||||
" id: 1 "
|
||||
" }"
|
||||
" foo { "
|
||||
" name: 'foo2' "
|
||||
" id: 2 "
|
||||
" }"
|
||||
" foo { "
|
||||
" name: 'foo3' "
|
||||
" id: 3 "
|
||||
" }"
|
||||
" }\n"
|
||||
"}\n"
|
||||
);
|
||||
|
||||
REQUIRE(get<Foo>().name() == "foo2");
|
||||
REQUIRE(get<Foo>().id() == 2);
|
||||
}
|
||||
|
||||
SECTION("named_key_syntax_error") {
|
||||
bool error = false;
|
||||
try {
|
||||
initialize_for_test(
|
||||
"Foo { \n"
|
||||
" value: @FooList[foo2] " // FooList doesn't have a key or a property named foo2
|
||||
"}\n"
|
||||
"FooList { \n"
|
||||
" value {\n"
|
||||
" foo { "
|
||||
" name: 'foo1' "
|
||||
" id: 1 "
|
||||
" }"
|
||||
" foo { "
|
||||
" name: 'foo2' "
|
||||
" id: 2 "
|
||||
" }"
|
||||
" foo { "
|
||||
" name: 'foo3' "
|
||||
" id: 3 "
|
||||
" }"
|
||||
" }\n"
|
||||
"}\n"
|
||||
);
|
||||
}
|
||||
catch(...) {
|
||||
error = true;
|
||||
}
|
||||
REQUIRE(error);
|
||||
}
|
||||
|
||||
SECTION("named_struture") {
|
||||
initialize_for_test(
|
||||
"FooGroup { \n"
|
||||
" value {\n"
|
||||
" foo: @FooList.item[foo3].foo "
|
||||
" }\n"
|
||||
"}\n"
|
||||
"FooList { \n"
|
||||
" value {\n"
|
||||
" item { "
|
||||
" key: 'foo1' "
|
||||
" foo { "
|
||||
" name: 'foo1' "
|
||||
" id: 1 "
|
||||
" }"
|
||||
" }"
|
||||
" item { "
|
||||
" key: 'foo2' "
|
||||
" foo { "
|
||||
" name: 'foo2' "
|
||||
" id: 2 "
|
||||
" }"
|
||||
" }"
|
||||
" item { "
|
||||
" key: 'foo3' "
|
||||
" foo { "
|
||||
" name: 'foo3' "
|
||||
" id: 3 "
|
||||
" }"
|
||||
" }"
|
||||
" }\n"
|
||||
"}\n"
|
||||
);
|
||||
REQUIRE(get<FooGroup>().foo().name() == "foo3");
|
||||
REQUIRE(get<FooGroup>().foo().id() == 3);
|
||||
}
|
||||
|
||||
SECTION("named_structure_rule") {
|
||||
initialize_for_test(
|
||||
"FooGroup { \n"
|
||||
" value {\n"
|
||||
" foo: @FooList.item[foo3].foo "
|
||||
" }\n"
|
||||
"}\n"
|
||||
"FooList { \n"
|
||||
" value {\n"
|
||||
" item { "
|
||||
" key: 'foo1' "
|
||||
" foo { "
|
||||
" name: 'foo1' "
|
||||
" id: 1 "
|
||||
" }"
|
||||
" }"
|
||||
" item { "
|
||||
" key: 'foo2' "
|
||||
" foo { "
|
||||
" name: 'foo2' "
|
||||
" id: 2 "
|
||||
" }"
|
||||
" }"
|
||||
" item { "
|
||||
" key: 'foo3' "
|
||||
" rule: 'false'"
|
||||
" foo { "
|
||||
" name: 'foo3' "
|
||||
" id: 3 "
|
||||
" }"
|
||||
" }"
|
||||
" }\n"
|
||||
"}\n"
|
||||
);
|
||||
//NOTE that a false rule will still create a message with defaults, so the list contains the same number of elements
|
||||
REQUIRE(get<FooGroup>().foo().name() == "Blue Foo");
|
||||
REQUIRE(get<FooGroup>().foo().id() == 1234);
|
||||
REQUIRE(get<FooList>().item_size() == 3);
|
||||
}
|
||||
|
||||
SECTION("named_value_rule") {
|
||||
initialize_for_test(
|
||||
"FooList { \n"
|
||||
" value {\n"
|
||||
" item { "
|
||||
" key: 'foo1' "
|
||||
" foo { "
|
||||
" name: 'foo1' "
|
||||
" id: 1 "
|
||||
" }"
|
||||
" }"
|
||||
" item { "
|
||||
" key: 'foo2' "
|
||||
" foo { "
|
||||
" name: 'foo2' "
|
||||
" id: 2 "
|
||||
" }"
|
||||
" }"
|
||||
" item { "
|
||||
" key: 'foo3' "
|
||||
" foo { "
|
||||
" name: 'foo3' "
|
||||
" id: 3 "
|
||||
" }"
|
||||
" }"
|
||||
" }\n"
|
||||
"}\n"
|
||||
"Foo { \n"
|
||||
// Adding [] to BooleanGrammer.h is very difficult because boost::spirit is crap
|
||||
// also it risks making list syntax [1,2,3] ambiguous so this is a workaround syntax
|
||||
" rule: 'FooList.item.foo1.foo.id = 2' "
|
||||
" value {\n"
|
||||
" name: 'bad' "
|
||||
" }\n"
|
||||
"}\n"
|
||||
"Foo { \n"
|
||||
" rule: 'FooList.item.foo2.foo.id = 2' "
|
||||
" value {\n"
|
||||
" name: 'good' "
|
||||
" }\n"
|
||||
"}\n"
|
||||
);
|
||||
|
||||
const Foo& foo = get<Foo>();
|
||||
REQUIRE(foo.name() == "good");
|
||||
}
|
||||
|
||||
SECTION("recursive_reference_good") {
|
||||
initialize_for_test(
|
||||
"TestSite { \n"
|
||||
" value {\n"
|
||||
" name: \"good\"\n"
|
||||
" }\n"
|
||||
"}\n"
|
||||
"Foo { \n"
|
||||
" value {\n"
|
||||
" name: @TestSite.name "
|
||||
" }\n"
|
||||
"}\n"
|
||||
"FooGroup {"
|
||||
" value { "
|
||||
" group: @Foo.name "
|
||||
" foo: @Foo "
|
||||
" }"
|
||||
"}"
|
||||
);
|
||||
|
||||
REQUIRE(get<FooGroup>().group() == "good");
|
||||
REQUIRE(get<FooGroup>().foo().name() == "good");
|
||||
}
|
||||
|
||||
SECTION("recursive_reference_bad") {
|
||||
bool error = false;
|
||||
try {
|
||||
|
||||
initialize_for_test(
|
||||
"TestSite { \n"
|
||||
" value {\n"
|
||||
" name: @Foo.name "
|
||||
" }\n"
|
||||
"}\n"
|
||||
"Foo { \n"
|
||||
" value {\n"
|
||||
" name: @TestSite.name "
|
||||
" }\n"
|
||||
"}\n"
|
||||
"FooGroup {"
|
||||
" value { "
|
||||
" group: @Foo.name "
|
||||
" foo: @Foo "
|
||||
" }"
|
||||
"}"
|
||||
);
|
||||
|
||||
|
||||
} catch(...) {
|
||||
error = true;
|
||||
}
|
||||
REQUIRE(error);
|
||||
}
|
||||
|
||||
SECTION("recursive_order_independent") {
|
||||
initialize_for_test(
|
||||
"FooGroup {"
|
||||
" value { "
|
||||
" group: @Foo.name "
|
||||
" foo: @Foo "
|
||||
" }"
|
||||
"}"
|
||||
"TestSite { \n"
|
||||
" value {\n"
|
||||
" name: \"good\"\n"
|
||||
" }\n"
|
||||
"}\n"
|
||||
"Foo { \n"
|
||||
" value {\n"
|
||||
" name: @TestSite.name "
|
||||
" }\n"
|
||||
"}\n"
|
||||
);
|
||||
|
||||
// In this test we mighe expect @Foo.name or @Foo to be evaluated first
|
||||
// But Foo is incomplete until @TestSite.name is evaluated.
|
||||
REQUIRE(get<FooGroup>().group() == "good");
|
||||
REQUIRE(get<FooGroup>().foo().name() == "good");
|
||||
}
|
||||
|
||||
SECTION("loop_test") {
|
||||
bool error = false;
|
||||
try {
|
||||
initialize_for_test(
|
||||
"Foo { \n"
|
||||
" value {\n"
|
||||
" name: @Foo.name "
|
||||
" }\n"
|
||||
"}\n");
|
||||
} catch(...) {
|
||||
error = true;
|
||||
}
|
||||
REQUIRE(error);
|
||||
}
|
||||
|
||||
SECTION("merge_test") {
|
||||
// Config used to go through a merge step for each file in a directory.
|
||||
// This would invalidate the memory held by the deferred value queue and cause
|
||||
// crashes and instability. This is to verify that we don't regress the new behavior.
|
||||
|
||||
HTTPServer server;
|
||||
std::string port = boost::lexical_cast<std::string>(server.port());
|
||||
std::string config_url = "http://localhost:" + port + "/";
|
||||
std::string response =
|
||||
"HTTP/1.0 200 OK\r\n"
|
||||
"Content-Type: text/plain\r\n\r\n";
|
||||
|
||||
server.add_response("/edge.conf", response,
|
||||
"Foo {\n"
|
||||
" value: {\n"
|
||||
" name: \"included_value\"\n"
|
||||
" id: 4096\n"
|
||||
" }}\n"
|
||||
"TestSite {"
|
||||
" value { "
|
||||
" name: @FooGroup.group" // reference to testkeys.conf
|
||||
" }"
|
||||
"}"
|
||||
);
|
||||
server.add_response("/testkeys.conf", response,
|
||||
"FooGroup {\n"
|
||||
" value {\n"
|
||||
" group: \"http_group\"\n"
|
||||
" foo {\n"
|
||||
" name: @Foo.name " // reference to edge.conf
|
||||
" id: 80\n"
|
||||
"}}}\n"
|
||||
);
|
||||
|
||||
server.start();
|
||||
initialize_for_test("include: \"" + config_url + "\"");
|
||||
server.stop();
|
||||
|
||||
const FooGroup& group = get<FooGroup>();
|
||||
const test::TestSite& site = get<test::TestSite>();
|
||||
|
||||
REQUIRE(group.foo().name() == "included_value");
|
||||
REQUIRE(site.name() == "http_group");
|
||||
}
|
||||
|
||||
SECTION("test_conversion") {
|
||||
initialize_for_test(
|
||||
"Foo {\n"
|
||||
" value: {\n"
|
||||
" name: @RuleRef.a_int \n"
|
||||
" id: @RuleRef.a_string "
|
||||
" }}\n"
|
||||
"Foo {\n"
|
||||
" rule: 'false' "
|
||||
" value: {\n"
|
||||
" name: @RuleRef.a_string \n"
|
||||
" id: @RuleRef.a_int "
|
||||
" }}\n"
|
||||
"RuleRef { "
|
||||
" value { "
|
||||
" a_string: '42' "
|
||||
" a_int: 99 "
|
||||
" }"
|
||||
"}"
|
||||
);
|
||||
|
||||
const Foo& foo = get<Foo>();
|
||||
REQUIRE(foo.name() == "99");
|
||||
REQUIRE(foo.id() == 42);
|
||||
}
|
||||
|
||||
SECTION("test_int") {
|
||||
initialize_for_test(
|
||||
"Foo {\n"
|
||||
" value: {\n"
|
||||
" id: @RuleRef.a_int "
|
||||
" }}\n"
|
||||
"RuleRef { "
|
||||
" value { "
|
||||
" a_string: 'good' "
|
||||
" a_int: 99 "
|
||||
" }"
|
||||
"}"
|
||||
);
|
||||
|
||||
const Foo& foo = get<Foo>();
|
||||
REQUIRE(foo.id() == 99);
|
||||
}
|
||||
|
||||
SECTION("test_repeated_to_repeated") {
|
||||
initialize_for_test(
|
||||
"FooList {\n"
|
||||
" value: {\n"
|
||||
" foo {\n"
|
||||
" name: 'good1' \n"
|
||||
" }\n"
|
||||
" foo {\n"
|
||||
" name: 'good2' \n"
|
||||
" }\n"
|
||||
" }}\n"
|
||||
"RuleRef { "
|
||||
" value { "
|
||||
" foox { "
|
||||
" name: 'original' "
|
||||
" }"
|
||||
" foox: @FooList.foo "
|
||||
" }"
|
||||
"}"
|
||||
);
|
||||
|
||||
const test::RuleRef& result = get<test::RuleRef>();
|
||||
|
||||
REQUIRE(result.foox_size() == 3);
|
||||
REQUIRE(result.foox(0).name() == "original");
|
||||
REQUIRE(result.foox(1).name() == "good1");
|
||||
REQUIRE(result.foox(2).name() == "good2");
|
||||
}
|
||||
|
||||
SECTION("test_repeated_after_key_rule") {
|
||||
initialize_for_test(
|
||||
"StringTable { \n"
|
||||
" value { \n"
|
||||
" entries: 'a' \n"
|
||||
" entries: 'b' \n"
|
||||
" } \n"
|
||||
"} \n"
|
||||
"FooList {\n"
|
||||
" value: {\n"
|
||||
" item {\n"
|
||||
" key: 'one' \n"
|
||||
" rule: \" 'a' in StringTable.entries\" \n"
|
||||
" foox { \n"
|
||||
" name: 'good1' \n"
|
||||
" }\n"
|
||||
" foox { \n"
|
||||
" name: 'good2' \n"
|
||||
" }\n"
|
||||
" }\n"
|
||||
" item {\n"
|
||||
" key: 'two' \n"
|
||||
" foox { \n"
|
||||
" name: 'bad1' \n"
|
||||
" }\n"
|
||||
" }\n"
|
||||
" }}\n"
|
||||
"RuleRef { "
|
||||
" value { "
|
||||
" foox { "
|
||||
" name: 'original' "
|
||||
" }"
|
||||
" foox: @FooList.item[one].foox "
|
||||
" }"
|
||||
"}"
|
||||
);
|
||||
|
||||
const test::RuleRef& result = get<test::RuleRef>();
|
||||
REQUIRE(result.foox_size() == 3);
|
||||
REQUIRE(result.foox(0).name() == "original");
|
||||
REQUIRE(result.foox(1).name() == "good1");
|
||||
REQUIRE(result.foox(2).name() == "good2");
|
||||
}
|
||||
|
||||
SECTION("test_repeated_after_key_rule2") {
|
||||
//This test fails on purpose to illustrate the frailty of the rule evaluation feature in 'keyed' list keys
|
||||
initialize_for_test(
|
||||
"TestSite {"
|
||||
" value {"
|
||||
" name: 'a' "
|
||||
" }"
|
||||
"}"
|
||||
"StringTable {"
|
||||
" value {"
|
||||
" entries: @TestSite.name "
|
||||
" entries: 'b' "
|
||||
" }"
|
||||
"}"
|
||||
"FooList {\n"
|
||||
" value: {\n"
|
||||
" item {\n"
|
||||
" key: 'one' \n"
|
||||
" rule: \"'a' in StringTable.entries\" \n"
|
||||
" foox { \n"
|
||||
" name: 'good1' \n"
|
||||
" }\n"
|
||||
" foox { \n"
|
||||
" name: 'good2' \n"
|
||||
" }\n"
|
||||
" }\n"
|
||||
" item {\n"
|
||||
" key: 'two' \n"
|
||||
" foox { \n"
|
||||
" name: 'bad1' \n"
|
||||
" }\n"
|
||||
" }\n"
|
||||
" }}\n"
|
||||
"RuleRef { "
|
||||
" value { "
|
||||
" foox { "
|
||||
" name: 'original' "
|
||||
" }"
|
||||
" foox: @FooList.item[one].foox "
|
||||
" }"
|
||||
"}"
|
||||
);
|
||||
|
||||
const test::RuleRef& result = get<test::RuleRef>();
|
||||
REQUIRE(result.foox_size() == 3);
|
||||
REQUIRE(result.foox(0).name() == "original");
|
||||
REQUIRE(result.foox(1).name() == "good1");
|
||||
REQUIRE(result.foox(2).name() == "good2");
|
||||
}
|
||||
|
||||
SECTION("test_repeated_after_key_rule3") {
|
||||
//This test fails on purpose to illustrate the frailty of the rule evaluation feature in 'keyed' list keys
|
||||
initialize_for_test(
|
||||
"RuleRef { "
|
||||
" value { "
|
||||
" foox { "
|
||||
" name: 'original' "
|
||||
" }"
|
||||
" foox: @FooList.item[one].foox "
|
||||
" }"
|
||||
"}"
|
||||
"TestSite {"
|
||||
" value {"
|
||||
" name: 'a' "
|
||||
" }"
|
||||
"}"
|
||||
"StringTable {"
|
||||
" value {"
|
||||
" entries: @TestSite.name "
|
||||
" entries: 'b' "
|
||||
" }"
|
||||
"}"
|
||||
"FooList {\n"
|
||||
" value: {\n"
|
||||
" item {\n"
|
||||
" key: 'one' \n"
|
||||
" rule: \"'a' in StringTable.entries\" \n"
|
||||
" foox { \n"
|
||||
" name: 'good1' \n"
|
||||
" }\n"
|
||||
" foox { \n"
|
||||
" name: 'good2' \n"
|
||||
" }\n"
|
||||
" }\n"
|
||||
" item {\n"
|
||||
" key: 'two' \n"
|
||||
" foox { \n"
|
||||
" name: 'bad1' \n"
|
||||
" }\n"
|
||||
" }\n"
|
||||
" }}\n"
|
||||
|
||||
);
|
||||
|
||||
const test::RuleRef& result = get<test::RuleRef>();
|
||||
//the order matters here, but seems to be deterministic
|
||||
REQUIRE(result.foox_size() == 1);
|
||||
}
|
||||
|
||||
// SECTION("test_repeated_after_key_rule_should_fail") {
|
||||
// //This test fails on purpose to illustrate the frailty of the rule evaluation feature in 'keyed' list keys
|
||||
// initialize_for_test(
|
||||
// "RuleRef { "
|
||||
// " value { "
|
||||
// " foox { "
|
||||
// " name: 'original' "
|
||||
// " }"
|
||||
// " foox: @FooList.item[one].foox "
|
||||
// " }"
|
||||
// "}"
|
||||
// "TestSite {"
|
||||
// " value {"
|
||||
// " name: 'a' "
|
||||
// " }"
|
||||
// "}"
|
||||
// "StringTable {"
|
||||
// " value {"
|
||||
// " entries: @TestSite.name "
|
||||
// " entries: 'b' "
|
||||
// " }"
|
||||
// "}"
|
||||
// "FooList {\n"
|
||||
// " value: {\n"
|
||||
// " item {\n"
|
||||
// " key: 'one' \n"
|
||||
// " rule: \"'a' in StringTable.entries\" \n"
|
||||
// " foox { \n"
|
||||
// " name: 'good1' \n"
|
||||
// " }\n"
|
||||
// " foox { \n"
|
||||
// " name: 'good2' \n"
|
||||
// " }\n"
|
||||
// " }\n"
|
||||
// " item {\n"
|
||||
// " key: 'two' \n"
|
||||
// " foox { \n"
|
||||
// " name: 'bad1' \n"
|
||||
// " }\n"
|
||||
// " }\n"
|
||||
// " }}\n"
|
||||
|
||||
// );
|
||||
|
||||
// const test::RuleRef& result = get<test::RuleRef>();
|
||||
// //this should fail
|
||||
// REQUIRE(result.foox_size() == 3);
|
||||
// }
|
||||
|
||||
SECTION("test_irrelevant_lookup") {
|
||||
// If a key references another key which is not present it should only be an error if the resulting key will ever be used.
|
||||
initialize_for_test(
|
||||
"FooList {\n"
|
||||
" value: {\n"
|
||||
" item {\n"
|
||||
" key: 'one' \n"
|
||||
" foox { \n"
|
||||
" name: 'good1' \n"
|
||||
" }\n"
|
||||
" foox { \n"
|
||||
" name: 'good2' \n"
|
||||
" }\n"
|
||||
" }\n"
|
||||
" item {\n"
|
||||
" key: 'two' \n"
|
||||
" foox { \n"
|
||||
" name: 'bad1' \n"
|
||||
" }\n"
|
||||
" }\n"
|
||||
" }}\n"
|
||||
"RuleRef { "
|
||||
" rule: 'false' "
|
||||
" value { "
|
||||
" foox { "
|
||||
" name: 'never used' "
|
||||
" }"
|
||||
" foox: @FooList.item[XXXXX].foox " // Invalid lookup
|
||||
" }"
|
||||
"}"
|
||||
"RuleRef { "
|
||||
" value { "
|
||||
" foox { "
|
||||
" name: 'original' "
|
||||
" }"
|
||||
" foox: @FooList.item[one].foox "
|
||||
" }"
|
||||
"}"
|
||||
);
|
||||
const test::RuleRef& result = get<test::RuleRef>();
|
||||
REQUIRE(result.foox_size() == 3);
|
||||
}
|
||||
|
||||
SECTION("macro_definition_order_test_hard") {
|
||||
// The $is_crusible test hard version
|
||||
// $macro1 tests Value2.x with rule about $macro2 before $macro2 is defined
|
||||
// Value2.x is an @reference of a 4th location
|
||||
initialize_for_test(
|
||||
"TestSite {"
|
||||
" value { name: 'cme_1u7_cert' }"
|
||||
"}"
|
||||
"Foo {"
|
||||
" rule: '$is_crucible'"
|
||||
" value { name: @TestSite.name }"
|
||||
"}"
|
||||
""
|
||||
"Foo {"
|
||||
" value { name: '' }"
|
||||
"}"
|
||||
""
|
||||
"macro {"
|
||||
" name: 'o2_cme_enabled'"
|
||||
" expression: \"Foo.name != ''\" "
|
||||
"}"
|
||||
""
|
||||
"macro {"
|
||||
" name: 'is_crucible'"
|
||||
" expression: 'true'"
|
||||
"}"
|
||||
);
|
||||
|
||||
REQUIRE(get<Foo>().name() == "cme_1u7_cert");
|
||||
}
|
||||
|
||||
reset();
|
||||
}
|
||||
|
||||
}
|
||||
Executable
+578
@@ -0,0 +1,578 @@
|
||||
#include "lib/utils/TempFile.h"
|
||||
|
||||
#include "../config.h"
|
||||
#include "../ConfigurationState.h"
|
||||
#include "../ConfigurationException.h"
|
||||
#include "lib/expression/ParserExceptions.h"
|
||||
#include "lib/utils/bts_assert.h"
|
||||
#include "lib/utils/is_unittest_environment.h"
|
||||
|
||||
#include "HTTPServer.h"
|
||||
|
||||
#include "lib/config/invalid/invalid.pb.h"
|
||||
#include "lib/config/protos/system.pb.h"
|
||||
#include "lib/config/protos/testkeys.pb.h"
|
||||
|
||||
#include <boost/filesystem.hpp>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
|
||||
#define URDL_HEADER_ONLY 1
|
||||
#define URDL_DISALE_SSL 1
|
||||
#include <urdl/url.hpp>
|
||||
#include <urdl/test/http_server.hpp>
|
||||
#include <catch/catch.h>
|
||||
|
||||
using namespace bts::config;
|
||||
using namespace bts::config::internal;
|
||||
namespace proto = google::protobuf;
|
||||
|
||||
using bts::config::test::Foo;
|
||||
using bts::config::test::FooGroup;
|
||||
using bts::config::test::StringTable;
|
||||
|
||||
namespace bts {
|
||||
TEST_CASE("Configuration Tests","[config]") {
|
||||
|
||||
bts::utils::internal::force_unittest_environment();
|
||||
|
||||
SECTION("basic_get_value_test")
|
||||
{
|
||||
initialize_for_test(
|
||||
"Foo { \n"
|
||||
" rule: \"true\"\n"
|
||||
" value {\n"
|
||||
" name: \"Name A\"\n"
|
||||
" id: 65\n"
|
||||
" email: \"test@example.com\"\n"
|
||||
" }\n"
|
||||
"}\n");
|
||||
|
||||
const Foo& foo = get<Foo>();
|
||||
|
||||
REQUIRE(foo.name() == "Name A");
|
||||
REQUIRE(foo.id() == 65);
|
||||
REQUIRE(foo.email().Get(0) == "test@example.com");
|
||||
}
|
||||
|
||||
SECTION("default_value_test")
|
||||
{
|
||||
initialize_for_test(""); // Only loads defaults.conf
|
||||
|
||||
// Should load a Foo from testkeys.conf
|
||||
const Foo& foo = get<Foo>();
|
||||
REQUIRE(foo.name() == "Blue Foo"); // from testkeys.proto
|
||||
REQUIRE(foo.id() == 1234); // from testkeys.proto
|
||||
REQUIRE(foo.email().size() > 0);
|
||||
REQUIRE(foo.email().Get(0) == "default@example.com"); // from testkeys.conf
|
||||
}
|
||||
|
||||
SECTION("default_include_test")
|
||||
{
|
||||
// test defaults.conf with an include
|
||||
}
|
||||
|
||||
SECTION("invalid_key_type_test")
|
||||
{
|
||||
// Load an initialize with no files - OK all values default
|
||||
|
||||
const Foo& foo = get<Foo>(); // OK
|
||||
REQUIRE(foo.name() == "Blue Foo");
|
||||
|
||||
bool error = false;
|
||||
try
|
||||
{
|
||||
get<config::test::InvalidMessageType>(); // BAD
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
error = true;
|
||||
}
|
||||
REQUIRE(error == true);
|
||||
}
|
||||
|
||||
SECTION("invalid_config_test2")
|
||||
{
|
||||
utils::TempFile config_b;
|
||||
|
||||
*config_b.out() <<
|
||||
"Foo {\n"
|
||||
" value { \n"
|
||||
" name: \"bob\"\n"
|
||||
" id: 7319 \n"
|
||||
" }";
|
||||
|
||||
bool error = false;
|
||||
try
|
||||
{
|
||||
initialize_for_test("include: \"" + config_b.path() + "\"", false);
|
||||
}
|
||||
catch(const ConfigurationException& err)
|
||||
{
|
||||
std::string what = err.what();
|
||||
bts_assert(what.find("Expected identifier.") != std::string::npos);
|
||||
error = true;
|
||||
}
|
||||
REQUIRE(error == true);
|
||||
|
||||
}
|
||||
|
||||
// Tests that we can load using a File:/// url
|
||||
// Tests complex value load
|
||||
SECTION("file_url_test")
|
||||
{
|
||||
utils::TempFile config_a;
|
||||
utils::TempFile config_b;
|
||||
|
||||
*config_a.out() << "include: \"" << config_b.path() << "\"" << std::endl <<
|
||||
"Foo { \n"
|
||||
" rule: \"false\"\n"
|
||||
" value {\n"
|
||||
" name: \"Name A\"\n"
|
||||
" id: 65\n"
|
||||
" email: \"A@bluecg.com\"\n"
|
||||
" }\n"
|
||||
"}\n";
|
||||
|
||||
*config_b.out() <<
|
||||
"Foo {\n"
|
||||
" rule: \"true\"\n"
|
||||
" value {\n"
|
||||
" name: \"Name B\"\n"
|
||||
" id: 66 "
|
||||
" email: \"A@bluecg.com\" \n"
|
||||
" }}";
|
||||
|
||||
|
||||
// Get key Foo without loading any config files - this will show the default value
|
||||
Foo foo = bts::config::get<Foo>();
|
||||
|
||||
REQUIRE(foo.name() == "Blue Foo");
|
||||
REQUIRE(foo.id() == 1234);
|
||||
|
||||
// Parse the config file and file:/// include
|
||||
initialize_for_test("include: \"" + config_a.path() + "\"");
|
||||
|
||||
// Get the new value of Foo - this time it will come from config_b
|
||||
foo = bts::config::get<Foo>();
|
||||
REQUIRE(foo.name() == "Name B");
|
||||
REQUIRE(foo.id() == 66);
|
||||
}
|
||||
|
||||
SECTION("http_test")
|
||||
{
|
||||
HTTPServer server;
|
||||
std::string port = boost::lexical_cast<std::string>(server.port());
|
||||
std::string path = "/edge.conf";
|
||||
std::string response =
|
||||
"HTTP/1.0 200 OK\r\n"
|
||||
"Content-Type: text/plain\r\n\r\n";
|
||||
std::string content =
|
||||
"FooGroup {\n"
|
||||
" rule: \"true\"\n"
|
||||
" value {\n"
|
||||
" group: \"http_group\"\n"
|
||||
" foo {\n"
|
||||
" name: \"http\"\n"
|
||||
" id: 80\n"
|
||||
"}}}\n";
|
||||
|
||||
server.add_response(path, response, content);
|
||||
server.start();
|
||||
std::string config_url = "http://127.0.0.1:" + port;
|
||||
|
||||
// Initialize with a configuration which references the http url
|
||||
initialize_for_test("include: \"" + config_url + "\"");
|
||||
|
||||
server.stop();
|
||||
|
||||
const FooGroup& foogrp = get<FooGroup>();
|
||||
|
||||
REQUIRE(foogrp.group() == "http_group");
|
||||
REQUIRE(foogrp.foo().name() == "http");
|
||||
REQUIRE(foogrp.foo().id() == 80);
|
||||
REQUIRE(get<System>().config_host() == "127.0.0.1");
|
||||
}
|
||||
|
||||
SECTION("http_folder_test")
|
||||
{
|
||||
HTTPServer server;
|
||||
std::string port = boost::lexical_cast<std::string>(server.port());
|
||||
std::string config_url = "http://localhost:" + port + "/";
|
||||
std::string response =
|
||||
"HTTP/1.0 200 OK\r\n"
|
||||
"Content-Type: text/plain\r\n\r\n";
|
||||
|
||||
server.add_response("/edge.conf", response, "include: \"" + config_url + "other/\"");
|
||||
server.add_response("/testkeys.conf", response,
|
||||
"FooGroup {\n"
|
||||
" rule: \"true\"\n"
|
||||
" value {\n"
|
||||
" group: \"http_group\"\n"
|
||||
" foo {\n"
|
||||
" name: \"http\"\n"
|
||||
" id: 80\n"
|
||||
"}}}\n");
|
||||
|
||||
server.add_response("/other/edge.conf", response,
|
||||
"Foo {\n"
|
||||
" rule: \"true\"\n"
|
||||
" value: {\n"
|
||||
" name: \"included_value\"\n"
|
||||
" id: 4096\n"
|
||||
" }}\n");
|
||||
|
||||
|
||||
server.start();
|
||||
initialize_for_test("include: \"" + config_url + "\"");
|
||||
|
||||
server.stop();
|
||||
|
||||
const FooGroup& foogrp = get<FooGroup>();
|
||||
|
||||
REQUIRE(foogrp.group() == "http_group");
|
||||
REQUIRE(foogrp.foo().name() == "http");
|
||||
REQUIRE(foogrp.foo().id() == 80);
|
||||
|
||||
REQUIRE(get<Foo>().name() == "included_value");
|
||||
REQUIRE(get<Foo>().id() == 4096);
|
||||
}
|
||||
|
||||
|
||||
SECTION("test_rules")
|
||||
{
|
||||
initialize_for_test(
|
||||
"StringTable {\n"
|
||||
" value { \n"
|
||||
" entries: [\"foo\", \"bar\", \"baz\"] \n"
|
||||
" }\n"
|
||||
" }\n"
|
||||
"RuleRef { \n"
|
||||
" # use this rule of StringTable has a cow \n"
|
||||
" rule: \"'cow' in StringTable.entries\" \n"
|
||||
" value { \n"
|
||||
" a_string: \"AAA\"\n"
|
||||
" a_int: -1\n"
|
||||
" }\n"
|
||||
"}\n"
|
||||
"RuleRef { \n"
|
||||
" rule: \"'baz' in StringTable.entries\" \n"
|
||||
" value { \n"
|
||||
" a_string: \"BBB\"\n"
|
||||
" a_int: 99\n"
|
||||
" }\n"
|
||||
"}\n"
|
||||
"Foo { \n"
|
||||
" rule: \"RuleRef.a_int == 789\"\n"
|
||||
" value {\n"
|
||||
" name: \"A\"\n"
|
||||
" }\n"
|
||||
"}\n"
|
||||
"Foo { \n"
|
||||
" rule: \"RuleRef.a_string == 'BBB'\"\n"
|
||||
" value {\n"
|
||||
" name: \"B\"\n"
|
||||
" }\n"
|
||||
"}\n"
|
||||
);
|
||||
|
||||
|
||||
// What should happen:
|
||||
// Foo A
|
||||
// eval rule
|
||||
// find RuleRef AAA
|
||||
// eval rule
|
||||
// fail - StringTable.entries does not have 'cow'
|
||||
// find RuleRef BBB
|
||||
// eval rule
|
||||
// success
|
||||
// Fail - RuleRef.a_int != 789
|
||||
// Foo B
|
||||
// eval rule
|
||||
// - same as above
|
||||
// success a_string == 'BBB'
|
||||
// return Foo B
|
||||
|
||||
const Foo& foo = get<Foo>();
|
||||
REQUIRE(foo.name() == "B");
|
||||
}
|
||||
|
||||
|
||||
|
||||
SECTION("test_recursive_rules")
|
||||
{
|
||||
initialize_for_test(
|
||||
"StringTable {\n"
|
||||
" rule: \"Foo.name == 'foo'\"\n"
|
||||
" value { \n"
|
||||
" entries: [\"foo\", \"bar\", \"baz\"] \n"
|
||||
" }\n"
|
||||
" }\n"
|
||||
"RuleRef { \n"
|
||||
" rule: \"'foo' in StringTable.entries\" \n"
|
||||
" value { \n"
|
||||
" a_string: \"AAA\"\n"
|
||||
" a_int: -1\n"
|
||||
" }\n"
|
||||
"}\n"
|
||||
"Foo { \n"
|
||||
" rule: \"RuleRef.a_string == 'BBB'\"\n"
|
||||
" value {\n"
|
||||
" name: \"foo\"\n"
|
||||
" }\n"
|
||||
"}\n"
|
||||
);
|
||||
|
||||
// Foo cannot be queried because RuleRef's rule requests StringTable which requests RuleRef
|
||||
bool error = false;
|
||||
try
|
||||
{
|
||||
get<Foo>();
|
||||
}
|
||||
catch(const expression::RecursivePropertyGetException&)
|
||||
{
|
||||
error = true;
|
||||
}
|
||||
REQUIRE(error);
|
||||
}
|
||||
|
||||
SECTION("test_nested_properties")
|
||||
{
|
||||
initialize_for_test(
|
||||
"RuleRef { \n"
|
||||
" value { \n"
|
||||
" nested {\n"
|
||||
" list_int: [7,8,9] \n"
|
||||
" nested {\n"
|
||||
" a_string: 'ABC' \n"
|
||||
" }\n"
|
||||
" }\n"
|
||||
" }\n"
|
||||
"}\n"
|
||||
"Foo { \n"
|
||||
" rule: \"RuleRef.nested.nested.a_string == 'ABC' and 9 in RuleRef.nested.list_int\"\n"
|
||||
" value {\n"
|
||||
" name: \"foo\"\n"
|
||||
" }\n"
|
||||
"}\n"
|
||||
);
|
||||
|
||||
REQUIRE(get<Foo>().name() == "foo");
|
||||
}
|
||||
|
||||
SECTION("built_in_properties_test")
|
||||
{
|
||||
initialize_for_test(
|
||||
"Foo { \n"
|
||||
" rule: \"System.unittest_environment == true \"\n"
|
||||
" value {\n"
|
||||
" name: \"unit tests\"\n"
|
||||
" }\n"
|
||||
"}\n"
|
||||
);
|
||||
|
||||
REQUIRE(get<Foo>().name() == "unit tests");
|
||||
}
|
||||
|
||||
SECTION("nonbreaking_space_test")
|
||||
{
|
||||
bool parse_error = false;
|
||||
try
|
||||
{
|
||||
initialize_for_test(
|
||||
"Foo { "
|
||||
" value {\xA0\xA0 "
|
||||
" name: \"valid name\""
|
||||
" \xA0 }"
|
||||
"} ", false);
|
||||
}
|
||||
catch(const bts::config::ConfigurationException)
|
||||
{
|
||||
parse_error = true;
|
||||
}
|
||||
REQUIRE(parse_error);
|
||||
}
|
||||
|
||||
SECTION("macro_bool_test")
|
||||
{
|
||||
initialize_for_test(
|
||||
"macro"
|
||||
"{"
|
||||
" name: \"bool\""
|
||||
" expression: \"'c' in ['a', 'b', 'c', 'd']\""
|
||||
"}"
|
||||
""
|
||||
"Foo"
|
||||
"{"
|
||||
" rule: \"$bool\""
|
||||
" value {"
|
||||
" name: 'good'"
|
||||
" }"
|
||||
"}"
|
||||
""
|
||||
"Foo"
|
||||
"{"
|
||||
" value {"
|
||||
" name: 'bad'"
|
||||
" }"
|
||||
"}"
|
||||
);
|
||||
|
||||
REQUIRE(config::get<Foo>().name() == "good");
|
||||
|
||||
}
|
||||
|
||||
SECTION("macro_list_test")
|
||||
{
|
||||
initialize_for_test(
|
||||
"macro"
|
||||
"{"
|
||||
" name: \"list\""
|
||||
" expression: \"['a', 'b', 'c', 'd']\""
|
||||
"}"
|
||||
""
|
||||
"Foo"
|
||||
"{"
|
||||
" rule: \"'a' in $list\""
|
||||
" value {"
|
||||
" name: 'good'"
|
||||
" }"
|
||||
"}"
|
||||
""
|
||||
"Foo"
|
||||
"{"
|
||||
" value {"
|
||||
" name: 'bad'"
|
||||
" }"
|
||||
"}"
|
||||
);
|
||||
|
||||
REQUIRE(config::get<Foo>().name() == "good");
|
||||
}
|
||||
|
||||
SECTION("fallback_test") {
|
||||
//HTTPServer main;
|
||||
HTTPServer fallback;
|
||||
//std::string main_url = "http://localhost:" + boost::lexical_cast<std::string>(main.port()) + "/";
|
||||
std::string main_url = "http://does_not_exist:12345/";
|
||||
//main.stop();
|
||||
std::string fallback_url = "http://127.0.0.1:" + boost::lexical_cast<std::string>(fallback.port()) + "/";
|
||||
std::string response =
|
||||
"HTTP/1.0 200 OK\r\n"
|
||||
"Content-Type: text/plain\r\n\r\n";
|
||||
|
||||
std::string content =
|
||||
"FooGroup {\n"
|
||||
" value {\n"
|
||||
" group: \"http_group\"\n"
|
||||
" foo {\n"
|
||||
" name: \"http\"\n"
|
||||
" id: 80\n"
|
||||
"}}}\n";
|
||||
|
||||
fallback.add_response("/edge.conf", response, content);
|
||||
|
||||
fallback.start();
|
||||
initialize_for_test(
|
||||
"include: '" + main_url + "'\n"
|
||||
"fallback: '" + fallback_url + "'\n",false
|
||||
);
|
||||
fallback.stop();
|
||||
|
||||
REQUIRE(get<FooGroup>().foo().name() == "http");
|
||||
REQUIRE(get<FooGroup>().foo().id() == 80);
|
||||
|
||||
}
|
||||
|
||||
SECTION("macro_definition_order_test") {
|
||||
// The $is_crusible test
|
||||
// o2_cme_enabled depends on Foo which has a rule which depends on is_crucible.
|
||||
// Eager evaluation caused a bug which would cause loading o2_cme_enabled to set is_crucible false. Case 3993
|
||||
initialize_for_test(
|
||||
"Foo {"
|
||||
" rule: '$is_crucible'"
|
||||
" value { name: 'cme_1u7_cert' }"
|
||||
"}"
|
||||
""
|
||||
"Foo {"
|
||||
" value { name: '' }"
|
||||
"}"
|
||||
""
|
||||
"macro {"
|
||||
" name: 'o2_cme_enabled'"
|
||||
" expression: \"Foo.name != ''\" "
|
||||
"}"
|
||||
""
|
||||
"macro {"
|
||||
" name: 'is_crucible'"
|
||||
" expression: 'true'"
|
||||
"}"
|
||||
);
|
||||
|
||||
REQUIRE(get<Foo>().name() == "cme_1u7_cert");
|
||||
}
|
||||
|
||||
SECTION("repeated_value_order_preserved") {
|
||||
initialize_for_test(
|
||||
"Foo {"
|
||||
" value { name: 'edge-eharding' id: 80 }"
|
||||
"}"
|
||||
"StringTable {"
|
||||
" value {"
|
||||
" entries: 'http://'"
|
||||
" entries: @Foo.name"
|
||||
" entries: ':'"
|
||||
" entries: @Foo.id"
|
||||
" entries: '/risk'"
|
||||
" }"
|
||||
"}");
|
||||
std::string result;
|
||||
for (const auto& part : get<StringTable>().entries()) {
|
||||
result += part;
|
||||
}
|
||||
REQUIRE(result == "http://edge-eharding:80/risk");
|
||||
}
|
||||
|
||||
SECTION("string_concat_test") {
|
||||
initialize_for_test(
|
||||
"Ports {\n"
|
||||
" value { \n"
|
||||
" config_port: 80 \n"
|
||||
" }\n"
|
||||
"}\n"
|
||||
"RuleRef { \n"
|
||||
" value { \n"
|
||||
" a_string: \"localhost\"\n"
|
||||
" }\n"
|
||||
"}\n"
|
||||
"macro{\n"
|
||||
" name: 'list'\n"
|
||||
" expression: \"['http://', RuleRef.a_string, ':', Ports.config_port, '/risk']\"\n"
|
||||
"}"
|
||||
"StringTable {\n"
|
||||
"value {\n"
|
||||
" entries: 'http://'\n"
|
||||
" entries: @RuleRef.a_string\n"
|
||||
" entries: ':'\n"
|
||||
" entries: @Ports.config_port\n"
|
||||
" entries: '/risk'\n"
|
||||
"}}\n"
|
||||
"Foo { \n"
|
||||
" value {\n"
|
||||
" name: $list\n"
|
||||
" url: @StringTable.entries \n"
|
||||
" }\n"
|
||||
"}"
|
||||
);
|
||||
|
||||
auto foo = config::get<Foo>();
|
||||
auto expected = "http://localhost:80/risk";
|
||||
REQUIRE(foo.name() == expected);
|
||||
REQUIRE(foo.url() == expected);
|
||||
}
|
||||
|
||||
reset();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,878 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// https://developers.google.com/protocol-buffers/
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// from google3/strings/strutil.h
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_STUBS_STRUTIL_H__
|
||||
#define GOOGLE_PROTOBUF_STUBS_STRUTIL_H__
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <vector>
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
#include <google/protobuf/stubs/stringpiece.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#define strtoll _strtoi64
|
||||
#define strtoull _strtoui64
|
||||
#elif defined(__DECCXX) && defined(__osf__)
|
||||
// HP C++ on Tru64 does not have strtoll, but strtol is already 64-bit.
|
||||
#define strtoll strtol
|
||||
#define strtoull strtoul
|
||||
#endif
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// ascii_isalnum()
|
||||
// Check if an ASCII character is alphanumeric. We can't use ctype's
|
||||
// isalnum() because it is affected by locale. This function is applied
|
||||
// to identifiers in the protocol buffer language, not to natural-language
|
||||
// strings, so locale should not be taken into account.
|
||||
// ascii_isdigit()
|
||||
// Like above, but only accepts digits.
|
||||
// ascii_isspace()
|
||||
// Check if the character is a space character.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
inline bool ascii_isalnum(char c) {
|
||||
return ('a' <= c && c <= 'z') ||
|
||||
('A' <= c && c <= 'Z') ||
|
||||
('0' <= c && c <= '9');
|
||||
}
|
||||
|
||||
inline bool ascii_isdigit(char c) {
|
||||
return ('0' <= c && c <= '9');
|
||||
}
|
||||
|
||||
inline bool ascii_isspace(char c) {
|
||||
return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' ||
|
||||
c == '\r';
|
||||
}
|
||||
|
||||
inline bool ascii_isupper(char c) {
|
||||
return c >= 'A' && c <= 'Z';
|
||||
}
|
||||
|
||||
inline bool ascii_islower(char c) {
|
||||
return c >= 'a' && c <= 'z';
|
||||
}
|
||||
|
||||
inline char ascii_toupper(char c) {
|
||||
return ascii_islower(c) ? c - ('a' - 'A') : c;
|
||||
}
|
||||
|
||||
inline char ascii_tolower(char c) {
|
||||
return ascii_isupper(c) ? c + ('a' - 'A') : c;
|
||||
}
|
||||
|
||||
inline int hex_digit_to_int(char c) {
|
||||
/* Assume ASCII. */
|
||||
int x = static_cast<unsigned char>(c);
|
||||
if (x > '9') {
|
||||
x += 9;
|
||||
}
|
||||
return x & 0xf;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// HasPrefixString()
|
||||
// Check if a string begins with a given prefix.
|
||||
// StripPrefixString()
|
||||
// Given a string and a putative prefix, returns the string minus the
|
||||
// prefix string if the prefix matches, otherwise the original
|
||||
// string.
|
||||
// ----------------------------------------------------------------------
|
||||
inline bool HasPrefixString(const string& str,
|
||||
const string& prefix) {
|
||||
return str.size() >= prefix.size() &&
|
||||
str.compare(0, prefix.size(), prefix) == 0;
|
||||
}
|
||||
|
||||
inline string StripPrefixString(const string& str, const string& prefix) {
|
||||
if (HasPrefixString(str, prefix)) {
|
||||
return str.substr(prefix.size());
|
||||
} else {
|
||||
return str;
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// HasSuffixString()
|
||||
// Return true if str ends in suffix.
|
||||
// StripSuffixString()
|
||||
// Given a string and a putative suffix, returns the string minus the
|
||||
// suffix string if the suffix matches, otherwise the original
|
||||
// string.
|
||||
// ----------------------------------------------------------------------
|
||||
inline bool HasSuffixString(const string& str,
|
||||
const string& suffix) {
|
||||
return str.size() >= suffix.size() &&
|
||||
str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
|
||||
}
|
||||
|
||||
inline string StripSuffixString(const string& str, const string& suffix) {
|
||||
if (HasSuffixString(str, suffix)) {
|
||||
return str.substr(0, str.size() - suffix.size());
|
||||
} else {
|
||||
return str;
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// ReplaceCharacters
|
||||
// Replaces any occurrence of the character 'remove' (or the characters
|
||||
// in 'remove') with the character 'replacewith'.
|
||||
// Good for keeping html characters or protocol characters (\t) out
|
||||
// of places where they might cause a problem.
|
||||
// StripWhitespace
|
||||
// Removes whitespaces from both ends of the given string.
|
||||
// ----------------------------------------------------------------------
|
||||
LIBPROTOBUF_EXPORT void ReplaceCharacters(string* s, const char* remove,
|
||||
char replacewith);
|
||||
LIBPROTOBUF_EXPORT void StripString(string* s, const char* remove,
|
||||
char replacewith);
|
||||
|
||||
LIBPROTOBUF_EXPORT void StripWhitespace(string* s);
|
||||
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// LowerString()
|
||||
// UpperString()
|
||||
// ToUpper()
|
||||
// Convert the characters in "s" to lowercase or uppercase. ASCII-only:
|
||||
// these functions intentionally ignore locale because they are applied to
|
||||
// identifiers used in the Protocol Buffer language, not to natural-language
|
||||
// strings.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
inline void LowerString(string * s) {
|
||||
string::iterator end = s->end();
|
||||
for (string::iterator i = s->begin(); i != end; ++i) {
|
||||
// tolower() changes based on locale. We don't want this!
|
||||
if ('A' <= *i && *i <= 'Z') *i += 'a' - 'A';
|
||||
}
|
||||
}
|
||||
|
||||
inline void UpperString(string * s) {
|
||||
string::iterator end = s->end();
|
||||
for (string::iterator i = s->begin(); i != end; ++i) {
|
||||
// toupper() changes based on locale. We don't want this!
|
||||
if ('a' <= *i && *i <= 'z') *i += 'A' - 'a';
|
||||
}
|
||||
}
|
||||
|
||||
inline string ToUpper(const string& s) {
|
||||
string out = s;
|
||||
UpperString(&out);
|
||||
return out;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// StringReplace()
|
||||
// Give me a string and two patterns "old" and "new", and I replace
|
||||
// the first instance of "old" in the string with "new", if it
|
||||
// exists. RETURN a new string, regardless of whether the replacement
|
||||
// happened or not.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
LIBPROTOBUF_EXPORT string StringReplace(const string& s, const string& oldsub,
|
||||
const string& newsub, bool replace_all);
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// SplitStringUsing()
|
||||
// Split a string using a character delimiter. Append the components
|
||||
// to 'result'. If there are consecutive delimiters, this function skips
|
||||
// over all of them.
|
||||
// ----------------------------------------------------------------------
|
||||
LIBPROTOBUF_EXPORT void SplitStringUsing(const string& full, const char* delim,
|
||||
vector<string>* res);
|
||||
|
||||
// Split a string using one or more byte delimiters, presented
|
||||
// as a nul-terminated c string. Append the components to 'result'.
|
||||
// If there are consecutive delimiters, this function will return
|
||||
// corresponding empty strings. If you want to drop the empty
|
||||
// strings, try SplitStringUsing().
|
||||
//
|
||||
// If "full" is the empty string, yields an empty string as the only value.
|
||||
// ----------------------------------------------------------------------
|
||||
LIBPROTOBUF_EXPORT void SplitStringAllowEmpty(const string& full,
|
||||
const char* delim,
|
||||
vector<string>* result);
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Split()
|
||||
// Split a string using a character delimiter.
|
||||
// ----------------------------------------------------------------------
|
||||
inline vector<string> Split(
|
||||
const string& full, const char* delim, bool skip_empty = true) {
|
||||
vector<string> result;
|
||||
if (skip_empty) {
|
||||
SplitStringUsing(full, delim, &result);
|
||||
} else {
|
||||
SplitStringAllowEmpty(full, delim, &result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// JoinStrings()
|
||||
// These methods concatenate a vector of strings into a C++ string, using
|
||||
// the C-string "delim" as a separator between components. There are two
|
||||
// flavors of the function, one flavor returns the concatenated string,
|
||||
// another takes a pointer to the target string. In the latter case the
|
||||
// target string is cleared and overwritten.
|
||||
// ----------------------------------------------------------------------
|
||||
LIBPROTOBUF_EXPORT void JoinStrings(const vector<string>& components,
|
||||
const char* delim, string* result);
|
||||
|
||||
inline string JoinStrings(const vector<string>& components,
|
||||
const char* delim) {
|
||||
string result;
|
||||
JoinStrings(components, delim, &result);
|
||||
return result;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// UnescapeCEscapeSequences()
|
||||
// Copies "source" to "dest", rewriting C-style escape sequences
|
||||
// -- '\n', '\r', '\\', '\ooo', etc -- to their ASCII
|
||||
// equivalents. "dest" must be sufficiently large to hold all
|
||||
// the characters in the rewritten string (i.e. at least as large
|
||||
// as strlen(source) + 1 should be safe, since the replacements
|
||||
// are always shorter than the original escaped sequences). It's
|
||||
// safe for source and dest to be the same. RETURNS the length
|
||||
// of dest.
|
||||
//
|
||||
// It allows hex sequences \xhh, or generally \xhhhhh with an
|
||||
// arbitrary number of hex digits, but all of them together must
|
||||
// specify a value of a single byte (e.g. \x0045 is equivalent
|
||||
// to \x45, and \x1234 is erroneous).
|
||||
//
|
||||
// It also allows escape sequences of the form \uhhhh (exactly four
|
||||
// hex digits, upper or lower case) or \Uhhhhhhhh (exactly eight
|
||||
// hex digits, upper or lower case) to specify a Unicode code
|
||||
// point. The dest array will contain the UTF8-encoded version of
|
||||
// that code-point (e.g., if source contains \u2019, then dest will
|
||||
// contain the three bytes 0xE2, 0x80, and 0x99).
|
||||
//
|
||||
// Errors: In the first form of the call, errors are reported with
|
||||
// LOG(ERROR). The same is true for the second form of the call if
|
||||
// the pointer to the string vector is NULL; otherwise, error
|
||||
// messages are stored in the vector. In either case, the effect on
|
||||
// the dest array is not defined, but rest of the source will be
|
||||
// processed.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
LIBPROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest);
|
||||
LIBPROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest,
|
||||
vector<string> *errors);
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// UnescapeCEscapeString()
|
||||
// This does the same thing as UnescapeCEscapeSequences, but creates
|
||||
// a new string. The caller does not need to worry about allocating
|
||||
// a dest buffer. This should be used for non performance critical
|
||||
// tasks such as printing debug messages. It is safe for src and dest
|
||||
// to be the same.
|
||||
//
|
||||
// The second call stores its errors in a supplied string vector.
|
||||
// If the string vector pointer is NULL, it reports the errors with LOG().
|
||||
//
|
||||
// In the first and second calls, the length of dest is returned. In the
|
||||
// the third call, the new string is returned.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
LIBPROTOBUF_EXPORT int UnescapeCEscapeString(const string& src, string* dest);
|
||||
LIBPROTOBUF_EXPORT int UnescapeCEscapeString(const string& src, string* dest,
|
||||
vector<string> *errors);
|
||||
LIBPROTOBUF_EXPORT string UnescapeCEscapeString(const string& src);
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// CEscape()
|
||||
// Escapes 'src' using C-style escape sequences and returns the resulting
|
||||
// string.
|
||||
//
|
||||
// Escaped chars: \n, \r, \t, ", ', \, and !isprint().
|
||||
// ----------------------------------------------------------------------
|
||||
LIBPROTOBUF_EXPORT string CEscape(const string& src);
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// CEscapeAndAppend()
|
||||
// Escapes 'src' using C-style escape sequences, and appends the escaped
|
||||
// string to 'dest'.
|
||||
// ----------------------------------------------------------------------
|
||||
LIBPROTOBUF_EXPORT void CEscapeAndAppend(StringPiece src, string* dest);
|
||||
|
||||
namespace strings {
|
||||
// Like CEscape() but does not escape bytes with the upper bit set.
|
||||
LIBPROTOBUF_EXPORT string Utf8SafeCEscape(const string& src);
|
||||
|
||||
// Like CEscape() but uses hex (\x) escapes instead of octals.
|
||||
LIBPROTOBUF_EXPORT string CHexEscape(const string& src);
|
||||
} // namespace strings
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// strto32()
|
||||
// strtou32()
|
||||
// strto64()
|
||||
// strtou64()
|
||||
// Architecture-neutral plug compatible replacements for strtol() and
|
||||
// strtoul(). Long's have different lengths on ILP-32 and LP-64
|
||||
// platforms, so using these is safer, from the point of view of
|
||||
// overflow behavior, than using the standard libc functions.
|
||||
// ----------------------------------------------------------------------
|
||||
LIBPROTOBUF_EXPORT int32 strto32_adaptor(const char *nptr, char **endptr,
|
||||
int base);
|
||||
LIBPROTOBUF_EXPORT uint32 strtou32_adaptor(const char *nptr, char **endptr,
|
||||
int base);
|
||||
|
||||
inline int32 strto32(const char *nptr, char **endptr, int base) {
|
||||
if (sizeof(int32) == sizeof(long))
|
||||
return strtol(nptr, endptr, base);
|
||||
else
|
||||
return strto32_adaptor(nptr, endptr, base);
|
||||
}
|
||||
|
||||
inline uint32 strtou32(const char *nptr, char **endptr, int base) {
|
||||
if (sizeof(uint32) == sizeof(unsigned long))
|
||||
return strtoul(nptr, endptr, base);
|
||||
else
|
||||
return strtou32_adaptor(nptr, endptr, base);
|
||||
}
|
||||
|
||||
// For now, long long is 64-bit on all the platforms we care about, so these
|
||||
// functions can simply pass the call to strto[u]ll.
|
||||
inline int64 strto64(const char *nptr, char **endptr, int base) {
|
||||
GOOGLE_COMPILE_ASSERT(sizeof(int64) == sizeof(long long),
|
||||
sizeof_int64_is_not_sizeof_long_long);
|
||||
return strtoll(nptr, endptr, base);
|
||||
}
|
||||
|
||||
inline uint64 strtou64(const char *nptr, char **endptr, int base) {
|
||||
GOOGLE_COMPILE_ASSERT(sizeof(uint64) == sizeof(unsigned long long),
|
||||
sizeof_uint64_is_not_sizeof_long_long);
|
||||
return strtoull(nptr, endptr, base);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// safe_strtob()
|
||||
// safe_strto32()
|
||||
// safe_strtou32()
|
||||
// safe_strto64()
|
||||
// safe_strtou64()
|
||||
// safe_strtof()
|
||||
// safe_strtod()
|
||||
// ----------------------------------------------------------------------
|
||||
LIBPROTOBUF_EXPORT bool safe_strtob(StringPiece str, bool* value);
|
||||
|
||||
LIBPROTOBUF_EXPORT bool safe_strto32(const string& str, int32* value);
|
||||
LIBPROTOBUF_EXPORT bool safe_strtou32(const string& str, uint32* value);
|
||||
inline bool safe_strto32(const char* str, int32* value) {
|
||||
return safe_strto32(string(str), value);
|
||||
}
|
||||
inline bool safe_strto32(StringPiece str, int32* value) {
|
||||
return safe_strto32(str.ToString(), value);
|
||||
}
|
||||
inline bool safe_strtou32(const char* str, uint32* value) {
|
||||
return safe_strtou32(string(str), value);
|
||||
}
|
||||
inline bool safe_strtou32(StringPiece str, uint32* value) {
|
||||
return safe_strtou32(str.ToString(), value);
|
||||
}
|
||||
|
||||
LIBPROTOBUF_EXPORT bool safe_strto64(const string& str, int64* value);
|
||||
LIBPROTOBUF_EXPORT bool safe_strtou64(const string& str, uint64* value);
|
||||
inline bool safe_strto64(const char* str, int64* value) {
|
||||
return safe_strto64(string(str), value);
|
||||
}
|
||||
inline bool safe_strto64(StringPiece str, int64* value) {
|
||||
return safe_strto64(str.ToString(), value);
|
||||
}
|
||||
inline bool safe_strtou64(const char* str, uint64* value) {
|
||||
return safe_strtou64(string(str), value);
|
||||
}
|
||||
inline bool safe_strtou64(StringPiece str, uint64* value) {
|
||||
return safe_strtou64(str.ToString(), value);
|
||||
}
|
||||
|
||||
LIBPROTOBUF_EXPORT bool safe_strtof(const char* str, float* value);
|
||||
LIBPROTOBUF_EXPORT bool safe_strtod(const char* str, double* value);
|
||||
inline bool safe_strtof(const string& str, float* value) {
|
||||
return safe_strtof(str.c_str(), value);
|
||||
}
|
||||
inline bool safe_strtod(const string& str, double* value) {
|
||||
return safe_strtod(str.c_str(), value);
|
||||
}
|
||||
inline bool safe_strtof(StringPiece str, float* value) {
|
||||
return safe_strtof(str.ToString(), value);
|
||||
}
|
||||
inline bool safe_strtod(StringPiece str, double* value) {
|
||||
return safe_strtod(str.ToString(), value);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// FastIntToBuffer()
|
||||
// FastHexToBuffer()
|
||||
// FastHex64ToBuffer()
|
||||
// FastHex32ToBuffer()
|
||||
// FastTimeToBuffer()
|
||||
// These are intended for speed. FastIntToBuffer() assumes the
|
||||
// integer is non-negative. FastHexToBuffer() puts output in
|
||||
// hex rather than decimal. FastTimeToBuffer() puts the output
|
||||
// into RFC822 format.
|
||||
//
|
||||
// FastHex64ToBuffer() puts a 64-bit unsigned value in hex-format,
|
||||
// padded to exactly 16 bytes (plus one byte for '\0')
|
||||
//
|
||||
// FastHex32ToBuffer() puts a 32-bit unsigned value in hex-format,
|
||||
// padded to exactly 8 bytes (plus one byte for '\0')
|
||||
//
|
||||
// All functions take the output buffer as an arg.
|
||||
// They all return a pointer to the beginning of the output,
|
||||
// which may not be the beginning of the input buffer.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
// Suggested buffer size for FastToBuffer functions. Also works with
|
||||
// DoubleToBuffer() and FloatToBuffer().
|
||||
static const int kFastToBufferSize = 32;
|
||||
|
||||
LIBPROTOBUF_EXPORT char* FastInt32ToBuffer(int32 i, char* buffer);
|
||||
LIBPROTOBUF_EXPORT char* FastInt64ToBuffer(int64 i, char* buffer);
|
||||
char* FastUInt32ToBuffer(uint32 i, char* buffer); // inline below
|
||||
char* FastUInt64ToBuffer(uint64 i, char* buffer); // inline below
|
||||
LIBPROTOBUF_EXPORT char* FastHexToBuffer(int i, char* buffer);
|
||||
LIBPROTOBUF_EXPORT char* FastHex64ToBuffer(uint64 i, char* buffer);
|
||||
LIBPROTOBUF_EXPORT char* FastHex32ToBuffer(uint32 i, char* buffer);
|
||||
|
||||
// at least 22 bytes long
|
||||
inline char* FastIntToBuffer(int i, char* buffer) {
|
||||
return (sizeof(i) == 4 ?
|
||||
FastInt32ToBuffer(i, buffer) : FastInt64ToBuffer(i, buffer));
|
||||
}
|
||||
inline char* FastUIntToBuffer(unsigned int i, char* buffer) {
|
||||
return (sizeof(i) == 4 ?
|
||||
FastUInt32ToBuffer(i, buffer) : FastUInt64ToBuffer(i, buffer));
|
||||
}
|
||||
inline char* FastLongToBuffer(long i, char* buffer) {
|
||||
return (sizeof(i) == 4 ?
|
||||
FastInt32ToBuffer(i, buffer) : FastInt64ToBuffer(i, buffer));
|
||||
}
|
||||
inline char* FastULongToBuffer(unsigned long i, char* buffer) {
|
||||
return (sizeof(i) == 4 ?
|
||||
FastUInt32ToBuffer(i, buffer) : FastUInt64ToBuffer(i, buffer));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// FastInt32ToBufferLeft()
|
||||
// FastUInt32ToBufferLeft()
|
||||
// FastInt64ToBufferLeft()
|
||||
// FastUInt64ToBufferLeft()
|
||||
//
|
||||
// Like the Fast*ToBuffer() functions above, these are intended for speed.
|
||||
// Unlike the Fast*ToBuffer() functions, however, these functions write
|
||||
// their output to the beginning of the buffer (hence the name, as the
|
||||
// output is left-aligned). The caller is responsible for ensuring that
|
||||
// the buffer has enough space to hold the output.
|
||||
//
|
||||
// Returns a pointer to the end of the string (i.e. the null character
|
||||
// terminating the string).
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
LIBPROTOBUF_EXPORT char* FastInt32ToBufferLeft(int32 i, char* buffer);
|
||||
LIBPROTOBUF_EXPORT char* FastUInt32ToBufferLeft(uint32 i, char* buffer);
|
||||
LIBPROTOBUF_EXPORT char* FastInt64ToBufferLeft(int64 i, char* buffer);
|
||||
LIBPROTOBUF_EXPORT char* FastUInt64ToBufferLeft(uint64 i, char* buffer);
|
||||
|
||||
// Just define these in terms of the above.
|
||||
inline char* FastUInt32ToBuffer(uint32 i, char* buffer) {
|
||||
FastUInt32ToBufferLeft(i, buffer);
|
||||
return buffer;
|
||||
}
|
||||
inline char* FastUInt64ToBuffer(uint64 i, char* buffer) {
|
||||
FastUInt64ToBufferLeft(i, buffer);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
inline string SimpleBtoa(bool value) {
|
||||
return value ? "true" : "false";
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// SimpleItoa()
|
||||
// Description: converts an integer to a string.
|
||||
//
|
||||
// Return value: string
|
||||
// ----------------------------------------------------------------------
|
||||
LIBPROTOBUF_EXPORT string SimpleItoa(int i);
|
||||
LIBPROTOBUF_EXPORT string SimpleItoa(unsigned int i);
|
||||
LIBPROTOBUF_EXPORT string SimpleItoa(long i);
|
||||
LIBPROTOBUF_EXPORT string SimpleItoa(unsigned long i);
|
||||
LIBPROTOBUF_EXPORT string SimpleItoa(long long i);
|
||||
LIBPROTOBUF_EXPORT string SimpleItoa(unsigned long long i);
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// SimpleDtoa()
|
||||
// SimpleFtoa()
|
||||
// DoubleToBuffer()
|
||||
// FloatToBuffer()
|
||||
// Description: converts a double or float to a string which, if
|
||||
// passed to NoLocaleStrtod(), will produce the exact same original double
|
||||
// (except in case of NaN; all NaNs are considered the same value).
|
||||
// We try to keep the string short but it's not guaranteed to be as
|
||||
// short as possible.
|
||||
//
|
||||
// DoubleToBuffer() and FloatToBuffer() write the text to the given
|
||||
// buffer and return it. The buffer must be at least
|
||||
// kDoubleToBufferSize bytes for doubles and kFloatToBufferSize
|
||||
// bytes for floats. kFastToBufferSize is also guaranteed to be large
|
||||
// enough to hold either.
|
||||
//
|
||||
// Return value: string
|
||||
// ----------------------------------------------------------------------
|
||||
LIBPROTOBUF_EXPORT string SimpleDtoa(double value);
|
||||
LIBPROTOBUF_EXPORT string SimpleFtoa(float value);
|
||||
|
||||
LIBPROTOBUF_EXPORT char* DoubleToBuffer(double i, char* buffer);
|
||||
LIBPROTOBUF_EXPORT char* FloatToBuffer(float i, char* buffer);
|
||||
|
||||
// In practice, doubles should never need more than 24 bytes and floats
|
||||
// should never need more than 14 (including null terminators), but we
|
||||
// overestimate to be safe.
|
||||
static const int kDoubleToBufferSize = 32;
|
||||
static const int kFloatToBufferSize = 24;
|
||||
|
||||
namespace strings {
|
||||
|
||||
enum PadSpec {
|
||||
NO_PAD = 1,
|
||||
ZERO_PAD_2,
|
||||
ZERO_PAD_3,
|
||||
ZERO_PAD_4,
|
||||
ZERO_PAD_5,
|
||||
ZERO_PAD_6,
|
||||
ZERO_PAD_7,
|
||||
ZERO_PAD_8,
|
||||
ZERO_PAD_9,
|
||||
ZERO_PAD_10,
|
||||
ZERO_PAD_11,
|
||||
ZERO_PAD_12,
|
||||
ZERO_PAD_13,
|
||||
ZERO_PAD_14,
|
||||
ZERO_PAD_15,
|
||||
ZERO_PAD_16,
|
||||
};
|
||||
|
||||
struct Hex {
|
||||
uint64 value;
|
||||
enum PadSpec spec;
|
||||
template <class Int>
|
||||
explicit Hex(Int v, PadSpec s = NO_PAD)
|
||||
: spec(s) {
|
||||
// Prevent sign-extension by casting integers to
|
||||
// their unsigned counterparts.
|
||||
#ifdef LANG_CXX11
|
||||
static_assert(
|
||||
sizeof(v) == 1 || sizeof(v) == 2 || sizeof(v) == 4 || sizeof(v) == 8,
|
||||
"Unknown integer type");
|
||||
#endif
|
||||
value = sizeof(v) == 1 ? static_cast<uint8>(v)
|
||||
: sizeof(v) == 2 ? static_cast<uint16>(v)
|
||||
: sizeof(v) == 4 ? static_cast<uint32>(v)
|
||||
: static_cast<uint64>(v);
|
||||
}
|
||||
};
|
||||
|
||||
struct LIBPROTOBUF_EXPORT AlphaNum {
|
||||
const char *piece_data_; // move these to string_ref eventually
|
||||
size_t piece_size_; // move these to string_ref eventually
|
||||
|
||||
char digits[kFastToBufferSize];
|
||||
|
||||
// No bool ctor -- bools convert to an integral type.
|
||||
// A bool ctor would also convert incoming pointers (bletch).
|
||||
|
||||
AlphaNum(int32 i32)
|
||||
: piece_data_(digits),
|
||||
piece_size_(FastInt32ToBufferLeft(i32, digits) - &digits[0]) {}
|
||||
AlphaNum(uint32 u32)
|
||||
: piece_data_(digits),
|
||||
piece_size_(FastUInt32ToBufferLeft(u32, digits) - &digits[0]) {}
|
||||
AlphaNum(int64 i64)
|
||||
: piece_data_(digits),
|
||||
piece_size_(FastInt64ToBufferLeft(i64, digits) - &digits[0]) {}
|
||||
AlphaNum(uint64 u64)
|
||||
: piece_data_(digits),
|
||||
piece_size_(FastUInt64ToBufferLeft(u64, digits) - &digits[0]) {}
|
||||
|
||||
AlphaNum(float f)
|
||||
: piece_data_(digits), piece_size_(strlen(FloatToBuffer(f, digits))) {}
|
||||
AlphaNum(double f)
|
||||
: piece_data_(digits), piece_size_(strlen(DoubleToBuffer(f, digits))) {}
|
||||
|
||||
AlphaNum(Hex hex);
|
||||
|
||||
AlphaNum(const char* c_str)
|
||||
: piece_data_(c_str), piece_size_(strlen(c_str)) {}
|
||||
// TODO: Add a string_ref constructor, eventually
|
||||
// AlphaNum(const StringPiece &pc) : piece(pc) {}
|
||||
|
||||
AlphaNum(const string& str)
|
||||
: piece_data_(str.data()), piece_size_(str.size()) {}
|
||||
|
||||
AlphaNum(StringPiece str)
|
||||
: piece_data_(str.data()), piece_size_(str.size()) {}
|
||||
|
||||
AlphaNum(internal::StringPiecePod str)
|
||||
: piece_data_(str.data()), piece_size_(str.size()) {}
|
||||
|
||||
size_t size() const { return piece_size_; }
|
||||
const char *data() const { return piece_data_; }
|
||||
|
||||
private:
|
||||
// Use ":" not ':'
|
||||
AlphaNum(char c); // NOLINT(runtime/explicit)
|
||||
|
||||
// Disallow copy and assign.
|
||||
AlphaNum(const AlphaNum&);
|
||||
void operator=(const AlphaNum&);
|
||||
};
|
||||
|
||||
} // namespace strings
|
||||
|
||||
using strings::AlphaNum;
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// StrCat()
|
||||
// This merges the given strings or numbers, with no delimiter. This
|
||||
// is designed to be the fastest possible way to construct a string out
|
||||
// of a mix of raw C strings, strings, bool values,
|
||||
// and numeric values.
|
||||
//
|
||||
// Don't use this for user-visible strings. The localization process
|
||||
// works poorly on strings built up out of fragments.
|
||||
//
|
||||
// For clarity and performance, don't use StrCat when appending to a
|
||||
// string. In particular, avoid using any of these (anti-)patterns:
|
||||
// str.append(StrCat(...)
|
||||
// str += StrCat(...)
|
||||
// str = StrCat(str, ...)
|
||||
// where the last is the worse, with the potential to change a loop
|
||||
// from a linear time operation with O(1) dynamic allocations into a
|
||||
// quadratic time operation with O(n) dynamic allocations. StrAppend
|
||||
// is a better choice than any of the above, subject to the restriction
|
||||
// of StrAppend(&str, a, b, c, ...) that none of the a, b, c, ... may
|
||||
// be a reference into str.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b);
|
||||
LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
|
||||
const AlphaNum& c);
|
||||
LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
|
||||
const AlphaNum& c, const AlphaNum& d);
|
||||
LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
|
||||
const AlphaNum& c, const AlphaNum& d,
|
||||
const AlphaNum& e);
|
||||
LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
|
||||
const AlphaNum& c, const AlphaNum& d,
|
||||
const AlphaNum& e, const AlphaNum& f);
|
||||
LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
|
||||
const AlphaNum& c, const AlphaNum& d,
|
||||
const AlphaNum& e, const AlphaNum& f,
|
||||
const AlphaNum& g);
|
||||
LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
|
||||
const AlphaNum& c, const AlphaNum& d,
|
||||
const AlphaNum& e, const AlphaNum& f,
|
||||
const AlphaNum& g, const AlphaNum& h);
|
||||
LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
|
||||
const AlphaNum& c, const AlphaNum& d,
|
||||
const AlphaNum& e, const AlphaNum& f,
|
||||
const AlphaNum& g, const AlphaNum& h,
|
||||
const AlphaNum& i);
|
||||
|
||||
inline string StrCat(const AlphaNum& a) { return string(a.data(), a.size()); }
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// StrAppend()
|
||||
// Same as above, but adds the output to the given string.
|
||||
// WARNING: For speed, StrAppend does not try to check each of its input
|
||||
// arguments to be sure that they are not a subset of the string being
|
||||
// appended to. That is, while this will work:
|
||||
//
|
||||
// string s = "foo";
|
||||
// s += s;
|
||||
//
|
||||
// This will not (necessarily) work:
|
||||
//
|
||||
// string s = "foo";
|
||||
// StrAppend(&s, s);
|
||||
//
|
||||
// Note: while StrCat supports appending up to 9 arguments, StrAppend
|
||||
// is currently limited to 4. That's rarely an issue except when
|
||||
// automatically transforming StrCat to StrAppend, and can easily be
|
||||
// worked around as consecutive calls to StrAppend are quite efficient.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
LIBPROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a);
|
||||
LIBPROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a,
|
||||
const AlphaNum& b);
|
||||
LIBPROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a,
|
||||
const AlphaNum& b, const AlphaNum& c);
|
||||
LIBPROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a,
|
||||
const AlphaNum& b, const AlphaNum& c,
|
||||
const AlphaNum& d);
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Join()
|
||||
// These methods concatenate a range of components into a C++ string, using
|
||||
// the C-string "delim" as a separator between components.
|
||||
// ----------------------------------------------------------------------
|
||||
template <typename Iterator>
|
||||
void Join(Iterator start, Iterator end,
|
||||
const char* delim, string* result) {
|
||||
for (Iterator it = start; it != end; ++it) {
|
||||
if (it != start) {
|
||||
result->append(delim);
|
||||
}
|
||||
StrAppend(result, *it);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Range>
|
||||
string Join(const Range& components,
|
||||
const char* delim) {
|
||||
string result;
|
||||
Join(components.begin(), components.end(), delim, &result);
|
||||
return result;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// ToHex()
|
||||
// Return a lower-case hex string representation of the given integer.
|
||||
// ----------------------------------------------------------------------
|
||||
LIBPROTOBUF_EXPORT string ToHex(uint64 num);
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// GlobalReplaceSubstring()
|
||||
// Replaces all instances of a substring in a string. Does nothing
|
||||
// if 'substring' is empty. Returns the number of replacements.
|
||||
//
|
||||
// NOTE: The string pieces must not overlap s.
|
||||
// ----------------------------------------------------------------------
|
||||
LIBPROTOBUF_EXPORT int GlobalReplaceSubstring(const string& substring,
|
||||
const string& replacement,
|
||||
string* s);
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Base64Unescape()
|
||||
// Converts "src" which is encoded in Base64 to its binary equivalent and
|
||||
// writes it to "dest". If src contains invalid characters, dest is cleared
|
||||
// and the function returns false. Returns true on success.
|
||||
// ----------------------------------------------------------------------
|
||||
LIBPROTOBUF_EXPORT bool Base64Unescape(StringPiece src, string* dest);
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// WebSafeBase64Unescape()
|
||||
// This is a variation of Base64Unescape which uses '-' instead of '+', and
|
||||
// '_' instead of '/'. src is not null terminated, instead specify len. I
|
||||
// recommend that slen<szdest, but we honor szdest anyway.
|
||||
// RETURNS the length of dest, or -1 if src contains invalid chars.
|
||||
|
||||
// The variation that stores into a string clears the string first, and
|
||||
// returns false (with dest empty) if src contains invalid chars; for
|
||||
// this version src and dest must be different strings.
|
||||
// ----------------------------------------------------------------------
|
||||
LIBPROTOBUF_EXPORT int WebSafeBase64Unescape(const char* src, int slen,
|
||||
char* dest, int szdest);
|
||||
LIBPROTOBUF_EXPORT bool WebSafeBase64Unescape(StringPiece src, string* dest);
|
||||
|
||||
// Return the length to use for the output buffer given to the base64 escape
|
||||
// routines. Make sure to use the same value for do_padding in both.
|
||||
// This function may return incorrect results if given input_len values that
|
||||
// are extremely high, which should happen rarely.
|
||||
LIBPROTOBUF_EXPORT int CalculateBase64EscapedLen(int input_len,
|
||||
bool do_padding);
|
||||
// Use this version when calling Base64Escape without a do_padding arg.
|
||||
LIBPROTOBUF_EXPORT int CalculateBase64EscapedLen(int input_len);
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Base64Escape()
|
||||
// WebSafeBase64Escape()
|
||||
// Encode "src" to "dest" using base64 encoding.
|
||||
// src is not null terminated, instead specify len.
|
||||
// 'dest' should have at least CalculateBase64EscapedLen() length.
|
||||
// RETURNS the length of dest.
|
||||
// The WebSafe variation use '-' instead of '+' and '_' instead of '/'
|
||||
// so that we can place the out in the URL or cookies without having
|
||||
// to escape them. It also has an extra parameter "do_padding",
|
||||
// which when set to false will prevent padding with "=".
|
||||
// ----------------------------------------------------------------------
|
||||
LIBPROTOBUF_EXPORT int Base64Escape(const unsigned char* src, int slen,
|
||||
char* dest, int szdest);
|
||||
LIBPROTOBUF_EXPORT int WebSafeBase64Escape(
|
||||
const unsigned char* src, int slen, char* dest,
|
||||
int szdest, bool do_padding);
|
||||
// Encode src into dest with padding.
|
||||
LIBPROTOBUF_EXPORT void Base64Escape(StringPiece src, string* dest);
|
||||
// Encode src into dest web-safely without padding.
|
||||
LIBPROTOBUF_EXPORT void WebSafeBase64Escape(StringPiece src, string* dest);
|
||||
// Encode src into dest web-safely with padding.
|
||||
LIBPROTOBUF_EXPORT void WebSafeBase64EscapeWithPadding(StringPiece src,
|
||||
string* dest);
|
||||
|
||||
LIBPROTOBUF_EXPORT void Base64Escape(const unsigned char* src, int szsrc,
|
||||
string* dest, bool do_padding);
|
||||
LIBPROTOBUF_EXPORT void WebSafeBase64Escape(const unsigned char* src, int szsrc,
|
||||
string* dest, bool do_padding);
|
||||
|
||||
inline bool IsValidCodePoint(uint32 code_point) {
|
||||
return code_point < 0xD800 ||
|
||||
(code_point >= 0xE000 && code_point <= 0x10FFFF);
|
||||
}
|
||||
|
||||
static const int UTFmax = 4;
|
||||
// ----------------------------------------------------------------------
|
||||
// EncodeAsUTF8Char()
|
||||
// Helper to append a Unicode code point to a string as UTF8, without bringing
|
||||
// in any external dependencies. The output buffer must be as least 4 bytes
|
||||
// large.
|
||||
// ----------------------------------------------------------------------
|
||||
LIBPROTOBUF_EXPORT int EncodeAsUTF8Char(uint32 code_point, char* output);
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// UTF8FirstLetterNumBytes()
|
||||
// Length of the first UTF-8 character.
|
||||
// ----------------------------------------------------------------------
|
||||
LIBPROTOBUF_EXPORT int UTF8FirstLetterNumBytes(const char* src, int len);
|
||||
|
||||
} // namespace protobuf
|
||||
} // namespace google
|
||||
|
||||
#endif // GOOGLE_PROTOBUF_STUBS_STRUTIL_H__
|
||||
Executable
+1386
File diff suppressed because it is too large.
Load diff
Executable
+320
@@ -0,0 +1,320 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// Author: jschorr@google.com (Joseph Schorr)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
//
|
||||
// Utilities for printing and parsing protocol messages in a human-readable,
|
||||
// text-based format.
|
||||
//
|
||||
|
||||
// Forked from LibProtobuf for BTS Config by Eric Harding on 5/29/2013
|
||||
//
|
||||
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_TEXT_FORMAT_H__
|
||||
#define GOOGLE_PROTOBUF_TEXT_FORMAT_H__
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <google/protobuf/message.h>
|
||||
#include <google/protobuf/descriptor.h>
|
||||
|
||||
#ifdef __GNUC__
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Weffc++"
|
||||
#endif
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace io {
|
||||
class ErrorCollector; // tokenizer.h
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace bts {
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
|
||||
using namespace ::google::protobuf;
|
||||
|
||||
|
||||
class IDeferValueLookup {
|
||||
public:
|
||||
virtual ~IDeferValueLookup() {};
|
||||
virtual void defer_value(Message*, const Reflection* reflection, const FieldDescriptor* field, int index, int line, int col, const std::string& value, const std::string& key_name, const Message* root) = 0;
|
||||
};
|
||||
|
||||
|
||||
// This class implements protocol buffer text format. Printing and parsing
|
||||
// protocol messages in text format is useful for debugging and human editing
|
||||
// of messages.
|
||||
//
|
||||
// This class is really a namespace that contains only static methods.
|
||||
class TextFormat {
|
||||
public:
|
||||
// Outputs a textual representation of the given message to the given
|
||||
// output stream.
|
||||
static bool Print(const Message& message, io::ZeroCopyOutputStream* output);
|
||||
|
||||
// Print the fields in an UnknownFieldSet. They are printed by tag number
|
||||
// only. Embedded messages are heuristically identified by attempting to
|
||||
// parse them.
|
||||
static bool PrintUnknownFields(const UnknownFieldSet& unknown_fields,
|
||||
io::ZeroCopyOutputStream* output);
|
||||
|
||||
// Like Print(), but outputs directly to a string.
|
||||
static bool PrintToString(const Message& message, string* output);
|
||||
|
||||
// Like PrintUnknownFields(), but outputs directly to a string.
|
||||
static bool PrintUnknownFieldsToString(const UnknownFieldSet& unknown_fields,
|
||||
string* output);
|
||||
|
||||
// Outputs a textual representation of the value of the field supplied on
|
||||
// the message supplied. For non-repeated fields, an index of -1 must
|
||||
// be supplied. Note that this method will print the default value for a
|
||||
// field if it is not set.
|
||||
static void PrintFieldValueToString(const Message& message,
|
||||
const FieldDescriptor* field,
|
||||
int index,
|
||||
string* output);
|
||||
|
||||
// Class for those users which require more fine-grained control over how
|
||||
// a protobuffer message is printed out.
|
||||
class Printer {
|
||||
public:
|
||||
Printer();
|
||||
~Printer();
|
||||
|
||||
// Like TextFormat::Print
|
||||
bool Print(const Message& message, io::ZeroCopyOutputStream* output) const;
|
||||
// Like TextFormat::PrintUnknownFields
|
||||
bool PrintUnknownFields(const UnknownFieldSet& unknown_fields,
|
||||
io::ZeroCopyOutputStream* output) const;
|
||||
// Like TextFormat::PrintToString
|
||||
bool PrintToString(const Message& message, string* output) const;
|
||||
// Like TextFormat::PrintUnknownFieldsToString
|
||||
bool PrintUnknownFieldsToString(const UnknownFieldSet& unknown_fields,
|
||||
string* output) const;
|
||||
// Like TextFormat::PrintFieldValueToString
|
||||
void PrintFieldValueToString(const Message& message,
|
||||
const FieldDescriptor* field,
|
||||
int index,
|
||||
string* output) const;
|
||||
|
||||
// Adjust the initial indent level of all output. Each indent level is
|
||||
// equal to two spaces.
|
||||
void SetInitialIndentLevel(int indent_level) {
|
||||
initial_indent_level_ = indent_level;
|
||||
}
|
||||
|
||||
// If printing in single line mode, then the entire message will be output
|
||||
// on a single line with no line breaks.
|
||||
void SetSingleLineMode(bool single_line_mode) {
|
||||
single_line_mode_ = single_line_mode;
|
||||
}
|
||||
|
||||
// Set true to print repeated primitives in a format like:
|
||||
// field_name: [1, 2, 3, 4]
|
||||
// instead of printing each value on its own line. Short format applies
|
||||
// only to primitive values -- i.e. everything except strings and
|
||||
// sub-messages/groups.
|
||||
void SetUseShortRepeatedPrimitives(bool use_short_repeated_primitives) {
|
||||
use_short_repeated_primitives_ = use_short_repeated_primitives;
|
||||
}
|
||||
|
||||
// Set true to output UTF-8 instead of ASCII. The only difference
|
||||
// is that bytes >= 0x80 in string fields will not be escaped,
|
||||
// because they are assumed to be part of UTF-8 multi-byte
|
||||
// sequences.
|
||||
void SetUseUtf8StringEscaping(bool as_utf8) {
|
||||
utf8_string_escaping_ = as_utf8;
|
||||
}
|
||||
|
||||
private:
|
||||
// Forward declaration of an internal class used to print the text
|
||||
// output to the OutputStream (see text_format.cc for implementation).
|
||||
class TextGenerator;
|
||||
|
||||
// Internal Print method, used for writing to the OutputStream via
|
||||
// the TextGenerator class.
|
||||
void Print(const Message& message,
|
||||
TextGenerator& generator) const;
|
||||
|
||||
// Print a single field.
|
||||
void PrintField(const Message& message,
|
||||
const Reflection* reflection,
|
||||
const FieldDescriptor* field,
|
||||
TextGenerator& generator) const;
|
||||
|
||||
// Print a repeated primitive field in short form.
|
||||
void PrintShortRepeatedField(const Message& message,
|
||||
const Reflection* reflection,
|
||||
const FieldDescriptor* field,
|
||||
TextGenerator& generator) const;
|
||||
|
||||
// Print the name of a field -- i.e. everything that comes before the
|
||||
// ':' for a single name/value pair.
|
||||
void PrintFieldName(const Message& message,
|
||||
const Reflection* reflection,
|
||||
const FieldDescriptor* field,
|
||||
TextGenerator& generator) const;
|
||||
|
||||
// Outputs a textual representation of the value of the field supplied on
|
||||
// the message supplied or the default value if not set.
|
||||
void PrintFieldValue(const Message& message,
|
||||
const Reflection* reflection,
|
||||
const FieldDescriptor* field,
|
||||
int index,
|
||||
TextGenerator& generator) const;
|
||||
|
||||
// Print the fields in an UnknownFieldSet. They are printed by tag number
|
||||
// only. Embedded messages are heuristically identified by attempting to
|
||||
// parse them.
|
||||
void PrintUnknownFields(const UnknownFieldSet& unknown_fields,
|
||||
TextGenerator& generator) const;
|
||||
|
||||
int initial_indent_level_;
|
||||
|
||||
bool single_line_mode_;
|
||||
|
||||
bool use_short_repeated_primitives_;
|
||||
|
||||
bool utf8_string_escaping_;
|
||||
};
|
||||
|
||||
// Parses a text-format protocol message from the given input stream to
|
||||
// the given message object. This function parses the format written
|
||||
// by Print().
|
||||
static bool Parse(io::ZeroCopyInputStream* input, Message* output);
|
||||
// Like Parse(), but reads directly from a string.
|
||||
static bool ParseFromString(const string& input, Message* output);
|
||||
|
||||
// Like Parse(), but the data is merged into the given message, as if
|
||||
// using Message::MergeFrom().
|
||||
static bool Merge(io::ZeroCopyInputStream* input, Message* output);
|
||||
// Like Merge(), but reads directly from a string.
|
||||
static bool MergeFromString(const string& input, Message* output);
|
||||
|
||||
// Parse the given text as a single field value and store it into the
|
||||
// given field of the given message. If the field is a repeated field,
|
||||
// the new value will be added to the end
|
||||
static bool ParseFieldValueFromString(const string& input,
|
||||
const FieldDescriptor* field,
|
||||
Message* message);
|
||||
|
||||
// Interface that TextFormat::Parser can use to find extensions.
|
||||
// This class may be extended in the future to find more information
|
||||
// like fields, etc.
|
||||
class Finder {
|
||||
public:
|
||||
virtual ~Finder();
|
||||
|
||||
// Try to find an extension of *message by fully-qualified field
|
||||
// name. Returns NULL if no extension is known for this name or number.
|
||||
virtual const FieldDescriptor* FindExtension(
|
||||
Message* message,
|
||||
const string& name) const = 0;
|
||||
};
|
||||
|
||||
// For more control over parsing, use this class.
|
||||
class Parser {
|
||||
public:
|
||||
Parser();
|
||||
~Parser();
|
||||
|
||||
// Like TextFormat::Parse().
|
||||
bool Parse(io::ZeroCopyInputStream* input, Message* output);
|
||||
// Like TextFormat::ParseFromString().
|
||||
bool ParseFromString(const string& input, Message* output);
|
||||
// Like TextFormat::Merge().
|
||||
bool Merge(io::ZeroCopyInputStream* input, Message* output);
|
||||
// Like TextFormat::MergeFromString().
|
||||
bool MergeFromString(const string& input, Message* output);
|
||||
|
||||
void SetValueLookup(IDeferValueLookup* lookup) {
|
||||
lookup_ = lookup;
|
||||
}
|
||||
|
||||
// Set where to report parse errors. If NULL (the default), errors will
|
||||
// be printed to stderr.
|
||||
void RecordErrorsTo(io::ErrorCollector* error_collector) {
|
||||
error_collector_ = error_collector;
|
||||
}
|
||||
|
||||
// Set how parser finds extensions. If NULL (the default), the
|
||||
// parser will use the standard Reflection object associated with
|
||||
// the message being parsed.
|
||||
void SetFinder(Finder* finder) {
|
||||
finder_ = finder;
|
||||
}
|
||||
|
||||
// Normally parsing fails if, after parsing, output->IsInitialized()
|
||||
// returns false. Call AllowPartialMessage(true) to skip this check.
|
||||
void AllowPartialMessage(bool allow) {
|
||||
allow_partial_ = allow;
|
||||
}
|
||||
|
||||
// Like TextFormat::ParseFieldValueFromString
|
||||
bool ParseFieldValueFromString(const string& input,
|
||||
const FieldDescriptor* field,
|
||||
Message* output);
|
||||
|
||||
private:
|
||||
// Forward declaration of an internal class used to parse text
|
||||
// representations (see text_format.cc for implementation).
|
||||
class ParserImpl;
|
||||
|
||||
// Like TextFormat::Merge(). The provided implementation is used
|
||||
// to do the parsing.
|
||||
bool MergeUsingImpl(io::ZeroCopyInputStream* input,
|
||||
Message* output,
|
||||
ParserImpl* parser_impl);
|
||||
|
||||
io::ErrorCollector* error_collector_;
|
||||
IDeferValueLookup* lookup_;
|
||||
Finder* finder_;
|
||||
bool allow_partial_;
|
||||
};
|
||||
|
||||
private:
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TextFormat);
|
||||
};
|
||||
|
||||
} // namespace protobuf
|
||||
} // namespace google
|
||||
}
|
||||
#ifdef __GNUC__
|
||||
#pragma GCC diagnostic pop
|
||||
#endif
|
||||
|
||||
#endif // GOOGLE_PROTOBUF_TEXT_FORMAT_H__
|
||||
Executable
+28
@@ -0,0 +1,28 @@
|
||||
#include "BooleanGrammar.h"
|
||||
|
||||
namespace bts {
|
||||
namespace expression {
|
||||
|
||||
ph::function<binary_operator> const and_expr = binary_operator("and");
|
||||
ph::function<binary_operator> const or_expr = binary_operator("or");
|
||||
ph::function<binary_operator> const in_expr = binary_operator("in");
|
||||
ph::function<binary_operator> const gt_expr = binary_operator(">");
|
||||
ph::function<binary_operator> const gte_expr = binary_operator(">=");
|
||||
ph::function<binary_operator> const lt_expr = binary_operator("<");
|
||||
ph::function<binary_operator> const lte_expr = binary_operator("<=");
|
||||
ph::function<binary_operator> const eq_expr = binary_operator("==");
|
||||
ph::function<binary_operator> const neq_expr = binary_operator("!=");
|
||||
ph::function<binary_operator> const match_expr = binary_operator("~=");
|
||||
|
||||
ph::function<unary_operator> not_expr = unary_operator("!");
|
||||
|
||||
ph::function<property_expr_type> const property_expr;
|
||||
|
||||
ph::function<list_expr_type> list_expr;
|
||||
|
||||
// For the sake of build performance this is instantiated here
|
||||
// and referenced by ExpressionEvaluator so that minor changes
|
||||
// to ExpressionEvaluator don't take 30 seconds to build.
|
||||
BooleanGrammar<std::string::const_iterator> boolean_string_grammar;
|
||||
|
||||
}}//namespace
|
||||
Executable
+276
@@ -0,0 +1,276 @@
|
||||
#ifndef BOOLEANGRAMMAR_H_
|
||||
#define BOOLEANGRAMMAR_H_
|
||||
|
||||
#include "lib/utils/bts_no_copy.h"
|
||||
|
||||
#include <boost/config/warning_disable.hpp>
|
||||
#include <boost/spirit/include/qi.hpp>
|
||||
#include <boost/spirit/include/support_utree.hpp>
|
||||
#include <boost/spirit/include/phoenix_operator.hpp>
|
||||
#include <boost/spirit/include/phoenix_function.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
/*
|
||||
* Using and modifying this grammar:
|
||||
*
|
||||
* Boost::spirit is a fantastically complex bit of technology which could take years to master.
|
||||
* I'll try to describe the conventsions followed in this grammar which form a more comprehensible
|
||||
* sub-set.
|
||||
*
|
||||
* spirit::utree is a generic syntax type which can act as the result (aka "property") of an expression or grammar.
|
||||
* boost::spirit can act on any arbitrary type using template based duck typing and a set of rules to transform the result
|
||||
* of your expressions to those types. However, this is incredibly tricky to get right and the error messages aren't very
|
||||
* useful. Whenever possible try to use utree as the result type of your grammar elements. It should support any type needed
|
||||
* for a typical parse grammar. To learn more about utree see the slides and talk
|
||||
* here: http://boost-spirit.com/home/2011/06/12/ast-construction-with-the-universal-tree/
|
||||
* and docs here http://www.boost.org/doc/libs/1_47_0/libs/spirit/doc/html/spirit/support/utree.html
|
||||
*
|
||||
* Note:
|
||||
* In utree there are 2 string type nodes. The standard std::string represents a quoted string value and utf8_symbol_range_type represents
|
||||
* an operator or key word in your grammar.
|
||||
*
|
||||
* Note 2:
|
||||
* When you modify your grammar keep an eye on the raw build output. There is a lot of debug information that gets printed but not included in the Visual Studio
|
||||
* error log.
|
||||
*
|
||||
* This is not meant ot be a complete tutorial so you should also read though the spirit docs.
|
||||
*
|
||||
* Basics:
|
||||
*
|
||||
* ** Example 0
|
||||
* Most spirit parse expressions will look something like this:
|
||||
* a = b [X] >> ";"
|
||||
* this means a will be a parser which matches b followed by a literal semicolon. The statement inside the [ ] is called a "semantic action"
|
||||
* When b is matched it will evaluate the semantic action X passing in the result (or property) of b as _1. The final result is always available
|
||||
* as _val.
|
||||
* If X takes the form _val = _1 it assigns the result of b to a assuming their type is compatible (nearly all types are compatible with utree)
|
||||
* If X takes the form [myoperator(_val, _1)] then _val and _1 are passed in to your user defined operator and you can modify the utree AST directly.
|
||||
*
|
||||
* ** Example 1
|
||||
* rule<Iterator, sp::utree()> term =
|
||||
* bool_ [_val = _1]
|
||||
* | '!' >> bool_ [not_expr(_val, _1)]
|
||||
*
|
||||
* If this encounters the phrase "true" the first part matches and we evaluate [_val = _1] the boolean is automatically converted to a utree (which contains a bool)
|
||||
* If we have "!true" the second part matches and we evaluate [not_expr(_val, _1)] which calls our unary_operator class passing in expr which is the result property
|
||||
* on term and rhs which is the bool value automatically converted to a utree. The operator is then free to modify the result (expr) directly. In this
|
||||
* case it pushes 2 child nodes into expr a not operator and the original utree bool node.
|
||||
*
|
||||
*
|
||||
* ** Example 2
|
||||
* rule<Iterator, std::string()> quoted_string =
|
||||
* char_("'\"")
|
||||
* >> (lexeme[*(alnum [_val += _1] | space [_val += _1])])
|
||||
* >> char_("'\"");
|
||||
*
|
||||
* This is currently the only rule in this grammar which does not use a utree. Here we use a regular std::string rule because in each semantic action we want to append
|
||||
* the new character to the result. If this semantic action was not there at all the resulting property would be a vector<char> which included the quotes. This would
|
||||
* be OK beause boost::spirit can automatically convert a vector<char> to a std::string but we prefer to remove the quotes now.
|
||||
* lexeme[] - is a spirit transform which tells the parser to ignore space skipping for the expression. In this case [ ] do not indicate a semantic action.
|
||||
* *( ) - a kleene star indicateing 0 or more matches of the contained grammar.
|
||||
* char_('") - this syntax matches either of the contained string literals.
|
||||
*
|
||||
*
|
||||
* ** Example 3
|
||||
* This is an excerpt from the term expression that might help you understand how the types flow though boost::spirit (and why utree is so useful).
|
||||
*
|
||||
* ("in" >> ((list | property) [in_expr(_val, _1)]
|
||||
* | _internal_string [in_expr(_val, _1)]))
|
||||
*
|
||||
* Q: Why did we separate quoted_string from (list | property) even though they both appear to have the same semantic action?
|
||||
* In this case list and property both have the result type utree but quoted_string has the result type std::string. Since in_expr() has overloads for both
|
||||
* a right hand utree and a right hand std::string so shoudln't it do the right thing?
|
||||
* A: If we wrote (list | property | quoted_string) [in_expr(_val, _1] the type of _1 would not be either utree or string but a union of both types. Specifically
|
||||
* it would be a boost::variant<utree, string>; Since we don't provide an in_expr::operator() overload for that compilation would fail.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifdef __GNUC__
|
||||
#pragma GCC diagnostic push
|
||||
// Disble effc++ for this file because a lot of the spirit base classes don't include a virtual destructor
|
||||
#pragma GCC diagnostic ignored "-Weffc++"
|
||||
#endif
|
||||
|
||||
|
||||
namespace bts {
|
||||
namespace expression {
|
||||
|
||||
namespace qi = boost::spirit::qi;
|
||||
namespace ph = boost::phoenix;
|
||||
namespace sp = boost::spirit;
|
||||
|
||||
// Base operator holds the result type
|
||||
struct base_operator
|
||||
{
|
||||
template <typename T1, typename T2>
|
||||
struct result { typedef void type; };
|
||||
|
||||
base_operator(const std::string& name)
|
||||
: _name(name)
|
||||
{}
|
||||
|
||||
protected:
|
||||
std::string _name;
|
||||
};
|
||||
|
||||
// Class of operator that acts on a left and right side
|
||||
struct binary_operator : public base_operator
|
||||
{
|
||||
binary_operator(const std::string& name)
|
||||
: base_operator(name)
|
||||
{}
|
||||
|
||||
void operator()(sp::utree& expr, const sp::utree& rhs) const
|
||||
{
|
||||
sp::utree lhs;
|
||||
lhs.swap(expr);
|
||||
expr.push_back(sp::utf8_symbol_type(_name));
|
||||
expr.push_back(lhs);
|
||||
expr.push_back(rhs);
|
||||
}
|
||||
|
||||
};
|
||||
extern ph::function<binary_operator> const and_expr;
|
||||
extern ph::function<binary_operator> const or_expr;
|
||||
extern ph::function<binary_operator> const in_expr;
|
||||
extern ph::function<binary_operator> const gt_expr;
|
||||
extern ph::function<binary_operator> const gte_expr;
|
||||
extern ph::function<binary_operator> const lt_expr;
|
||||
extern ph::function<binary_operator> const lte_expr;
|
||||
extern ph::function<binary_operator> const eq_expr;
|
||||
extern ph::function<binary_operator> const neq_expr;
|
||||
extern ph::function<binary_operator> const match_expr;
|
||||
|
||||
// "!"
|
||||
struct unary_operator : public base_operator
|
||||
{
|
||||
unary_operator(const std::string& name)
|
||||
: base_operator(name)
|
||||
{}
|
||||
|
||||
void operator()(sp::utree& expr, const sp::utree & rhs) const
|
||||
{
|
||||
expr.push_back(sp::utf8_symbol_type(_name));
|
||||
expr.push_back(rhs);
|
||||
}
|
||||
};
|
||||
extern ph::function<unary_operator> not_expr;
|
||||
|
||||
//
|
||||
// The property expression needs to accept a raw vector of characters.
|
||||
//
|
||||
struct property_expr_type
|
||||
{
|
||||
template <typename T1, typename T2>
|
||||
struct result { typedef void type; };
|
||||
|
||||
void operator() (sp::utree& expr, const std::vector<char>& rhs) const
|
||||
{
|
||||
std::string prop_name(rhs.begin (), rhs.end ());
|
||||
expr.clear();
|
||||
expr.push_back(sp::utf8_symbol_type("property"));
|
||||
expr.push_back(sp::utf8_symbol_type(prop_name));
|
||||
}
|
||||
};
|
||||
extern ph::function<property_expr_type> const property_expr;
|
||||
|
||||
//
|
||||
// The list expression simply concatenates values in to one utree node
|
||||
//
|
||||
struct list_expr_type
|
||||
{
|
||||
template <typename T1, typename T2>
|
||||
struct result { typedef void type; };
|
||||
|
||||
void operator()(sp::utree& expr, const sp::utree& rhs) const
|
||||
{
|
||||
if (expr.empty())
|
||||
{
|
||||
expr.push_back(sp::utf8_symbol_type("list"));
|
||||
}
|
||||
expr.push_back(rhs);
|
||||
}
|
||||
};
|
||||
extern ph::function<list_expr_type> list_expr;
|
||||
|
||||
template <typename Iterator, typename space_type = qi::ascii::space_type>
|
||||
class BooleanGrammar : public qi::grammar<Iterator, boost::spirit::utree(), space_type>
|
||||
{
|
||||
public:
|
||||
BooleanGrammar()
|
||||
: BooleanGrammar::base_type(_expression)
|
||||
{
|
||||
using namespace qi;
|
||||
using qi::_1;
|
||||
|
||||
//
|
||||
// Basic types
|
||||
//
|
||||
|
||||
// quoted string's property is std::string instead of utree b/c we need to keep the type compatible with the += operator to build up the string contents
|
||||
_internal_string =
|
||||
char_("'\"")
|
||||
>> (lexeme[*(alnum | space | (punct - char_("'\""))) [_val += _1]])
|
||||
>> char_("'\"");
|
||||
_quoted_string = _internal_string;
|
||||
|
||||
// [1,2,3,4] - sorry no lists of lists
|
||||
_list = '[' >> (_primitive [list_expr(_val, _1)] % ',') >> ']';
|
||||
|
||||
// A property is an unquoted token which will be passed to an IPropertyEvaluator
|
||||
// to be turned into a primitive value or a list.
|
||||
_property = lexeme[(+(alnum | char_("_.$")))] [property_expr(_val, _1)];
|
||||
|
||||
_primitive =
|
||||
qi::no_case[qi::bool_] [_val = _1]
|
||||
| qi::double_ [_val = _1]
|
||||
| _quoted_string [_val = _1]
|
||||
| _property [_val = _1]
|
||||
| _list [_val = _1]
|
||||
| '!' >> _primitive [not_expr(_val, _1)]
|
||||
| '(' >> _expression [_val = _1] >> ')'
|
||||
;
|
||||
|
||||
//
|
||||
// operators
|
||||
//
|
||||
|
||||
_expression =
|
||||
_term [_val = _1]
|
||||
>> *(
|
||||
("and" >> _term [and_expr(_val, _1)])
|
||||
| ("&&" >> _term [and_expr(_val, _1)])
|
||||
| ("or" >> _term [or_expr(_val, _1)])
|
||||
| ("||" >> _term [or_expr(_val, _1)])
|
||||
);
|
||||
|
||||
_term =
|
||||
_primitive [_val = _1]
|
||||
>> *( ("in" >> ((_list | _property | _quoted_string) [in_expr(_val, _1)]))
|
||||
| ("~=" >> (( _property | _quoted_string) [match_expr(_val, _1)]))
|
||||
| (">" >> _primitive [gt_expr(_val, _1)])
|
||||
| (">=" >> _primitive [gte_expr(_val, _1)])
|
||||
| ("<" >> _primitive [lt_expr(_val, _1)])
|
||||
| ("<=" >> _primitive [lte_expr(_val, _1)])
|
||||
| ("==" >> _primitive [eq_expr(_val, _1)])
|
||||
| ("=" >> _primitive [eq_expr(_val, _1)])
|
||||
| ("!=" >> _primitive [neq_expr(_val, _1)])
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
private:
|
||||
BTS_NO_COPY(BooleanGrammar);
|
||||
qi::rule<Iterator, std::string()> _internal_string;
|
||||
qi::rule<Iterator, sp::utree(), space_type> _expression, _primitive, _term, _list, _property, _quoted_string;
|
||||
};
|
||||
|
||||
extern BooleanGrammar<std::string::const_iterator> boolean_string_grammar;
|
||||
|
||||
#ifdef __GNUC__
|
||||
#pragma GCC diagnostic pop
|
||||
#endif
|
||||
|
||||
}}//namespace
|
||||
#endif
|
||||
Executable
+478
@@ -0,0 +1,478 @@
|
||||
#include "ExpressionEvaluator.h"
|
||||
#include "BooleanGrammar.h"
|
||||
#include "ParserExceptions.h"
|
||||
#include "IPropertyEvaluator.h"
|
||||
|
||||
#include <sstream>
|
||||
#include <boost/spirit/include/qi.hpp>
|
||||
#include <boost/spirit/include/support_utree.hpp>
|
||||
#include <boost/algorithm/string.hpp> // iequals
|
||||
#include <boost/regex.hpp>
|
||||
|
||||
namespace qi = boost::spirit::qi;
|
||||
namespace sp = boost::spirit;
|
||||
using namespace std;
|
||||
|
||||
namespace bts {
|
||||
namespace expression {
|
||||
|
||||
class ExpressionEvaluatorImpl
|
||||
{
|
||||
public:
|
||||
ExpressionEvaluatorImpl(std::shared_ptr<IPropertyEvaluator> property_eval);
|
||||
~ExpressionEvaluatorImpl();
|
||||
|
||||
bool eval(const std::string& expression) const;
|
||||
bool check_valid(const std::string& expression, std::string* failed_property) const;
|
||||
void pre_parse(const string& expression, sp::utree& parse_result) const;
|
||||
void pre_parse(const std::vector<std::string>& expressions, std::vector<boost::spirit::utree>& asts) const;
|
||||
bool eval_ast(const boost::spirit::utree& ast) const;
|
||||
Value eval_to_value(const std::string& expression) const;
|
||||
|
||||
private:
|
||||
BTS_NO_COPY(ExpressionEvaluatorImpl);
|
||||
|
||||
bool parse(std::string::const_iterator& begin, const std::string::const_iterator& end, boost::spirit::utree& result) const;
|
||||
bool check_properties(const boost::spirit::utree& node, std::string* failed_property) const;
|
||||
Value eval_node(const boost::spirit::utree& node) const;
|
||||
|
||||
inline bool op_and(boost::spirit::utree::const_iterator& args) const;
|
||||
inline bool op_or(boost::spirit::utree::const_iterator& args) const;
|
||||
inline bool op_in(boost::spirit::utree::const_iterator& args) const;
|
||||
inline bool op_gt(boost::spirit::utree::const_iterator& args) const;
|
||||
inline bool op_gte(boost::spirit::utree::const_iterator& args) const;
|
||||
inline bool op_lt(boost::spirit::utree::const_iterator& args) const;
|
||||
inline bool op_lte(boost::spirit::utree::const_iterator& args) const;
|
||||
inline bool op_eq(boost::spirit::utree::const_iterator args) const;
|
||||
inline bool op_neq(boost::spirit::utree::const_iterator& args) const;
|
||||
inline bool op_match(boost::spirit::utree::const_iterator& args) const;
|
||||
|
||||
|
||||
inline bool op_not(const boost::spirit::utree& operand) const;
|
||||
inline Value op_list(const boost::spirit::utree& operands) const;
|
||||
inline Value op_prop(const boost::spirit::utree& operand) const;
|
||||
|
||||
const std::shared_ptr<IPropertyEvaluator> _property_eval;
|
||||
|
||||
mutable RecursionGuard<std::string> _recursion_guard;
|
||||
};
|
||||
|
||||
|
||||
ExpressionEvaluatorImpl::ExpressionEvaluatorImpl(std::shared_ptr<IPropertyEvaluator> property_eval)
|
||||
:
|
||||
_property_eval(property_eval),
|
||||
_recursion_guard()
|
||||
{
|
||||
}
|
||||
|
||||
ExpressionEvaluatorImpl::~ExpressionEvaluatorImpl()
|
||||
{
|
||||
}
|
||||
|
||||
bool ExpressionEvaluatorImpl::eval(const std::string& expression) const
|
||||
{
|
||||
boost::spirit::utree parse_result;
|
||||
pre_parse(expression, parse_result);
|
||||
return eval_ast(parse_result);
|
||||
}
|
||||
|
||||
Value ExpressionEvaluatorImpl::eval_to_value(const std::string& expression) const
|
||||
{
|
||||
boost::spirit::utree parse_result;
|
||||
pre_parse(expression, parse_result);
|
||||
return eval_node(parse_result);
|
||||
}
|
||||
|
||||
void ExpressionEvaluatorImpl::pre_parse(const std::string& expression, boost::spirit::utree& parse_result) const
|
||||
{
|
||||
std::string::const_iterator begin = expression.begin ();
|
||||
std::string::const_iterator end = expression.end ();
|
||||
bool result = parse(begin, end, parse_result);
|
||||
if (!result)
|
||||
{
|
||||
size_t pos = begin - expression.begin ();
|
||||
throw ParseFailedException(expression, pos);
|
||||
}
|
||||
// std::cout << std::endl << parse_result;
|
||||
}
|
||||
|
||||
void ExpressionEvaluatorImpl::pre_parse(const std::vector<std::string>& expressions, std::vector<boost::spirit::utree>& asts) const
|
||||
{
|
||||
std::vector<std::string>::const_iterator i;
|
||||
asts.reserve(expressions.size());
|
||||
for(i = expressions.begin(); i != expressions.end(); ++i)
|
||||
{
|
||||
boost::spirit::utree parse_result;
|
||||
pre_parse(*i, parse_result);
|
||||
asts.push_back(parse_result);
|
||||
}
|
||||
}
|
||||
|
||||
bool ExpressionEvaluatorImpl::eval_ast(const boost::spirit::utree& ast) const
|
||||
{
|
||||
return value_to_bool(eval_node(ast));
|
||||
}
|
||||
|
||||
bool ExpressionEvaluatorImpl::check_valid(const std::string& expression, std::string* failed_property) const
|
||||
{
|
||||
sp::utree parse_result;
|
||||
std::string::const_iterator begin = expression.begin ();
|
||||
std::string::const_iterator end = expression.end ();
|
||||
bool result = parse(begin, end, parse_result);
|
||||
if (result)
|
||||
{
|
||||
result = check_properties(parse_result, failed_property);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool ExpressionEvaluatorImpl::parse(std::string::const_iterator& begin, const std::string::const_iterator& end, sp::utree& ast) const
|
||||
{
|
||||
// We reference a grammar defined elsewhere for compile time performance
|
||||
bool result = qi::phrase_parse(begin, end, boolean_string_grammar, qi::ascii::space, ast);
|
||||
return result && (begin==end);
|
||||
}
|
||||
|
||||
bool ExpressionEvaluatorImpl::check_properties(const boost::spirit::utree& node, std::string* failed_property) const
|
||||
{
|
||||
bool result = true;
|
||||
|
||||
// a list is either a list [a,b,c] or (operator, arg1, arg2,...)
|
||||
if (node.which () == sp::utree_type::list_type)
|
||||
{
|
||||
boost::spirit::utree::const_iterator iter = node.begin ();
|
||||
boost::spirit::utree::const_iterator end = node.end ();
|
||||
|
||||
const sp::utree& operator_node = node.front();
|
||||
|
||||
if (operator_node.which() == sp::utree_type::symbol_type)
|
||||
{
|
||||
std::string op = get_symbol(operator_node);
|
||||
++iter; // advanced past operator
|
||||
|
||||
if (op == "property")
|
||||
{
|
||||
std::string symbol = get_symbol(*iter);
|
||||
if(!_property_eval->get_value(symbol, nullptr))
|
||||
{
|
||||
if (failed_property != nullptr)
|
||||
{
|
||||
*failed_property = symbol;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for(; result && iter != end; ++iter)
|
||||
{
|
||||
result = check_properties(*iter, failed_property);
|
||||
}
|
||||
}
|
||||
else if (node.which () == sp::utree_type::invalid_type)
|
||||
{
|
||||
result = false;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void check_args(const std::string& op, const sp::utree& node, size_t got, size_t expected)
|
||||
{
|
||||
if (got != expected)
|
||||
{
|
||||
std::ostringstream s_exp;
|
||||
s_exp << node;
|
||||
throw InsuficientArgumentsException(op, s_exp.str(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
Value ExpressionEvaluatorImpl::eval_node(const sp::utree& node) const
|
||||
{
|
||||
if (node.which() != sp::utree_type::list_type || node.size() == 1)
|
||||
{
|
||||
return value_from_utree(node);
|
||||
}
|
||||
|
||||
sp::utree::const_iterator iter = node.begin ();
|
||||
const sp::utree& operator_node = *iter;
|
||||
++iter; // advance past operator
|
||||
|
||||
if (operator_node.which() != sp::utree_type::symbol_type)
|
||||
throw std::invalid_argument("Operator expression must begin with operator symbol");
|
||||
|
||||
std::string op = get_symbol(operator_node);
|
||||
|
||||
if (op == "property")
|
||||
{
|
||||
check_args(op, node, node.size(), 2);
|
||||
return op_prop(*iter);
|
||||
}
|
||||
else if (op == "==")
|
||||
{
|
||||
check_args(op, node, node.size(), 3);
|
||||
return op_eq(iter);
|
||||
}
|
||||
else if (op == "~=")
|
||||
{
|
||||
check_args(op, node, node.size(), 3);
|
||||
return op_match(iter);
|
||||
}
|
||||
else if (op == "!")
|
||||
{
|
||||
check_args(op, node, node.size(), 2);
|
||||
return op_not(*iter);
|
||||
}
|
||||
else if (op == "list")
|
||||
{
|
||||
return op_list(node);
|
||||
}
|
||||
else if (op == "and")
|
||||
{
|
||||
check_args(op, node, node.size(), 3);
|
||||
return op_and(iter);
|
||||
}
|
||||
else if (op == "or")
|
||||
{
|
||||
check_args(op, node, node.size(), 3);
|
||||
return op_or(iter);
|
||||
}
|
||||
else if (op == "in")
|
||||
{
|
||||
check_args(op, node, node.size(), 3);
|
||||
return op_in(iter);
|
||||
}
|
||||
else if (op == ">")
|
||||
{
|
||||
check_args(op, node, node.size(), 3);
|
||||
return op_gt(iter);
|
||||
}
|
||||
else if (op == ">=")
|
||||
{
|
||||
check_args(op, node, node.size(), 3);
|
||||
return op_gte(iter);
|
||||
}
|
||||
else if (op == "<")
|
||||
{
|
||||
check_args(op, node, node.size(), 3);
|
||||
return op_lt(iter);
|
||||
}
|
||||
else if (op == "<=")
|
||||
{
|
||||
check_args(op, node, node.size(), 3);
|
||||
return op_lte(iter);
|
||||
}
|
||||
else if (op == "!=")
|
||||
{
|
||||
check_args(op, node, node.size(), 3);
|
||||
return op_neq(iter);
|
||||
}
|
||||
|
||||
std::string exception_msg = "Unknown operator: " + op;
|
||||
throw ParserException(exception_msg);
|
||||
}
|
||||
|
||||
bool ExpressionEvaluatorImpl::op_and(boost::spirit::utree::const_iterator& args) const
|
||||
{
|
||||
// short circuit rhs
|
||||
bool left = value_to_bool(eval_node(*args));
|
||||
args++;
|
||||
return left && value_to_bool(eval_node(*args));
|
||||
}
|
||||
|
||||
bool ExpressionEvaluatorImpl::op_or(boost::spirit::utree::const_iterator& args) const
|
||||
{
|
||||
// short circuit rhs
|
||||
bool left = value_to_bool(eval_node(*args));
|
||||
return left || value_to_bool(eval_node(*++args));
|
||||
}
|
||||
|
||||
struct InsensitiveStringCompare
|
||||
{
|
||||
InsensitiveStringCompare(const std::string& val) : value(val) { }
|
||||
const std::string& value;
|
||||
|
||||
bool operator() (const std::string& val) const
|
||||
{
|
||||
return boost::iequals(value, val);
|
||||
}
|
||||
|
||||
bool operator() (const Value val) const {
|
||||
if (val.which() != ValueType::anything) {
|
||||
return boost::iequals(value, expression::value_to_string(val));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
bool ExpressionEvaluatorImpl::op_in(boost::spirit::utree::const_iterator& args) const
|
||||
{
|
||||
Value left = eval_node(*args);
|
||||
Value right = eval_node(*++args);
|
||||
|
||||
std::vector<Value> vector;
|
||||
if (right.which() == ValueType::list)
|
||||
{
|
||||
vector = boost::get<std::vector<Value> >(right);
|
||||
if (left.which() == ValueType::string)
|
||||
{
|
||||
return std::find_if(vector.begin(), vector.end(), InsensitiveStringCompare(boost::get<string>(left))) != vector.end();
|
||||
}
|
||||
else
|
||||
{
|
||||
return std::find(vector.begin (), vector.end (), left) != vector.end ();
|
||||
}
|
||||
}
|
||||
else if (right.which() == ValueType::string)
|
||||
{
|
||||
string r = boost::get<string>(right);
|
||||
string l = boost::get<string>(left);
|
||||
boost::algorithm::to_lower(r);
|
||||
boost::algorithm::to_lower(l);
|
||||
return r.find(l) != std::string::npos;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw std::invalid_argument("Right hand argument to 'in' operator must be a list");
|
||||
}
|
||||
}
|
||||
|
||||
bool ExpressionEvaluatorImpl::op_gt(boost::spirit::utree::const_iterator& args) const
|
||||
{
|
||||
Value left = eval_node(*args);
|
||||
Value right = eval_node(*++args);
|
||||
return right < left;
|
||||
}
|
||||
|
||||
bool ExpressionEvaluatorImpl::op_gte(boost::spirit::utree::const_iterator& args) const
|
||||
{
|
||||
Value left = eval_node(*args);
|
||||
Value right = eval_node(*++args);
|
||||
return right == left || right < left;
|
||||
}
|
||||
|
||||
bool ExpressionEvaluatorImpl::op_lt(boost::spirit::utree::const_iterator& args) const
|
||||
{
|
||||
Value left = eval_node(*args);
|
||||
Value right = eval_node(*++args);
|
||||
return left < right;
|
||||
}
|
||||
|
||||
bool ExpressionEvaluatorImpl::op_lte(boost::spirit::utree::const_iterator& args) const
|
||||
{
|
||||
Value left = eval_node(*args);
|
||||
Value right = eval_node(*++args);
|
||||
return left == right || left < right;
|
||||
}
|
||||
|
||||
bool ExpressionEvaluatorImpl::op_eq(boost::spirit::utree::const_iterator args) const
|
||||
{
|
||||
Value left = eval_node(*args);
|
||||
args++;
|
||||
Value right = eval_node(*args);
|
||||
if (left.which() == ValueType::string && right.which() == ValueType::string)
|
||||
{
|
||||
return boost::iequals(
|
||||
boost::get<std::string>(left),
|
||||
boost::get<std::string>(right));
|
||||
}
|
||||
return left == right;
|
||||
}
|
||||
|
||||
bool ExpressionEvaluatorImpl::op_neq(boost::spirit::utree::const_iterator& args) const
|
||||
{
|
||||
return !op_eq(args);
|
||||
}
|
||||
|
||||
inline bool ExpressionEvaluatorImpl::op_match(boost::spirit::utree::const_iterator& args) const
|
||||
{
|
||||
Value left = eval_node(*args);
|
||||
args++;
|
||||
Value right = eval_node(*args);
|
||||
|
||||
return ::boost::regex_search(boost::get<std::string>(left), boost::regex(boost::get<std::string>(right)));
|
||||
}
|
||||
|
||||
bool ExpressionEvaluatorImpl::op_not(const boost::spirit::utree& operand) const
|
||||
{
|
||||
return !value_to_bool(eval_node(operand));
|
||||
}
|
||||
|
||||
Value ExpressionEvaluatorImpl::op_list(const boost::spirit::utree& operands) const
|
||||
{
|
||||
boost::spirit::utree::const_iterator iter = operands.begin (), end = operands.end ();
|
||||
++iter; // advance over "list" operator
|
||||
|
||||
std::vector<Value> list_values;
|
||||
list_values.reserve(operands.size() - 1);
|
||||
|
||||
for (; iter != end; ++iter)
|
||||
{
|
||||
list_values.push_back(eval_node(*iter));
|
||||
}
|
||||
|
||||
return Value(list_values);
|
||||
}
|
||||
|
||||
Value ExpressionEvaluatorImpl::op_prop(const sp::utree& node) const
|
||||
{
|
||||
Value result;
|
||||
std::string symbol = get_symbol(node);
|
||||
|
||||
if (_recursion_guard.check(symbol))
|
||||
{
|
||||
throw RecursivePropertyGetException(symbol, _recursion_guard.get());
|
||||
}
|
||||
GuardFrame<std::string> frame;
|
||||
_recursion_guard.push(symbol, &frame);
|
||||
|
||||
if (!_property_eval->get_value(symbol, &result))
|
||||
{
|
||||
throw InvalidPropertyException(symbol);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
// Outter class method definitions
|
||||
//
|
||||
|
||||
ExpressionEvaluator::ExpressionEvaluator(std::shared_ptr<IPropertyEvaluator> property_eval)
|
||||
: _impl(new ExpressionEvaluatorImpl(property_eval))
|
||||
{
|
||||
}
|
||||
|
||||
ExpressionEvaluator::~ExpressionEvaluator()
|
||||
{
|
||||
}
|
||||
|
||||
bool ExpressionEvaluator::eval(const std::string& expression) const
|
||||
{
|
||||
return _impl->eval(expression);
|
||||
}
|
||||
|
||||
Value ExpressionEvaluator::eval_to_value(const std::string& expression) const
|
||||
{
|
||||
return _impl->eval_to_value(expression);
|
||||
}
|
||||
|
||||
bool ExpressionEvaluator::check_valid(const std::string& expression, std::string* failed_property) const
|
||||
{
|
||||
return _impl->check_valid(expression, failed_property);
|
||||
}
|
||||
|
||||
void ExpressionEvaluator::pre_parse(const std::string& expression, boost::spirit::utree& ast) const {
|
||||
return _impl->pre_parse(expression, ast);
|
||||
}
|
||||
void ExpressionEvaluator::pre_parse(const std::vector<std::string>& expressions, std::vector<boost::spirit::utree>& asts) const
|
||||
{
|
||||
return _impl->pre_parse(expressions, asts);
|
||||
}
|
||||
bool ExpressionEvaluator::eval_ast(const boost::spirit::utree& ast) const
|
||||
{
|
||||
return _impl->eval_ast(ast);
|
||||
}
|
||||
|
||||
|
||||
}}//namespace
|
||||
Executable
+39
@@ -0,0 +1,39 @@
|
||||
#ifndef EXPRESSIONEVALUATOR_H_
|
||||
#define EXPRESSIONEVALUATOR_H_
|
||||
|
||||
#include "Value.h"
|
||||
#include "RecursionGuard.h"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <utility>
|
||||
#include <memory>
|
||||
|
||||
namespace bts {
|
||||
namespace expression {
|
||||
|
||||
class IPropertyEvaluator;
|
||||
class ExpressionEvaluatorImpl;
|
||||
|
||||
class ExpressionEvaluator
|
||||
{
|
||||
public:
|
||||
ExpressionEvaluator(std::shared_ptr<IPropertyEvaluator> property_eval);
|
||||
~ExpressionEvaluator();
|
||||
|
||||
bool eval(const std::string& expression) const;
|
||||
Value eval_to_value(const std::string& expression) const;
|
||||
|
||||
bool check_valid(const std::string& expression, std::string* failed_property) const;
|
||||
|
||||
void pre_parse(const std::string& expression, boost::spirit::utree& ast) const;
|
||||
void pre_parse(const std::vector<std::string>& expressions, std::vector<boost::spirit::utree>& asts) const;
|
||||
bool eval_ast(const boost::spirit::utree& ast) const;
|
||||
|
||||
private:
|
||||
BTS_NO_COPY(ExpressionEvaluator);
|
||||
std::unique_ptr<ExpressionEvaluatorImpl> _impl;
|
||||
};
|
||||
|
||||
}}//namespace
|
||||
#endif
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#ifndef IPROPERTY_EVAULATOR_H_
|
||||
#define IPROPERTY_EVAULATOR_H_
|
||||
|
||||
#include "ExpressionEvaluator.h"
|
||||
#include "Value.h"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace bts {
|
||||
namespace expression {
|
||||
|
||||
class IPropertyEvaluator
|
||||
{
|
||||
public:
|
||||
virtual bool get_value(const std::string& property, Value* out_value) = 0;
|
||||
|
||||
virtual ~IPropertyEvaluator() { }
|
||||
};
|
||||
|
||||
|
||||
}}//namespace
|
||||
#endif
|
||||
Executable
+87
@@ -0,0 +1,87 @@
|
||||
#include "ParserExceptions.h"
|
||||
|
||||
#include <sstream>
|
||||
#include <boost/lexical_cast.hpp>
|
||||
|
||||
namespace bts {
|
||||
namespace expression {
|
||||
|
||||
//
|
||||
// ParserException
|
||||
//
|
||||
ParserException::ParserException(const char* what)
|
||||
: std::logic_error(""), _what(what)
|
||||
{
|
||||
}
|
||||
|
||||
ParserException::ParserException(const std::string& what)
|
||||
: std::logic_error(""), _what(what)
|
||||
{
|
||||
}
|
||||
|
||||
ParserException::ParserException(const ParserException& other)
|
||||
: std::logic_error(""), _what(other._what)
|
||||
{
|
||||
}
|
||||
|
||||
ParserException& ParserException::operator=(const ParserException& other)
|
||||
{
|
||||
_what = other._what;
|
||||
return *this;
|
||||
}
|
||||
|
||||
const char* ParserException::what() const throw()
|
||||
{
|
||||
return _what.c_str();
|
||||
}
|
||||
|
||||
ParserException::~ParserException() throw() { }
|
||||
|
||||
|
||||
//
|
||||
// ParseFailedException
|
||||
//
|
||||
ParseFailedException::ParseFailedException(const std::string& context, size_t at)
|
||||
: ParserException("Parse failed at position: " + boost::lexical_cast<std::string>(at) + " in expression: " + context),
|
||||
context(context)
|
||||
{
|
||||
}
|
||||
|
||||
//
|
||||
// InvalidPropertyException
|
||||
//
|
||||
InvalidPropertyException::InvalidPropertyException(const std::string& prop_name)
|
||||
: ParserException("Invalid property name: " + prop_name)
|
||||
{}
|
||||
|
||||
//
|
||||
// InsuficientArgumentsException
|
||||
//
|
||||
InsuficientArgumentsException::InsuficientArgumentsException(const std::string& op, const std::string& got, size_t expected)
|
||||
: ParserException(""),
|
||||
expected_argument_count(expected),
|
||||
expression(got)
|
||||
{
|
||||
std::ostringstream what;
|
||||
what << "Bad argument count for operator " << op << std::endl << "expected " << expected_argument_count << " arguments. Got '" << expression << "'";
|
||||
_what = what.str();
|
||||
}
|
||||
|
||||
//
|
||||
// RecursivePropertyGetException
|
||||
//
|
||||
RecursivePropertyGetException::RecursivePropertyGetException(const std::string& property, const std::vector<std::string>& stack)
|
||||
: ParserException("")
|
||||
{
|
||||
std::ostringstream what;
|
||||
what << "Error evaluating property '" << property << "': recursive property request at:" << std::endl;
|
||||
std::vector<std::string>::const_reverse_iterator iter = stack.rbegin ();
|
||||
std::vector<std::string>::const_reverse_iterator end = stack.rend ();
|
||||
for(; iter != end; iter++)
|
||||
{
|
||||
what << "> " << *iter << std::endl;
|
||||
}
|
||||
_what = what.str();
|
||||
}
|
||||
|
||||
}}//namespace
|
||||
Executable
+55
@@ -0,0 +1,55 @@
|
||||
#ifndef PARSEREXCEPTIONS_H_
|
||||
#define PARSEREXCEPTIONS_H_
|
||||
|
||||
//#include <exception>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace bts {
|
||||
namespace expression {
|
||||
|
||||
struct ParserException : public std::logic_error
|
||||
{
|
||||
ParserException(const char* what);
|
||||
ParserException(const std::string& what);
|
||||
ParserException(const ParserException& other);
|
||||
ParserException& operator=(const ParserException& other);
|
||||
virtual ~ParserException() throw();
|
||||
|
||||
const char* what() const throw();
|
||||
|
||||
protected:
|
||||
std::string _what;
|
||||
};
|
||||
|
||||
struct ParseFailedException : public ParserException
|
||||
{
|
||||
ParseFailedException(const std::string& context, size_t at);
|
||||
~ParseFailedException() throw() {}
|
||||
std::string context;
|
||||
};
|
||||
|
||||
struct InvalidPropertyException : public ParserException
|
||||
{
|
||||
InvalidPropertyException(const std::string& prop_name);
|
||||
~InvalidPropertyException() throw() {}
|
||||
};
|
||||
|
||||
struct InsuficientArgumentsException : public ParserException
|
||||
{
|
||||
InsuficientArgumentsException(const std::string& oper, const std::string& expression, size_t expected);
|
||||
~InsuficientArgumentsException() throw() {}
|
||||
|
||||
size_t expected_argument_count;
|
||||
std::string expression;
|
||||
};
|
||||
|
||||
struct RecursivePropertyGetException : public ParserException
|
||||
{
|
||||
RecursivePropertyGetException(const std::string& property, const std::vector<std::string>& stack);
|
||||
~RecursivePropertyGetException() throw() {}
|
||||
};
|
||||
|
||||
}}//namespace
|
||||
#endif
|
||||
Executable
+91
@@ -0,0 +1,91 @@
|
||||
#ifndef RECURSIONGUARD_H_
|
||||
#define RECURSIONGUARD_H_
|
||||
|
||||
#include "lib/utils/bts_no_copy.h"
|
||||
#include <boost/thread.hpp>
|
||||
#include <vector>
|
||||
|
||||
namespace bts {
|
||||
namespace expression {
|
||||
|
||||
template<typename T>
|
||||
class RecursionGuard;
|
||||
|
||||
// Safely pops the stack when destroyed
|
||||
template <typename T>
|
||||
struct GuardFrame
|
||||
{
|
||||
GuardFrame ()
|
||||
: _owner (0)
|
||||
{}
|
||||
|
||||
GuardFrame(RecursionGuard<T>& owner)
|
||||
: _owner(&owner)
|
||||
{}
|
||||
|
||||
~GuardFrame()
|
||||
{
|
||||
if (_owner)
|
||||
{
|
||||
std::vector<T>& guard = _owner->get();
|
||||
guard.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
void set_owner (RecursionGuard<T> *owner)
|
||||
{
|
||||
_owner = owner;
|
||||
}
|
||||
|
||||
private:
|
||||
BTS_NO_COPY(GuardFrame);
|
||||
RecursionGuard<T>* _owner;
|
||||
};
|
||||
|
||||
|
||||
template <typename T>
|
||||
class RecursionGuard
|
||||
{
|
||||
public:
|
||||
RecursionGuard()
|
||||
: _recursion_guard()
|
||||
{}
|
||||
~RecursionGuard()
|
||||
{}
|
||||
|
||||
std::vector<T>& get()
|
||||
{
|
||||
std::vector<T>* guard = _recursion_guard.get();
|
||||
if (guard == 0)
|
||||
{
|
||||
guard = new std::vector<T>();
|
||||
_recursion_guard.reset(guard);
|
||||
}
|
||||
return *guard;
|
||||
}
|
||||
|
||||
bool check(const T& value)
|
||||
{
|
||||
std::vector<T>& guard = get();
|
||||
typename std::vector<T>::iterator begin = guard.begin (), end = guard.end ();
|
||||
bool is_recursive = std::find(begin, end, value) != end;
|
||||
return is_recursive;
|
||||
}
|
||||
|
||||
void push(const T& value, GuardFrame<T> *frame)
|
||||
{
|
||||
std::vector<T>& guard = get();
|
||||
guard.push_back(value);
|
||||
frame->set_owner (this);
|
||||
}
|
||||
|
||||
template <typename U>
|
||||
friend struct GuardFrame;
|
||||
private:
|
||||
BTS_NO_COPY(RecursionGuard);
|
||||
boost::thread_specific_ptr<std::vector<T> > _recursion_guard;
|
||||
};
|
||||
|
||||
|
||||
}}//namespace
|
||||
#endif
|
||||
Executable
+94
@@ -0,0 +1,94 @@
|
||||
#include "Value.h"
|
||||
|
||||
#include <stdexcept>
|
||||
|
||||
#include <boost/spirit/include/support_utree.hpp>
|
||||
#include <boost/lexical_cast.hpp>
|
||||
|
||||
namespace bts {
|
||||
namespace expression {
|
||||
|
||||
namespace sp = boost::spirit;
|
||||
|
||||
bool value_to_bool(const Value& val)
|
||||
{
|
||||
switch(val.which())
|
||||
{
|
||||
case ValueType::boolean:
|
||||
return boost::get<bool>(val);
|
||||
case ValueType::integer:
|
||||
return boost::get<int>(val) != 0;
|
||||
case ValueType::real:
|
||||
return boost::get<double>(val) != 0;
|
||||
case ValueType::string:
|
||||
return !boost::get<std::string>(val).empty();
|
||||
case ValueType::list:
|
||||
return boost::get<std::vector<Value> >(val).size() > 0;
|
||||
default:
|
||||
throw std::logic_error("Invalid type in variant. Please update this switch statement");
|
||||
}
|
||||
}
|
||||
std::string value_to_string(const Value& val)
|
||||
{
|
||||
switch(val.which())
|
||||
{
|
||||
case ValueType::boolean:
|
||||
return boost::get<bool>(val) ? "true" : "false";
|
||||
case ValueType::integer:
|
||||
return boost::lexical_cast<std::string>(
|
||||
boost::get<int>(val));
|
||||
case ValueType::real:
|
||||
return boost::lexical_cast<std::string>(
|
||||
boost::get<double>(val));
|
||||
case ValueType::string:
|
||||
return boost::get<std::string>(val);
|
||||
case ValueType::list: {
|
||||
auto vals = boost::get<std::vector<Value>>(val);
|
||||
std::string result;
|
||||
for (const auto& v : vals) {
|
||||
result += value_to_string(v);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
default:
|
||||
throw std::logic_error("Invalid type in variant. Please update this switch statement");
|
||||
}
|
||||
}
|
||||
|
||||
const std::string get_symbol(const sp::utree& node)
|
||||
{
|
||||
sp::utf8_symbol_range_type rt = node.get<sp::utf8_symbol_range_type>();
|
||||
return std::string(rt.begin (),rt.end ());
|
||||
}
|
||||
|
||||
const std::string get_string(const boost::spirit::utree& node)
|
||||
{
|
||||
sp::utf8_symbol_range_type string_range = node.get<sp::utf8_string_range_type>();
|
||||
return std::string(string_range.begin (), string_range.end ());
|
||||
}
|
||||
|
||||
Value value_from_utree(const boost::spirit::utree& node)
|
||||
{
|
||||
switch(node.which())
|
||||
{
|
||||
case sp::utree_type::bool_type:
|
||||
return Value(node.get<bool>());
|
||||
case sp::utree_type::int_type:
|
||||
return Value(node.get<int>());
|
||||
case sp::utree_type::double_type:
|
||||
return Value(node.get<double>());
|
||||
case sp::utree_type::string_type:
|
||||
return Value(get_string(node));
|
||||
case sp::utree_type::list_type:
|
||||
if (node.size() == 1)
|
||||
{
|
||||
return value_from_utree(node.front());
|
||||
}
|
||||
// else fall through
|
||||
default:
|
||||
// Switch may need updating
|
||||
throw std::logic_error("Invalid type node primitive type");
|
||||
}
|
||||
}
|
||||
|
||||
}}//namespace
|
||||
Executable
+44
@@ -0,0 +1,44 @@
|
||||
#ifndef VALUE_H_
|
||||
#define VALUE_H_
|
||||
|
||||
#include <boost/variant.hpp>
|
||||
#include <vector>
|
||||
|
||||
namespace boost {
|
||||
namespace spirit {
|
||||
class utree;
|
||||
}}
|
||||
|
||||
|
||||
namespace bts {
|
||||
namespace expression {
|
||||
|
||||
struct ValueType
|
||||
{
|
||||
enum type {
|
||||
boolean,
|
||||
integer,
|
||||
real,
|
||||
string,
|
||||
list,
|
||||
anything
|
||||
};
|
||||
};
|
||||
|
||||
typedef boost::make_recursive_variant<
|
||||
bool,
|
||||
int,
|
||||
double,
|
||||
std::string,
|
||||
std::vector<boost::recursive_variant_>,
|
||||
void*>::type Value;
|
||||
|
||||
bool value_to_bool(const Value& val);
|
||||
std::string value_to_string(const Value& val);
|
||||
Value value_from_utree(const boost::spirit::utree& node);
|
||||
|
||||
const std::string get_symbol(const boost::spirit::utree& node);
|
||||
const std::string get_string(const boost::spirit::utree& node);
|
||||
|
||||
}}//namespace
|
||||
#endif
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
#include "core/bts_core/utest/utest.h"
|
||||
|
||||
#include "../IPropertyEvaluator.h"
|
||||
#include "../ExpressionEvaluator.h"
|
||||
#include "../ParserExceptions.h"
|
||||
|
||||
#include "core/bts_core/utils/BTS_SharedPtr.h"
|
||||
#include <utility>
|
||||
|
||||
using namespace bts::expression;
|
||||
|
||||
namespace bts {
|
||||
|
||||
// Simple property evaluator for testing
|
||||
class EvaluatesToFoo : public IPropertyEvaluator
|
||||
{
|
||||
public:
|
||||
EvaluatesToFoo()
|
||||
{ }
|
||||
~EvaluatesToFoo()
|
||||
{ }
|
||||
BTS_NO_COPY(EvaluatesToFoo);
|
||||
|
||||
bool get_value(const std::string& prop, Value* out_value) OVERRIDE
|
||||
{
|
||||
bool valid = prop.substr(0,3) == "Foo";
|
||||
if (valid && out_value != nullptr)
|
||||
{
|
||||
if (prop == "Foo.number")
|
||||
{
|
||||
*out_value = Value(42.0);
|
||||
}
|
||||
else if (prop == "Foo.list")
|
||||
{
|
||||
std::vector<Value> values;
|
||||
values.push_back(Value(std::string("foo")));
|
||||
values.push_back(Value(std::string("bar")));
|
||||
values.push_back(Value(std::string("baz")));
|
||||
*out_value = Value(values);
|
||||
}
|
||||
else if (prop == "Foo.bool")
|
||||
{
|
||||
*out_value = Value(true);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Foo.*
|
||||
*out_value = Value(std::string("Foo"));
|
||||
}
|
||||
}
|
||||
|
||||
return valid;
|
||||
}
|
||||
};
|
||||
|
||||
class EvaluatesRecursively : public IPropertyEvaluator
|
||||
{
|
||||
public:
|
||||
EvaluatesRecursively()
|
||||
: _e(nullptr)
|
||||
{ }
|
||||
~EvaluatesRecursively()
|
||||
{ }
|
||||
BTS_NO_COPY(EvaluatesRecursively);
|
||||
|
||||
void set_evaluator(ExpressionEvaluator* e)
|
||||
{
|
||||
_e = e;
|
||||
}
|
||||
|
||||
bool get_value(const std::string& prop, Value* out_value) OVERRIDE
|
||||
{
|
||||
std::string recur = "42 == " + prop;
|
||||
if (out_value)
|
||||
{
|
||||
*out_value = Value(_e->eval(recur));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
ExpressionEvaluator* _e;
|
||||
};
|
||||
|
||||
struct expression_tests : public TestSuite
|
||||
{
|
||||
expression_tests() { }
|
||||
~expression_tests() { }
|
||||
BTS_NO_COPY(expression_tests);
|
||||
|
||||
void setup()
|
||||
{
|
||||
}
|
||||
|
||||
void teardown()
|
||||
{
|
||||
}
|
||||
|
||||
void simple_operator_test()
|
||||
{
|
||||
ExpressionEvaluator e(BTS_SharedPtr<IPropertyEvaluator> (new EvaluatesToFoo()));
|
||||
test_assert(e.eval("!!true"));
|
||||
test_assert(e.eval("3 == 3"));
|
||||
test_assert(e.eval("4 > 3"));
|
||||
test_assert(e.eval("3 < 6"));
|
||||
test_assert(e.eval("3 <= 3.5"));
|
||||
test_assert(e.eval("3 in [1,2,3]"));
|
||||
test_assert(!e.eval("3 in [1,2,4]"));
|
||||
test_assert(e.eval("'oo' in Foo.foo"));
|
||||
test_assert(e.eval("'oo' == 'oo'"));
|
||||
test_assert(e.eval("'afoobar' ~= 'foo.*'"));
|
||||
test_assert(!e.eval("'afoobar' ~= '^foo.*'"));
|
||||
}
|
||||
|
||||
void test_bool_conversion()
|
||||
{
|
||||
ExpressionEvaluator e(BTS_SharedPtr<IPropertyEvaluator> (new EvaluatesToFoo()));
|
||||
test_assert(e.eval("true"));
|
||||
test_assert(e.eval("1"));
|
||||
test_assert(e.eval("1.5"));
|
||||
test_assert(e.eval("'true string'"));
|
||||
//test_assert(e.eval("[1,2,3]")); // list not valid here - only after "in"
|
||||
test_assert(e.eval("Foo.x"));
|
||||
test_assert(e.eval("Foo.list"));
|
||||
test_assert(!e.eval("''"));
|
||||
}
|
||||
|
||||
void property_validator_test()
|
||||
{
|
||||
ExpressionEvaluator e(BTS_SharedPtr<IPropertyEvaluator> (new EvaluatesToFoo()));
|
||||
test_assert(e.check_valid("Foo.bar == 'Foo' or 'x' in [Foo.x, Foo.y, 'z']", nullptr));
|
||||
std::string bad_property;
|
||||
test_assert(!e.check_valid("Foo.bar == 'Foo' or 'x' in [Fuu.x, Foo.y, 'z']", &bad_property));
|
||||
test_assert(bad_property == "Fuu.x");
|
||||
}
|
||||
|
||||
void more_complex_test()
|
||||
{
|
||||
ExpressionEvaluator e(BTS_SharedPtr<IPropertyEvaluator> (new EvaluatesToFoo()));
|
||||
|
||||
test_assert(e.eval("Foo.bar == 'Foo' and 'b' in ['a', 'b', 'c', Foo.bar]"));
|
||||
test_assert(e.eval("Foo.number > 2 or (3.5 <= 7 and Foo.number == 3) or 'x' in ['a', 'b', 'c']"));
|
||||
test_assert(!e.eval("(3.5 <= 7 and Foo.number == 3) or 'x' in ['a', 'b', 'c']"));
|
||||
test_assert(e.eval("'foo' in Foo.list and Foo.number == 42.0"));
|
||||
test_assert(e.eval("!!('oo' in Foo.foo)"));
|
||||
test_assert(e.eval("!('ooo' in Foo.foo)"));
|
||||
test_assert(e.eval("!false in [false, false, false, false, true, Foo.bool]"));
|
||||
}
|
||||
|
||||
void recursive_test()
|
||||
{
|
||||
BTS_SharedPtr<EvaluatesRecursively> badprops (new EvaluatesRecursively());
|
||||
ExpressionEvaluator e(badprops);
|
||||
badprops->set_evaluator(&e);
|
||||
|
||||
// Try to get the 'fuzzy'property recursively
|
||||
bool success = false;
|
||||
try
|
||||
{
|
||||
test_assert(e.eval("fuzzy == 42"));
|
||||
}
|
||||
catch(RecursivePropertyGetException)
|
||||
{
|
||||
success = true;
|
||||
}
|
||||
test_assert(success);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
|
||||
BEGIN_TEST_SUITE(expression_tests)
|
||||
ADD_TEST(simple_operator_test);
|
||||
ADD_TEST(test_bool_conversion);
|
||||
ADD_TEST(property_validator_test);
|
||||
ADD_TEST(more_complex_test);
|
||||
ADD_TEST(recursive_test);
|
||||
END_TEST_SUITE
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <array>
|
||||
#include <limits>
|
||||
#include <string>
|
||||
|
||||
namespace bts {
|
||||
namespace log {
|
||||
|
||||
struct Level {
|
||||
using Rep = uint8_t;
|
||||
constexpr static auto Max = std::numeric_limits<Rep>::max();
|
||||
Rep ordinal;
|
||||
bool operator<(const Level &rhs) const {return ordinal < rhs.ordinal;}
|
||||
};
|
||||
|
||||
struct Subsystem {
|
||||
using Rep = uint8_t;
|
||||
constexpr static auto Max = std::numeric_limits<Rep>::max();
|
||||
Rep ordinal;
|
||||
bool operator<(const Subsystem &rhs) const {return ordinal < rhs.ordinal;}
|
||||
};
|
||||
|
||||
using ArgBuffer = std::array<uint8_t,36>;
|
||||
using MsgFormatter = std::string(*) (ArgBuffer const&,const char*);
|
||||
using Filter = std::array<Level,Subsystem::Max+1>;
|
||||
|
||||
}}
|
||||
@@ -0,0 +1,42 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/utils/warn_ctrl.h"
|
||||
#include "Common.h"
|
||||
#include "MsgPacking.h"
|
||||
|
||||
namespace bts {
|
||||
namespace log {
|
||||
|
||||
using ArgUnpacker = std::string (*) (ArgBuffer const&b, const char*msg_template);
|
||||
|
||||
GCC_DIAG_OFF("-Weffc++")
|
||||
struct LogRec {
|
||||
const char *file;
|
||||
const char *msg_template;
|
||||
ArgUnpacker unpacker;
|
||||
uint16_t line;
|
||||
Level level;
|
||||
Subsystem subsystem;
|
||||
ArgBuffer args;
|
||||
|
||||
template <typename... Args>
|
||||
void pack_msg (const char *msg_t, Args&&... msg_args) {
|
||||
msg_template = msg_t;
|
||||
|
||||
unpacker = unpack_msg_args<sizeof(ArgBuffer),typename std::remove_reference<Args>::type...>;
|
||||
pack_msg_args(args,std::forward<Args>(msg_args)...);
|
||||
}
|
||||
|
||||
std::string unpack_msg()
|
||||
{
|
||||
return unpacker(args,msg_template);
|
||||
}
|
||||
};
|
||||
GCC_DIAG_RESTORE()
|
||||
|
||||
#ifndef WIN32
|
||||
static_assert(sizeof(LogRec) == 64, "LogRec should be 64 bytes");
|
||||
#endif
|
||||
|
||||
}}
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
#pragma once
|
||||
|
||||
#include "MsgPacking.h"
|
||||
#include "LogRec.h"
|
||||
#include "lib/utils/bts_assert.h"
|
||||
|
||||
#include <thread>
|
||||
#include <atomic>
|
||||
|
||||
namespace bts {
|
||||
namespace log {
|
||||
|
||||
class Logger {
|
||||
public:
|
||||
Logger(const Logger&) = delete;
|
||||
Logger&operator=(const Logger&) = delete;
|
||||
|
||||
Logger(std::thread::id tid,
|
||||
Filter const&f,
|
||||
size_t initial_queue_size,
|
||||
size_t max_queue_growth):
|
||||
_mutex () ,
|
||||
_read_q (&_queue_b),
|
||||
_write_q(&_queue_a),
|
||||
_wcursor(0),
|
||||
_filter(f),
|
||||
_drop_count(0),
|
||||
_queue_a(initial_queue_size),
|
||||
_queue_b(initial_queue_size),
|
||||
_tid(tid),
|
||||
_active(true),
|
||||
_max_queue_size(initial_queue_size*max_queue_growth)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void enqueue (Subsystem subsystem,Level lv, const char*file, int line,
|
||||
const char *msg_template, Args&&... msg_args)
|
||||
{
|
||||
bts_assert(_active);
|
||||
lock();
|
||||
if (lv.ordinal >= _filter[subsystem.ordinal].ordinal) {
|
||||
if (_wcursor == _write_q->size())
|
||||
_drop_count++;
|
||||
else {
|
||||
auto &lrec = (*_write_q) [_wcursor++];
|
||||
lrec.file = file;
|
||||
lrec.line = line;
|
||||
lrec.level = lv;
|
||||
lrec.subsystem = subsystem;
|
||||
lrec.pack_msg(msg_template, std::forward<Args>(msg_args)...);
|
||||
}
|
||||
}
|
||||
unlock();
|
||||
}
|
||||
|
||||
template <class S>
|
||||
void unqueue(S const&s) {
|
||||
size_t logged_msg_count = 0;
|
||||
size_t dropped_msg_count = 0;
|
||||
bool active = true;
|
||||
|
||||
lock();
|
||||
std::swap(_read_q,_write_q);
|
||||
logged_msg_count = _wcursor;
|
||||
dropped_msg_count = _drop_count;
|
||||
active = _active;
|
||||
_wcursor = 0;
|
||||
_drop_count = 0;
|
||||
unlock();
|
||||
|
||||
s(_tid,active,dropped_msg_count,logged_msg_count,*_read_q);
|
||||
|
||||
if ((logged_msg_count > _read_q->size() / 2) &&
|
||||
_read_q->size() < _max_queue_size)
|
||||
_read_q->resize(_read_q->size()*2);
|
||||
}
|
||||
|
||||
void update_filter(Filter const&new_filter)
|
||||
{
|
||||
lock();
|
||||
_filter = new_filter;
|
||||
unlock();
|
||||
}
|
||||
|
||||
void update_queue_limits(size_t initial_queue_size,
|
||||
size_t max_queue_growth) {
|
||||
lock();
|
||||
if (_wcursor == 0) {
|
||||
// we can only do this if the queue is empty because each log
|
||||
// record contains a tuple with possibly non trivially
|
||||
// constructuable objects and cannot be moved
|
||||
_write_q->resize(initial_queue_size);
|
||||
}
|
||||
_read_q->resize(initial_queue_size);
|
||||
_max_queue_size = initial_queue_size*max_queue_growth;
|
||||
unlock();
|
||||
}
|
||||
|
||||
void mark_inactive()
|
||||
{
|
||||
lock();
|
||||
bts_assert(_active);
|
||||
_active=false;
|
||||
unlock();
|
||||
}
|
||||
|
||||
~Logger()
|
||||
{
|
||||
bts_assert(!_active);
|
||||
bts_assert(_wcursor == 0);
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
void lock ()
|
||||
{while (_mutex.test_and_set(std::memory_order_acquire));}
|
||||
|
||||
void unlock ()
|
||||
{_mutex.clear(std::memory_order_release);}
|
||||
|
||||
std::atomic_flag _mutex = ATOMIC_FLAG_INIT;
|
||||
std::vector<LogRec>* _read_q;
|
||||
std::vector<LogRec>* _write_q;
|
||||
size_t _wcursor;
|
||||
Filter _filter;
|
||||
size_t _drop_count;
|
||||
std::vector<LogRec> _queue_a;
|
||||
std::vector<LogRec> _queue_b;
|
||||
std::thread::id _tid;
|
||||
bool _active;
|
||||
size_t _max_queue_size;
|
||||
};
|
||||
}}
|
||||
@@ -0,0 +1,201 @@
|
||||
#include "LoggerHub.h"
|
||||
|
||||
#include "lib/utils/bts_assert.h"
|
||||
#include "Logger.h"
|
||||
#include "lib/os/os.h"
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
#include <atomic>
|
||||
#include <algorithm>
|
||||
|
||||
namespace bts {
|
||||
namespace log {
|
||||
|
||||
struct LoggerHub::SinkRec {
|
||||
Sink sink;
|
||||
Filter filter;
|
||||
std::string name;
|
||||
};
|
||||
|
||||
struct LoggerHub::PImpl {
|
||||
PImpl(std::string const&logger_name) :
|
||||
lock(),
|
||||
sinks(),
|
||||
loggers(),
|
||||
level_names(),
|
||||
subsystem_names(),
|
||||
worker(),
|
||||
done(false),
|
||||
logger_initial_queue_size(),
|
||||
logger_max_queue_growth(),
|
||||
logger_name(logger_name)
|
||||
{}
|
||||
|
||||
std::mutex lock;
|
||||
std::vector<SinkRec> sinks;
|
||||
std::vector<std::unique_ptr<Logger>> loggers;
|
||||
std::array<std::string,Level::Max+1> level_names;
|
||||
std::array<std::string,Subsystem::Max+1> subsystem_names;
|
||||
std::thread worker;
|
||||
std::atomic<bool> done;
|
||||
size_t logger_initial_queue_size;
|
||||
size_t logger_max_queue_growth;
|
||||
std::string logger_name;
|
||||
};
|
||||
|
||||
LoggerHub::LoggerHub(std::string const&logger_name)
|
||||
: me (new PImpl(logger_name))
|
||||
{
|
||||
LoggingConfig cfg ;
|
||||
config(cfg);
|
||||
me->worker = std::thread(std::bind(&LoggerHub::do_work,this));
|
||||
}
|
||||
|
||||
void LoggerHub::config(const LoggingConfig &cfg)
|
||||
{
|
||||
std::lock_guard<std::mutex> l (me->lock);
|
||||
|
||||
me->logger_initial_queue_size = cfg.logger_initial_queue_size;
|
||||
me->logger_max_queue_growth = cfg.logger_max_queue_growth;
|
||||
|
||||
for (size_t i = 0; i <= Level::Max ; i++)
|
||||
me->level_names[i] = std::to_string(i);
|
||||
|
||||
for (size_t i = 0; i <= Subsystem::Max ; i++)
|
||||
me->subsystem_names[i] = std::to_string(i);
|
||||
|
||||
for (auto const &kvp : cfg.level_names)
|
||||
me->level_names[kvp.first.ordinal] = kvp.second;
|
||||
|
||||
for (auto const &kvp : cfg.subsystem_names)
|
||||
me->subsystem_names[kvp.first.ordinal ] = kvp.second;
|
||||
|
||||
me->sinks.clear();
|
||||
for (auto const &kvp : cfg.sinks) {
|
||||
auto const &name = kvp.first;
|
||||
auto const &sink = kvp.second.first;
|
||||
auto const &filter = kvp.second.second;
|
||||
me->sinks.push_back(SinkRec{sink,filter,name});
|
||||
}
|
||||
rebuild_logger_filters();
|
||||
update_logger_queue_limits();
|
||||
}
|
||||
|
||||
LoggerHub::~LoggerHub()
|
||||
{
|
||||
me->done=true;
|
||||
me->worker.join();
|
||||
}
|
||||
|
||||
Logger &LoggerHub::make_logger()
|
||||
{
|
||||
std::lock_guard<std::mutex> l (me->lock);
|
||||
me->loggers.push_back(std::make_unique<Logger> (std::this_thread::get_id(),
|
||||
get_base_filter(),
|
||||
me->logger_initial_queue_size,
|
||||
me->logger_max_queue_growth));
|
||||
return *me->loggers.back();
|
||||
}
|
||||
|
||||
void LoggerHub::do_work()
|
||||
{
|
||||
os::set_thread_name(me->logger_name.c_str());
|
||||
while (!me->done) {
|
||||
size_t consumed = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> l (me->lock);
|
||||
consumed = consume_log_recs();
|
||||
}
|
||||
if (consumed == 0)
|
||||
std::this_thread::yield();
|
||||
}
|
||||
|
||||
for (;;) {
|
||||
auto all_shutdown = false;
|
||||
{
|
||||
std::lock_guard<std::mutex> l (me->lock);
|
||||
consume_log_recs();
|
||||
all_shutdown = me->loggers.empty();
|
||||
}
|
||||
if (all_shutdown)
|
||||
return ;
|
||||
else
|
||||
std::this_thread::yield();
|
||||
}
|
||||
}
|
||||
|
||||
size_t LoggerHub::consume_log_recs()
|
||||
{
|
||||
std::vector<std::unique_ptr<Logger>> to_keep;
|
||||
to_keep.reserve(me->loggers.size());
|
||||
|
||||
size_t consumed = 0;
|
||||
for (size_t i = 0; i < me->loggers.size();i++) {
|
||||
auto &l = me->loggers[i];
|
||||
l->unqueue([&l,&to_keep,i,&consumed,this] (std::thread::id tid, bool active,
|
||||
size_t dropped_msg_count,
|
||||
size_t logged_msg_count,
|
||||
std::vector<LogRec> &msgs) {
|
||||
consumed+= (dropped_msg_count + logged_msg_count);
|
||||
if (dropped_msg_count) {
|
||||
LogRec lrec;
|
||||
lrec.file = __FILE__;
|
||||
lrec.line = __LINE__;
|
||||
lrec.level = Level {Level::Max};
|
||||
lrec.subsystem = Subsystem {Subsystem::Max};
|
||||
lrec.pack_msg ("Dropped {} messages. Increase logging buffer size.",
|
||||
dropped_msg_count);
|
||||
dispatch_to_sinks (tid,lrec);
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < logged_msg_count; i++)
|
||||
dispatch_to_sinks(tid,msgs[i]);
|
||||
|
||||
if (active)
|
||||
to_keep.emplace_back(std::move(l));
|
||||
});
|
||||
}
|
||||
me->loggers = std::move(to_keep);
|
||||
return consumed;
|
||||
}
|
||||
|
||||
void LoggerHub::dispatch_to_sinks(std::thread::id tid,LogRec&lr)
|
||||
{
|
||||
auto msg = lr.unpack_msg();
|
||||
auto lm = LogMsg { msg, lr.file, lr.line,
|
||||
lr.level, me->level_names[lr.level.ordinal],
|
||||
lr.subsystem, me->subsystem_names[lr.subsystem.ordinal],
|
||||
tid };
|
||||
|
||||
for (auto &s : me->sinks)
|
||||
if (lr.level.ordinal >= s.filter[lr.subsystem.ordinal].ordinal)
|
||||
s.sink(lm);
|
||||
}
|
||||
|
||||
|
||||
void LoggerHub::rebuild_logger_filters()
|
||||
{
|
||||
auto f = get_base_filter();
|
||||
for (auto &l : me->loggers)
|
||||
l->update_filter(f);
|
||||
}
|
||||
|
||||
Filter LoggerHub::get_base_filter() const
|
||||
{
|
||||
Filter f;
|
||||
for (auto &l : f)
|
||||
l.ordinal = 255;
|
||||
|
||||
for (auto &s : me->sinks)
|
||||
for(size_t i = 0; i < Subsystem::Max+1; i++)
|
||||
f[i].ordinal = std::min(f[i].ordinal,s.filter[i].ordinal);
|
||||
return f;
|
||||
}
|
||||
|
||||
void LoggerHub::update_logger_queue_limits()
|
||||
{
|
||||
for (auto &l : me->loggers)
|
||||
l->update_queue_limits(me->logger_initial_queue_size,me->logger_max_queue_growth);
|
||||
}
|
||||
|
||||
}}
|
||||
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include "Common.h"
|
||||
#include "Sink.h"
|
||||
#include "LoggingConfig.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace bts {
|
||||
namespace log {
|
||||
|
||||
class Logger;
|
||||
struct LogRec;
|
||||
|
||||
class LoggerHub {
|
||||
public:
|
||||
LoggerHub(std::string const& );
|
||||
~LoggerHub();
|
||||
void config(const LoggingConfig &cfg);
|
||||
Logger &make_logger();
|
||||
|
||||
private:
|
||||
struct SinkRec;
|
||||
struct PImpl;
|
||||
std::unique_ptr<PImpl> me;
|
||||
|
||||
void do_work();
|
||||
void update_logger_queue_limits();
|
||||
size_t consume_log_recs();
|
||||
void rebuild_logger_filters();
|
||||
void dispatch_to_sinks(std::thread::id,LogRec&);
|
||||
Filter get_base_filter() const;
|
||||
};
|
||||
|
||||
}}
|
||||
Loaded 100 of 350 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user