8 #include <sandesh/request_pipeline.h>
10 #include "rapidjson/writer.h"
11 #include "rapidjson/stringbuffer.h"
14 #include "config_client_log_types.h"
15 #include "config_client_show_types.h"
17 #include <boost/algorithm/string/join.hpp>
18 #include <boost/algorithm/string/predicate.hpp>
19 #include <boost/foreach.hpp>
20 #include <boost/functional/hash.hpp>
21 #include <boost/ptr_container/ptr_map.hpp>
22 #include <boost/uuid/uuid.hpp>
38 #include "config_client_log_types.h"
39 #include "config_client_show_types.h"
40 #include "sandesh/common/vns_constants.h"
48 using contrail_rapidjson::Value;
49 using contrail_rapidjson::Document;
50 using contrail_rapidjson::SizeType;
51 using contrail_rapidjson::StringBuffer;
52 using contrail_rapidjson::Writer;
67 etcd_client_(etcd_client) {
76 return "ConfigEtcdClient::EtcdWatcher";
89 num_workers_(num_workers)
100 ConfigStaticObjectFactory::Create<ConfigEtcdPartition>(
this, i));
116 ConfigClientMgrDebug,
117 "ETCD Watcher SM: StartWatcher: ETCD watch disabled");
124 if (
mgr()->is_reinit_triggered()) {
126 ConfigClientMgrDebug,
127 "ETCD Watcher SM: StartWatcher: re init triggered,"
128 " don't enqueue ETCD Watcher Task.");
147 if (etcd_client_->mgr()->is_reinit_triggered()) {
149 ConfigClientMgrDebug,
150 "ETCD Watcher SM: Run: re init triggered,"
151 " don't wait for end of config");
158 client()->eqlif_->Watch(
"/contrail/",
170 if (
mgr()->is_reinit_triggered()) {
172 ConfigClientMgrDebug,
173 "ETCD Watcher SM: ProcessResponse: re init triggered,"
193 }
else if (resp.
action() == 1) {
195 }
else if (resp.
action() == 2) {
206 "Database initialization failed");
223 process::ConnectionType::DATABASE,
"Etcd",
224 process::ConnectionStatus::UP,
225 eqlif_->endpoints(),
"Established ETCD connection");
227 "ETCD SM: Established ETCD connection");
230 process::ConnectionType::DATABASE,
"Etcd",
231 process::ConnectionStatus::DOWN,
232 eqlif_->endpoints(),
"Lost ETCD connection");
234 "ETCD SM: Lost ETCD connection");
241 if (
mgr()->is_reinit_triggered())
return false;
248 "ETCD SM: BulkDataSync Started");
255 long num_config_readers_still_processing =
257 if (num_config_readers_still_processing == 1) {
259 "Etcd SM: BulkSyncDone by all readers");
263 "Etcd SM: One reader finished BulkSync");
269 "ETCD SM: Post shutdown during re-init");
293 boost::hash<string> string_hash;
315 size_t front_pos =
uuid.rfind(
'/');
316 string uuid_key =
uuid.substr(front_pos + 1);
319 if (oper ==
"CREATE" || oper ==
"UPDATE") {
322 d.Parse<0>(value.c_str());
323 Document::AllocatorType &a = d.GetAllocator();
328 "non-object json. uuid: "
329 + uuid_key +
" value: "
330 + value +
" .Skipping");
337 if (!d.HasMember(
"type")) {
338 string type =
uuid.substr(10, front_pos - 10);
341 d.AddMember(v.SetString(
"type", a),
342 va.SetString(
type.c_str(), a), a);
344 Writer<StringBuffer> writer(sb);
346 value = sb.GetString();
350 if (d.HasMember(
"type") &&
351 d.HasMember(
"fq_name")) {
352 string obj_type = d[
"type"].GetString();
354 const Value &name = d[
"fq_name"];
355 for (Value::ConstValueIterator name_itr = name.Begin();
356 name_itr != name.End(); ++name_itr) {
357 fq_name += name_itr->GetString();
360 fq_name.erase(fq_name.end()-1);
365 }
else if (oper ==
"DELETE") {
381 for (UUIDValueList::const_iterator it = uuid_list.begin();
382 it != uuid_list.end(); it++) {
390 string prefix =
"/contrail/";
391 bool read_done =
false;
394 for (ConfigClientManager::ObjectTypeList::const_iterator it =
395 mgr()->config_json_parser()->ObjectTypeListToRead().begin();
400 next_key = prefix + it->c_str();
405 unsigned int num_entries;
412 "ETCD SM: Abort UUID reader on reinit trigger");
427 EtcdResponse::kv_map kvs = resp.
kvmap();
438 for (multimap<string, string>::const_iterator iter = kvs.begin();
444 next_key = iter->first;
445 if (!boost::starts_with(next_key,
"/contrail/")) {
447 "ETCD SM: Non-contrail uuid: "
448 + next_key +
" received");
450 uuid_list.push_back(make_pair(iter->first, iter->second));
470 if (kvs.size() < num_entries) {
473 }
else if (resp.
err_code() == 100) {
524 const string &search_string,
526 const string &last_uuid,
527 uint32_t num_entries,
528 vector<ConfigDBUUIDCacheEntry> *entries)
const {
530 num_entries, entries);
534 const string &lookup_key) {
540 : config_client_(client), worker_id_(idx) {
570 const string &uuid_key,
571 const string &value_str) {
572 pair<UUIDProcessSet::iterator, bool> ret;
579 size_t front_pos = uuid_key.rfind(
'/');
580 string uuid = uuid_key.substr(front_pos + 1);
600 if ((oper ==
"DELETE") &&
601 (ret.first->second->oper ==
"CREATE")) {
606 ret.first->second->
oper = oper;
607 ret.first->second->uuid =
uuid;
608 ret.first->second->value = value_str;
617 UUIDCacheMap::const_iterator uuid_iter,
618 ConfigDBUUIDCacheEntry *entry)
const {
619 entry->set_uuid(
uuid);
620 entry->set_timestamp(
622 entry->set_fq_name(uuid_iter->second->GetFQName());
623 entry->set_obj_type(uuid_iter->second->GetObjType());
624 entry->set_json_str(uuid_iter->second->GetJsonString());
628 const string &search_string,
629 const string &last_uuid,
630 uint32_t num_entries,
631 vector<ConfigDBUUIDCacheEntry> *entries)
const {
633 regex search_expr(search_string);
634 for (UUIDCacheMap::const_iterator it =
641 ConfigDBUUIDCacheEntry entry;
643 entries->push_back(entry);
655 return uuid_iter->second;
674 string tmp_uuid =
uuid;
675 pair<UUIDCacheMap::iterator, bool> ret_uuid =
677 assert(ret_uuid.second);
678 uuid_iter = ret_uuid.first;
695 return uuid_iter->second;
700 uint32_t retry_time_pow_of_two =
708 const string value) {
711 *parent_->client()->event_manager()->io_service(),
712 "UUID retry timer for " +
uuid,
714 "config_client::Reader"),
715 parent_->worker_id_);
717 "Created UUID read retry timer ",
uuid);
719 retry_timer_->Cancel();
720 retry_timer_->Start(parent_->UUIDRetryTimeInMSec(
this),
728 "Start/restart UUID Read Retry timer due to configuration",
uuid);
735 retry_timer_->Cancel();
740 "UUID Read retry timer - deleted timer due to configuration",
747 return (retry_timer_->running());
753 const string value) {
755 parent_->client()->EnqueueUUIDRequest(
756 "UPDATE", parent_->client()->uuid_str(
uuid), value);
764 std::string message =
"Timer";
766 "UUID Read Retry Timer error ", message, message);
770 const string &prop)
const {
771 ListMapSet::const_iterator it = list_map_set_.find(prop);
772 if (it == list_map_set_.end()) {
775 return (it->second ==
false);
791 bool notify_update =
false;
795 Value::ConstMemberIterator itr = doc.MemberBegin();
796 Document::AllocatorType &a = doc.GetAllocator();
798 while (itr != doc.MemberEnd()) {
800 string key = itr->name.GetString();
807 if (!notify_update &&
808 key.compare(
"type") != 0 &&
809 key.compare(
"fq_name") != 0) {
810 notify_update =
true;
820 itr = doc.EraseMember(itr);
828 if (key.compare(
"type") == 0) {
829 type_str = itr->value.GetString();
830 itr = doc.EraseMember(itr);
835 GetWrapperFieldName(obj_type, key.c_str());
836 if (!wrapper.empty()) {
849 Value &map_value = doc[key.c_str()];
855 }
else if (key.compare(
"parent_type") == 0) {
861 string parent_type = doc[key.c_str()].GetString();
862 replace(parent_type.begin(), parent_type.end(),
864 doc[key.c_str()].SetString(parent_type.c_str(), a);
866 }
else if (key.compare(
"parent_uuid") == 0) {
874 string parent_uuid = doc[key.c_str()].GetString();
876 if (parent_fq_name ==
"ERROR") {
878 "Parent fq_name not available for ",
uuid);
883 }
else if (key.compare(
"bgpaas_session_attributes") == 0) {
890 doc[key.c_str()].SetString(
"", a);
892 }
else if (key.find(
"_refs") != string::npos && add_change) {
903 string ref_type = key.substr(0, key.length() - 5);
904 bool link_with_attr =
906 IsLinkWithAttr(obj_type, ref_type);
909 Value *v = &doc[key.c_str()];
911 assert(v->IsArray());
912 for (SizeType i = 0; i < v->Size(); i++) {
916 if (link_with_attr) {
917 if (va[
"attr"].IsNull()) {
918 (*v)[i].RemoveMember(
"attr");
920 (*v)[i].AddMember(
"attr", vm.SetObject(), a);
932 Value &uuidVal = va[
"uuid"];
933 const string ref_uuid = uuidVal.GetString();
936 if (ref_fq_name ==
"ERROR") {
940 if (!va.HasMember(
"to")) {
942 "Ref fq_name not available for ",
uuid);
947 const Value &name = va[
"to"];
948 for (Value::ConstValueIterator itr = name.Begin();
949 itr != name.End(); ++itr) {
950 ref_fq_name += itr->GetString();
953 ref_fq_name.erase(ref_fq_name.end()-1);
958 (*v)[i].RemoveMember(
"to");
959 Value vs1(ref_fq_name.c_str(), a);
960 (*v)[i].AddMember(
"to", vs1, a);
969 cacheDoc.Parse<0>(cache_json_str.c_str());
970 cacheDoc.RemoveMember(key.c_str());
974 refVal.CopyFrom(*v, a);
975 cacheDoc.AddMember(vr.SetString(key.c_str(), a),
978 Writer<StringBuffer> writer(sb);
979 cacheDoc.Accept(writer);
980 string cache_str = sb.GetString();
984 if (itr != doc.MemberEnd()) itr++;
987 if (!notify_update) {
989 "ETCD SM: Nothing to update");
994 Writer<StringBuffer> writer1(sb1);
996 refDoc.CopyFrom(doc, refDoc.GetAllocator());
997 refDoc.Accept(writer1);
998 string refString = sb1.GetString();
1000 "ETCD SM: JSON Doc fed to CJP: " + refString);
1009 const string &uuid_key) {
1016 if (
client()->FindFQName(uuid_key) ==
"ERROR") {
1018 "ETCD SM: Nothing to delete");
1053 delDoc.Parse<0>(cache_json_str.c_str());
1076 const string &value_str) {
1083 bool is_new =
false;
1098 if (cache_json_str.compare(
"retry") == 0) {
1103 cache_json_str = value_str;
1107 cacheDoc.Parse<0>(cache_json_str.c_str());
1116 updDoc.Parse<0>(value_str.c_str());
1123 if (!updDoc.HasMember(
"fq_name") ||
1124 !updDoc.HasMember(
"type")) {
1126 "fq_name or type not present for ",
1127 "obj_uuid_table with uuid: ", uuid_key);
1143 Value::ConstMemberIterator itr = updDoc.MemberBegin();
1144 while (itr != updDoc.MemberEnd()) {
1146 key = itr->name.GetString();
1153 if (key.compare(
"draft_mode_state") == 0) {
1154 string mode = itr->value.GetString();
1155 if (!mode.empty()) {
1160 itr = updDoc.EraseMember(itr);
1171 if (key.compare(
"type") == 0) {
1172 string type = itr->value.GetString();
1174 }
else if (key.compare(
"fq_name") == 0) {
1176 const Value &name = updDoc[key.c_str()];
1177 for (Value::ConstValueIterator name_itr = name.Begin();
1178 name_itr != name.End(); ++name_itr) {
1179 fq_name += name_itr->GetString();
1182 fq_name.erase(fq_name.end()-1);
1194 if (!is_new && cacheDoc.HasMember(key.c_str()) &&
1195 key.compare(
"type") != 0 &&
1196 key.compare(
"fq_name") != 0) {
1197 if (cacheDoc[key.c_str()] == updDoc[key.c_str()]) {
1198 itr = updDoc.EraseMember(itr);
1200 assert(cacheDoc.RemoveMember(key.c_str()));
1202 if (itr != updDoc.MemberEnd()) itr++;
1243 const string &lookup_key) {
1260 int num_req_handled = 0;
1270 !
client()->mgr()->is_reinit_triggered();
1278 if (obj_req->
oper ==
"CREATE" || obj_req->
oper ==
"UPDATE") {
1280 }
else if (obj_req->
oper ==
"DELETE") {
1282 }
else if (obj_req->
oper ==
"EndOfConfig") {
1291 if (++num_req_handled ==
client()->GetMaxRequestsToYield()) {
1297 if (
client()->mgr()->is_reinit_triggered()) {
1299 "ETCD SM: Clear UUID process set due to reinit");
1307 UUIDProcessSet::iterator req_it =
1309 delete req_it->second;
static const std::set< std::string > skip_properties
void WaitForEndOfConfig()
bool is_reinit_triggered()
ConfigJsonParserBase * config_json_parser()
virtual std::string FindFQName(const std::string &uuid) const
virtual std::string uuid_str(const std::string &uuid)
const std::vector< std::string > & config_db_ips() const
virtual uint32_t GetNumReadRequestToBunch() const
virtual void InvalidateFQNameCache(const std::string &uuid)
int GetFirstConfigDbPort() const
virtual void UpdateConnectionInfo(bool success, bool force)
virtual void AddFQNameCache(const std::string &uuid, const std::string &obj_type, const std::string &fq_name)
virtual void InitConnectionInfo()
virtual void PurgeFQNameCache(const std::string &uuid)
virtual void ClearFQNameCache()
ConfigClientManager * mgr()
virtual const uint64_t GetInitRetryTimeUSec() const
ConfigEtcdClient * etcd_client_
ConfigEtcdClient * client() const
void ProcessResponse(EtcdResponse resp)
EtcdWatcher(ConfigEtcdClient *etcd_client)
virtual bool Run()
Code to execute in a task. Returns true if task is completed. Return false to reschedule the task.
string Description() const
Gives a description of the task.
virtual void PostShutdown()
PartitionList partitions_
virtual int HashUUID(const std::string &uuid_str) const
virtual void ProcessResponse(EtcdResponse resp)
bool IsTaskTriggered() const
virtual void InitDatabase()
void EnqueueUUIDRequest(string oper, string obj_type, string uuid_str)
std::atomic< long > bulk_sync_status_
virtual bool IsListOrMapPropEmpty(const string &uuid_key, const string &lookup_key)
virtual bool BulkDataSync()
void EnqueueDBSyncRequest(const UUIDValueList &uuid_list)
boost::scoped_ptr< EtcdIf > eqlif_
virtual ~ConfigEtcdClient()
virtual bool UUIDToObjCacheShow(const string &search_string, int inst_num, const string &last_uuid, uint32_t num_entries, vector< ConfigDBUUIDCacheEntry > *entries) const
ConfigEtcdPartition * GetPartition(const string &uuid)
void HandleEtcdConnectionStatus(bool success, bool force_update=false)
static bool disable_watch_
ConfigEtcdClient(ConfigClientManager *mgr, EventManager *evm, const ConfigClientOptions &options, int num_workers)
list< UUIDValueType > UUIDValueList
boost::scoped_ptr< TaskTrigger > uuid_reader_
void EnableEtcdReadRetry(const string uuid, const string value)
void EtcdReadRetryTimerErrorHandler()
bool EtcdReadRetryTimerExpired(const string uuid, const string value)
bool IsRetryTimerRunning() const
void SetJsonString(const string &value_str)
const string & GetJsonString() const
void DisableEtcdReadRetry(const string uuid)
bool ListOrMapPropEmpty(const string &prop) const
void SetListOrMapPropEmpty(const string &prop, bool empty)
uint32_t GetRetryCount() const
void AddUUIDToProcessList(const string &oper, const string &uuid_key, const string &value_str)
bool RequestHandler(ObjectProcessReq *req)
virtual bool IsTaskTriggered() const
virtual int UUIDRetryTimeInMSec(const UUIDCacheEntry *obj) const
bool UUIDToObjCacheShow(const string &search_string, const string &last_uuid, uint32_t num_entries, vector< ConfigDBUUIDCacheEntry > *entries) const
void DeleteCacheMap(const string &uuid)
boost::shared_ptr< TaskTrigger > config_reader_
bool IsListOrMapPropEmpty(const string &uuid_key, const string &lookup_key)
UUIDCacheEntry * GetUUIDCacheEntry(const string &uuid)
ConfigEtcdPartition(ConfigEtcdClient *client, size_t idx)
virtual ~ConfigEtcdPartition()
void ProcessUUIDDelete(const string &uuid_key)
void ProcessUUIDUpdate(const string &uuid_key, const string &value_str)
UUIDProcessWorkQType obj_process_queue_
void Enqueue(ObjectProcessReq *req)
ConfigEtcdClient * client()
void FillUUIDToObjCacheInfo(const string &uuid, UUIDCacheMap::const_iterator uuid_iter, ConfigDBUUIDCacheEntry *entry) const
virtual bool GenerateAndPushJson(const string &uuid_key, Document &doc, bool add_change, UUIDCacheEntry *cache)
UUIDCacheMap uuid_cache_map_
static const uint32_t kMaxUUIDRetryTimePowOfTwo
static const uint32_t kMinUUIDRetryTimeMSec
UUIDProcessSet uuid_process_set_
void RemoveObjReqEntry(string &uuid)
const ObjectTypeList & ObjectTypeListToRead() const
virtual bool Receive(const ConfigCass2JsonAdapter &adapter, bool add_change)=0
virtual const std::string & GetObjType() const
virtual void SetFQName(std::string fq_name)
virtual void SetObjType(std::string obj_type)
The TaskScheduler keeps track of what tasks are currently schedulable. When a task is enqueued it is ...
int GetTaskId(const std::string &name)
void Enqueue(Task *task)
Enqueues a task for running. Starts task if all policy rules are met else puts task in waitq....
static TaskScheduler * GetInstance()
Task is a class to describe a computational task within OpenSDN control plane applications....
static bool DeleteTimer(Timer *Timer)
static Timer * CreateTimer(boost::asio::io_context &service, const std::string &name, int task_id=Timer::GetTimerTaskId(), int task_instance=Timer::GetTimerInstanceId(), bool delete_on_completion=false)
WatchAction action() const
const std::string & key() const
const kv_map & kvmap() const
const std::string & value() const
static ConnectionState * GetInstance()
#define CONFIG_CLIENT_DEBUG(obj,...)
#define CONFIG_CLIENT_WARN(obj,...)
static bool regex_search(const std::string &input, const regex ®ex)
static bool regex_match(const std::string &input, const regex ®ex)
#define CHECK_CONCURRENCY(...)
static std::string UTCUsecToString(uint64_t tstamp)
static uint64_t UTCTimestampUsec()
void STLDeleteValues(Container *container)