OpenSDN source code
config_etcd_client.cc
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2018 Juniper Networks, Inc. All rights reserved.
3  * Copyright Contributors to the OpenSDN project
4  */
5 
7 
8 #include <sandesh/request_pipeline.h>
9 
10 #include "rapidjson/writer.h"
11 #include "rapidjson/stringbuffer.h"
12 
13 #include "config_client_log.h"
14 #include "config_client_log_types.h"
15 #include "config_client_show_types.h"
16 
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>
23 #include <map>
24 #include <set>
25 #include <string>
26 #include <utility>
27 
28 #include "base/connection_info.h"
29 #include "base/logging.h"
30 #include "base/regex.h"
31 #include "base/task.h"
32 #include "base/task_annotations.h"
33 #include "base/task_trigger.h"
35 #include "io/event_manager.h"
36 #include "config_factory.h"
37 #include "config_client_log.h"
38 #include "config_client_log_types.h"
39 #include "config_client_show_types.h"
40 #include "sandesh/common/vns_constants.h"
41 
42 using contrail::regex;
45 using namespace std;
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;
53 
55 
64 public:
65  EtcdWatcher(ConfigEtcdClient *etcd_client) :
66  Task(TaskScheduler::GetInstance()->GetTaskId("etcd::EtcdWatcher")),
67  etcd_client_(etcd_client) {
68  }
69 
70  virtual bool Run();
71 
73  return etcd_client_;
74  }
75  string Description() const {
76  return "ConfigEtcdClient::EtcdWatcher";
77  }
78 
79 private:
81  void ProcessResponse(EtcdResponse resp);
82 };
83 
87  int num_workers)
88  : ConfigDbClient(mgr, evm, options),
89  num_workers_(num_workers)
90 {
91  eqlif_.reset(ConfigStaticObjectFactory::Create<EtcdIf>(config_db_ips(),
93  false));
94 
97 
98  for (int i = 0; i < num_workers_; i++) {
99  partitions_.push_back(
100  ConfigStaticObjectFactory::Create<ConfigEtcdPartition>(this, i));
101  }
102 
103  uuid_reader_.reset(new
104  TaskTrigger(boost::bind(&ConfigEtcdClient::UUIDReader, this),
105  TaskScheduler::GetInstance()->GetTaskId("config_client::DBReader"),
106  0));
107 }
108 
111 }
112 
114  if (disable_watch_) {
116  ConfigClientMgrDebug,
117  "ETCD Watcher SM: StartWatcher: ETCD watch disabled");
118  return;
119  }
120 
124  if (mgr()->is_reinit_triggered()) {
126  ConfigClientMgrDebug,
127  "ETCD Watcher SM: StartWatcher: re init triggered,"
128  " don't enqueue ETCD Watcher Task.");
129  return;
130  }
131 
133  Task *task = new EtcdWatcher(this);
134  scheduler->Enqueue(task);
135 }
136 
138  EtcdResponse resp) {
139  client()->ProcessResponse(resp);
140 }
141 
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");
152  return true;
153  }
154 
158  client()->eqlif_->Watch("/contrail/",
160  this, _1));
161 
162  return true;
163 }
164 
170  if (mgr()->is_reinit_triggered()) {
172  ConfigClientMgrDebug,
173  "ETCD Watcher SM: ProcessResponse: re init triggered,"
174  " stop watching");
175  eqlif_->StopWatch();
176  return;
177  }
178 
183  mgr()->WaitForEndOfConfig();
184 
189  assert(resp.err_code() == 0);
190 
191  if (resp.action() == 0) {
192  EnqueueUUIDRequest("CREATE", resp.key(), resp.value());
193  } else if (resp.action() == 1) {
194  EnqueueUUIDRequest("UPDATE", resp.key(), resp.value());
195  } else if (resp.action() == 2) {
196  EnqueueUUIDRequest("DELETE", resp.key(), resp.value());
197  }
198 }
199 
201  HandleEtcdConnectionStatus(false, true);
202  while (true) {
203  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug, "ETCD SM: Db Init");
204  if (!eqlif_->Connect()) {
205  CONFIG_CLIENT_DEBUG(ConfigEtcdInitErrorMessage,
206  "Database initialization failed");
207  if (!InitRetry()) return;
208  continue;
209  }
210  break;
211  }
213  BulkDataSync();
214 }
215 
217  bool force_update) {
218  UpdateConnectionInfo(success, force_update);
219 
220  if (success) {
221  // Update connection info
223  process::ConnectionType::DATABASE, "Etcd",
224  process::ConnectionStatus::UP,
225  eqlif_->endpoints(), "Established ETCD connection");
226  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
227  "ETCD SM: Established ETCD connection");
228  } else {
230  process::ConnectionType::DATABASE, "Etcd",
231  process::ConnectionStatus::DOWN,
232  eqlif_->endpoints(), "Lost ETCD connection");
233  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
234  "ETCD SM: Lost ETCD connection");
235  }
236 }
237 
239  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug, "ETCD SM: DB Init Retry");
240  // If reinit is triggered, return false to abort connection attempt
241  if (mgr()->is_reinit_triggered()) return false;
242  usleep(GetInitRetryTimeUSec());
243  return true;
244 }
245 
247  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
248  "ETCD SM: BulkDataSync Started");
250  uuid_reader_->Set();
251  return true;
252 }
253 
255  long num_config_readers_still_processing =
256  bulk_sync_status_.fetch_sub(1);
257  if (num_config_readers_still_processing == 1) {
258  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
259  "Etcd SM: BulkSyncDone by all readers");
260  mgr()->EndOfConfig();
261  } else {
262  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
263  "Etcd SM: One reader finished BulkSync");
264  }
265 }
266 
268  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
269  "ETCD SM: Post shutdown during re-init");
272 }
273 
276  int worker_id = HashUUID(uuid);
277  return partitions_[worker_id];
278 }
279 
280 const ConfigEtcdPartition *
281 ConfigEtcdClient::GetPartition(const string &uuid) const {
282  int worker_id = HashUUID(uuid);
283  return partitions_[worker_id];
284 }
285 
286 const ConfigEtcdPartition *
287 ConfigEtcdClient::GetPartition(int worker_id) const {
288  assert(worker_id < num_workers_);
289  return partitions_[worker_id];
290 }
291 
292 int ConfigEtcdClient::HashUUID(const string &uuid_str) const {
293  boost::hash<string> string_hash;
294  return string_hash(uuid_str) % num_workers_;
295 }
296 
298  string uuid,
299  string value) {
314  // Get the trimmed uuid
315  size_t front_pos = uuid.rfind('/');
316  string uuid_key = uuid.substr(front_pos + 1);
317 
318  // Cache uses the trimmed uuid
319  if (oper == "CREATE" || oper == "UPDATE") {
320 
321  Document d;
322  d.Parse<0>(value.c_str());
323  Document::AllocatorType &a = d.GetAllocator();
324 
325  // If non-object JSON is received, log a warning and return.
326  if (!d.IsObject()) {
327  CONFIG_CLIENT_WARN(ConfigClientMgrWarning, "ETCD SM: Received "
328  "non-object json. uuid: "
329  + uuid_key + " value: "
330  + value + " .Skipping");
331  return;
332  }
333 
334  // ETCD does not provide obj-type since it is encoded in the
335  // UUID key. Since config_json_parser and IFMap need type to be
336  // present in the document, fix up by adding obj-type.
337  if (!d.HasMember("type")) {
338  string type = uuid.substr(10, front_pos - 10);
339  Value v;
340  Value va;
341  d.AddMember(v.SetString("type", a),
342  va.SetString(type.c_str(), a), a);
343  StringBuffer sb;
344  Writer<StringBuffer> writer(sb);
345  d.Accept(writer);
346  value = sb.GetString();
347  }
348 
349  // Add to FQName cache if not present
350  if (d.HasMember("type") &&
351  d.HasMember("fq_name")) {
352  string obj_type = d["type"].GetString();
353  string fq_name;
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();
358  fq_name += ":";
359  }
360  fq_name.erase(fq_name.end()-1);
361  if (FindFQName(uuid_key) == "ERROR") {
362  AddFQNameCache(uuid_key, obj_type, fq_name);
363  }
364  }
365  } else if (oper == "DELETE") {
366  // Invalidate cache
367  InvalidateFQNameCache(uuid_key);
368  }
369 
370  // Request has the uuid with entire path
371  ObjectProcessReq *req = new ObjectProcessReq(oper, uuid, value);
372 
373  // GetPartition uses the trimmed uuid so that the same
374  // partition is returned for different requests on the
375  // same UUID
376  GetPartition(uuid_key)->Enqueue(req);
377 }
378 
380  const UUIDValueList &uuid_list) {
381  for (UUIDValueList::const_iterator it = uuid_list.begin();
382  it != uuid_list.end(); it++) {
383  EnqueueUUIDRequest("CREATE", it->first, it->second);
384  }
385 }
386 
388 
389  string next_key;
390  string prefix = "/contrail/";
391  bool read_done = false;
392  ostringstream os;
393 
394  for (ConfigClientManager::ObjectTypeList::const_iterator it =
395  mgr()->config_json_parser()->ObjectTypeListToRead().begin();
396  it != mgr()->config_json_parser()->ObjectTypeListToRead().end();
397  it++) {
398 
399  /* Form the key for the object type to lookup */
400  next_key = prefix + it->c_str();
401  os.str("");
402  os << next_key << 1;
403 
404  while (true) {
405  unsigned int num_entries;
406 
410  if (mgr()->is_reinit_triggered()) {
411  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
412  "ETCD SM: Abort UUID reader on reinit trigger");
413  return true;
414  }
415 
419  num_entries = GetNumReadRequestToBunch();
420 
424  EtcdResponse resp = eqlif_->Get(next_key,
425  os.str(),
426  num_entries);
427  EtcdResponse::kv_map kvs = resp.kvmap();
428 
432  if (resp.err_code() == 0) {
436  UUIDValueList uuid_list;
437 
438  for (multimap<string, string>::const_iterator iter = kvs.begin();
439  iter != kvs.end();
440  ++iter) {
444  next_key = iter->first;
445  if (!boost::starts_with(next_key, "/contrail/")) {
446  CONFIG_CLIENT_WARN(ConfigClientMgrWarning,
447  "ETCD SM: Non-contrail uuid: "
448  + next_key + " received");
449  } else {
450  uuid_list.push_back(make_pair(iter->first, iter->second));
451  }
452  }
453 
458  EnqueueDBSyncRequest(uuid_list);
459 
463  next_key += "00";
464 
470  if (kvs.size() < num_entries) {
471  break;
472  }
473  } else if (resp.err_code() == 100) {
477  break;
478  } else if (resp.err_code() == -1) {
479  /* Test ONLY */
480  read_done = true;
481  break;
482  } else {
488  usleep(GetInitRetryTimeUSec());
489  }
490  } //while
491  if (read_done) {
492  break;
493  }
494  } //for
495 
496  // At the end of task trigger
497  BOOST_FOREACH(ConfigEtcdPartition *partition, partitions_) {
498  ObjectProcessReq *req = new ObjectProcessReq("EndOfConfig", "", "");
499  partition->Enqueue(req);
500  }
501 
502  return true;
503 }
504 
506  // If UUIDReader task has been triggered return true.
507  if (uuid_reader_->IsSet()) {
508  return true;
509  }
510 
515  BOOST_FOREACH(ConfigEtcdPartition *partition, partitions_) {
516  if (partition->IsTaskTriggered()) {
517  return true;
518  }
519  }
520  return false;
521 }
522 
524  const string &search_string,
525  int inst_num,
526  const string &last_uuid,
527  uint32_t num_entries,
528  vector<ConfigDBUUIDCacheEntry> *entries) const {
529  return GetPartition(inst_num)->UUIDToObjCacheShow(search_string, last_uuid,
530  num_entries, entries);
531 }
532 
533 bool ConfigEtcdClient::IsListOrMapPropEmpty(const string &uuid_key,
534  const string &lookup_key) {
535  return GetPartition(uuid_key)->IsListOrMapPropEmpty(uuid_key, lookup_key);
536 }
537 
539  ConfigEtcdClient *client, size_t idx)
540  : config_client_(client), worker_id_(idx) {
541  int task_id = TaskScheduler::GetInstance()->GetTaskId("config_client::Reader");
542  config_reader_.reset(new
544  task_id, idx));
545  task_id =
546  TaskScheduler::GetInstance()->GetTaskId("config_client::ObjectProcessor");
548  task_id, idx, bind(&ConfigEtcdPartition::RequestHandler, this, _1),
550 }
551 
553  obj_process_queue_->Shutdown();
554 }
555 
557  obj_process_queue_->Enqueue(req);
558 }
559 
561  AddUUIDToProcessList(req->oper_, req->uuid_str_, req->value_);
562  delete req;
563  return true;
564 }
565 
570  const string &uuid_key,
571  const string &value_str) {
572  pair<UUIDProcessSet::iterator, bool> ret;
573  bool trigger = uuid_process_set_.empty();
574 
579  size_t front_pos = uuid_key.rfind('/');
580  string uuid = uuid_key.substr(front_pos + 1);
582  new UUIDProcessRequestType(oper, uuid, value_str);
583  ret = uuid_process_set_.insert(make_pair(client()->GetUUID(uuid), req));
584  if (ret.second) {
590  if (trigger) {
591  config_reader_->Set();
592  }
593  } else {
600  if ((oper == "DELETE") &&
601  (ret.first->second->oper == "CREATE")) {
602  uuid_process_set_.erase(ret.first);
604  } else {
605  delete req;
606  ret.first->second->oper = oper;
607  ret.first->second->uuid = uuid;
608  ret.first->second->value = value_str;
609  }
610  }
611 }
612 
614 }
615 
617  UUIDCacheMap::const_iterator uuid_iter,
618  ConfigDBUUIDCacheEntry *entry) const {
619  entry->set_uuid(uuid);
620  entry->set_timestamp(
621  UTCUsecToString(uuid_iter->second->GetLastReadTimeStamp()));
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());
625 }
626 
628  const string &search_string,
629  const string &last_uuid,
630  uint32_t num_entries,
631  vector<ConfigDBUUIDCacheEntry> *entries) const {
632  uint32_t count = 0;
633  regex search_expr(search_string);
634  for (UUIDCacheMap::const_iterator it =
635  uuid_cache_map_.upper_bound(last_uuid);
636  count < num_entries && it != uuid_cache_map_.end(); it++) {
637  if (regex_search(it->first, search_expr) ||
638  regex_search(it->second->GetObjType(), search_expr) ||
639  regex_search(it->second->GetFQName(), search_expr)) {
640  count++;
641  ConfigDBUUIDCacheEntry entry;
642  FillUUIDToObjCacheInfo(it->first, it, &entry);
643  entries->push_back(entry);
644  }
645  }
646  return true;
647 }
648 
651  UUIDCacheMap::iterator uuid_iter = uuid_cache_map_.find(uuid);
652  if (uuid_iter == uuid_cache_map_.end()) {
653  return NULL;
654  }
655  return uuid_iter->second;
656 }
657 
660  const string &value,
661  bool &is_new) {
662  UUIDCacheMap::iterator uuid_iter = uuid_cache_map_.find(uuid);
663  if (uuid_iter == uuid_cache_map_.end()) {
667  UUIDCacheEntry *obj;
668  obj = new UUIDCacheEntry(this,
669  value,
670  UTCTimestampUsec());
674  string tmp_uuid = uuid;
675  pair<UUIDCacheMap::iterator, bool> ret_uuid =
676  uuid_cache_map_.insert(tmp_uuid, obj);
677  assert(ret_uuid.second);
678  uuid_iter = ret_uuid.first;
679 
684  is_new = true;
685  } else {
689  uuid_iter->second->SetLastReadTimeStamp(UTCTimestampUsec());
690  }
691 
695  return uuid_iter->second;
696 }
697 
699  const UUIDCacheEntry *obj) const {
700  uint32_t retry_time_pow_of_two =
703  return ((1 << retry_time_pow_of_two) * kMinUUIDRetryTimeMSec);
704 }
705 
707  const string uuid,
708  const string value) {
709  if (!retry_timer_) {
710  retry_timer_ = TimerManager::CreateTimer(
711  *parent_->client()->event_manager()->io_service(),
712  "UUID retry timer for " + uuid,
714  "config_client::Reader"),
715  parent_->worker_id_);
716  CONFIG_CLIENT_DEBUG(ConfigClientReadRetry,
717  "Created UUID read retry timer ", uuid);
718  }
719  retry_timer_->Cancel();
720  retry_timer_->Start(parent_->UUIDRetryTimeInMSec(this),
721  boost::bind(
723  this, uuid, value),
724  boost::bind(
726  this));
727  CONFIG_CLIENT_DEBUG(ConfigClientReadRetry,
728  "Start/restart UUID Read Retry timer due to configuration", uuid);
729 }
730 
732  const string uuid) {
733  CHECK_CONCURRENCY("config_client::Reader");
734  if (retry_timer_) {
735  retry_timer_->Cancel();
736  TimerManager::DeleteTimer(retry_timer_);
737  retry_timer_ = NULL;
738  retry_count_ = 0;
739  CONFIG_CLIENT_DEBUG(ConfigClientReadRetry,
740  "UUID Read retry timer - deleted timer due to configuration",
741  uuid);
742  }
743 }
744 
746  if (retry_timer_)
747  return (retry_timer_->running());
748  return false;
749 }
750 
752  const string uuid,
753  const string value) {
754  CHECK_CONCURRENCY("config_client::Reader");
755  parent_->client()->EnqueueUUIDRequest(
756  "UPDATE", parent_->client()->uuid_str(uuid), value);
757  retry_count_++;
758  CONFIG_CLIENT_DEBUG(ConfigClientReadRetry, "timer expired ", uuid);
759  return false;
760 }
761 
762 void
764  std::string message = "Timer";
765  CONFIG_CLIENT_WARN(ConfigClientGetRowError,
766  "UUID Read Retry Timer error ", message, message);
767 }
768 
770  const string &prop) const {
771  ListMapSet::const_iterator it = list_map_set_.find(prop);
772  if (it == list_map_set_.end()) {
773  return true;
774  }
775  return (it->second == false);
776 }
777 
779  Document &doc,
780  bool add_change,
781  UUIDCacheEntry *cache) {
782 
783  // Get obj_type from cache.
784  const string &obj_type = cache->GetObjType();
785 
786  // string to get the type field.
787  string type_str;
788 
789  // bool to indicate if an update to ifmap_server is
790  // necessary.
791  bool notify_update = false;
792 
793  // Walk the document, remove unwanted properties and do
794  // needed fixup for the others.
795  Value::ConstMemberIterator itr = doc.MemberBegin();
796  Document::AllocatorType &a = doc.GetAllocator();
797 
798  while (itr != doc.MemberEnd()) {
799 
800  string key = itr->name.GetString();
801 
802  /*
803  * Indicate need for update since document has
804  * at least one field other than fq_name or
805  * obj_type to be updated.
806  */
807  if (!notify_update &&
808  key.compare("type") != 0 &&
809  key.compare("fq_name") != 0) {
810  notify_update = true;
811  }
812 
818  if (ConfigClientManager::skip_properties.find(key) !=
820  itr = doc.EraseMember(itr);
821  continue;
822  }
823 
828  if (key.compare("type") == 0) {
829  type_str = itr->value.GetString();
830  itr = doc.EraseMember(itr);
831  continue;
832  }
833 
834  string wrapper = client()->mgr()->config_json_parser()-> \
835  GetWrapperFieldName(obj_type, key.c_str());
836  if (!wrapper.empty()) {
837 
848  // Get the propl/propm json Value
849  Value &map_value = doc[key.c_str()];
850 
851  // Indicate in cache if propm/propl is empty
852  cache->SetListOrMapPropEmpty(key,
853  map_value.IsNull());
854 
855  } else if (key.compare("parent_type") == 0) {
856 
861  string parent_type = doc[key.c_str()].GetString();
862  replace(parent_type.begin(), parent_type.end(),
863  '-', '_');
864  doc[key.c_str()].SetString(parent_type.c_str(), a);
865 
866  } else if (key.compare("parent_uuid") == 0) {
867 
873  if (add_change) {
874  string parent_uuid = doc[key.c_str()].GetString();
875  string parent_fq_name = client()->FindFQName(parent_uuid);
876  if (parent_fq_name == "ERROR") {
877  CONFIG_CLIENT_DEBUG(ConfigClientReadRetry,
878  "Parent fq_name not available for ", uuid);
879  return false;
880  }
881  }
882 
883  } else if (key.compare("bgpaas_session_attributes") == 0) {
884 
890  doc[key.c_str()].SetString("", a);
891 
892  } else if (key.find("_refs") != string::npos && add_change) {
893 
902  // Determine if NULL attr needs to be processed
903  string ref_type = key.substr(0, key.length() - 5);
904  bool link_with_attr =
905  client()->mgr()->config_json_parser()-> \
906  IsLinkWithAttr(obj_type, ref_type);
907 
908  // Get a pointer to the _refs json Value
909  Value *v = &doc[key.c_str()];
910 
911  assert(v->IsArray());
912  for (SizeType i = 0; i < v->Size(); i++) {
913 
914  // Process NULL attr
915  Value &va = (*v)[i];
916  if (link_with_attr) {
917  if (va["attr"].IsNull()) {
918  (*v)[i].RemoveMember("attr");
919  Value vm;
920  (*v)[i].AddMember("attr", vm.SetObject(), a);
921  }
922  }
923 
932  Value &uuidVal = va["uuid"];
933  const string ref_uuid = uuidVal.GetString();
934  string ref_fq_name = client()->FindFQName(ref_uuid);
935 
936  if (ref_fq_name == "ERROR") {
937  // ref_fq_name not in FQNameCache
938  // If we cannot find ref_fq_name in the doc
939  // as well, return false to enable retry.
940  if (!va.HasMember("to")) {
941  CONFIG_CLIENT_DEBUG(ConfigClientReadRetry,
942  "Ref fq_name not available for ", uuid);
943  return false;
944  }
945 
946  ref_fq_name.clear();
947  const Value &name = va["to"];
948  for (Value::ConstValueIterator itr = name.Begin();
949  itr != name.End(); ++itr) {
950  ref_fq_name += itr->GetString();
951  ref_fq_name += ":";
952  }
953  ref_fq_name.erase(ref_fq_name.end()-1);
954  }
955 
956  // Remove ref_fq_name from doc and re-add the
957  // string formatted fq_name.
958  (*v)[i].RemoveMember("to");
959  Value vs1(ref_fq_name.c_str(), a);
960  (*v)[i].AddMember("to", vs1, a);
961  }
962 
963  // For creates/updates, need to update cache json_str
964  // with the new fixed ref_fq_names for _refs.
965  // Remove existing reference in cache and create a new
966  // ref with updated ref_fq_names.
967  Document cacheDoc;
968  string cache_json_str = cache->GetJsonString();
969  cacheDoc.Parse<0>(cache_json_str.c_str());
970  cacheDoc.RemoveMember(key.c_str());
971  Value vr;
972  Value vra;
973  Value refVal;
974  refVal.CopyFrom(*v, a);
975  cacheDoc.AddMember(vr.SetString(key.c_str(), a),
976  refVal, a);
977  StringBuffer sb;
978  Writer<StringBuffer> writer(sb);
979  cacheDoc.Accept(writer);
980  string cache_str = sb.GetString();
981  cache->SetJsonString(cache_str);
982  }
983 
984  if (itr != doc.MemberEnd()) itr++;
985  }
986 
987  if (!notify_update) {
988  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
989  "ETCD SM: Nothing to update");
990  return true;
991  }
992 
993  StringBuffer sb1;
994  Writer<StringBuffer> writer1(sb1);
995  Document refDoc;
996  refDoc.CopyFrom(doc, refDoc.GetAllocator());
997  refDoc.Accept(writer1);
998  string refString = sb1.GetString();
999  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
1000  "ETCD SM: JSON Doc fed to CJP: " + refString);
1001 
1002  ConfigCass2JsonAdapter ccja(uuid, type_str, doc);
1003  client()->mgr()->config_json_parser()->Receive(ccja, add_change);
1004 
1005  return true;
1006 }
1007 
1009  const string &uuid_key) {
1010 
1016  if (client()->FindFQName(uuid_key) == "ERROR") {
1017  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
1018  "ETCD SM: Nothing to delete");
1019  return;
1020  }
1021 
1026  UUIDCacheMap::iterator uuid_iter = uuid_cache_map_.find(uuid_key);
1027  if (uuid_iter == uuid_cache_map_.end()) {
1028  return;
1029  }
1030  UUIDCacheEntry *cache = uuid_iter->second;
1031 
1037  if (cache->IsRetryTimerRunning()) {
1038  cache->DisableEtcdReadRetry(uuid_key);
1039  client()->PurgeFQNameCache(uuid_key);
1040  return;
1041  }
1042 
1051  const string cache_json_str = cache->GetJsonString();
1052  Document delDoc;
1053  delDoc.Parse<0>(cache_json_str.c_str());
1054 
1059  GenerateAndPushJson(uuid_key,
1060  delDoc,
1061  false,
1062  cache);
1063 
1067  uuid_cache_map_.erase(uuid_iter);
1068 
1072  client()->PurgeFQNameCache(uuid_key);
1073 }
1074 
1075 void ConfigEtcdPartition::ProcessUUIDUpdate(const string &uuid_key,
1076  const string &value_str) {
1083  bool is_new = false;
1084  UUIDCacheEntry *cache = GetUUIDCacheEntry(uuid_key,
1085  value_str,
1086  is_new);
1087 
1097  string cache_json_str = cache->GetJsonString();
1098  if (cache_json_str.compare("retry") == 0) {
1099  // If we are retrying due to ref or parent
1100  // fq_name not available previously, cache
1101  // json_str would have been cleared and set
1102  // to retry. Process now like a new create.
1103  cache_json_str = value_str;
1104  is_new = true;
1105  }
1106  Document cacheDoc;
1107  cacheDoc.Parse<0>(cache_json_str.c_str());
1108 
1115  Document updDoc;
1116  updDoc.Parse<0>(value_str.c_str());
1117  string key;
1118 
1123  if (!updDoc.HasMember("fq_name") ||
1124  !updDoc.HasMember("type")) {
1125  CONFIG_CLIENT_WARN(ConfigClientGetRowError,
1126  "fq_name or type not present for ",
1127  "obj_uuid_table with uuid: ", uuid_key);
1128  cache->DisableEtcdReadRetry(uuid_key);
1129  ProcessUUIDDelete(uuid_key);
1130  return;
1131  }
1132 
1143  Value::ConstMemberIterator itr = updDoc.MemberBegin();
1144  while (itr != updDoc.MemberEnd()) {
1145 
1146  key = itr->name.GetString();
1147 
1153  if (key.compare("draft_mode_state") == 0) {
1154  string mode = itr->value.GetString();
1155  if (!mode.empty()) {
1156  client()->PurgeFQNameCache(uuid_key);
1157  DeleteCacheMap(uuid_key);
1158  return;
1159  }
1160  itr = updDoc.EraseMember(itr);
1161  continue;
1162  }
1163 
1170  if (is_new) {
1171  if (key.compare("type") == 0) {
1172  string type = itr->value.GetString();
1173  cache->SetObjType(type);
1174  } else if (key.compare("fq_name") == 0) {
1175  string fq_name;
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();
1180  fq_name += ":";
1181  }
1182  fq_name.erase(fq_name.end()-1);
1183  cache->SetFQName(fq_name);
1184  }
1185  }
1186 
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);
1199  }
1200  assert(cacheDoc.RemoveMember(key.c_str()));
1201  } else {
1202  if (itr != updDoc.MemberEnd()) itr++;
1203  }
1204  }
1205 
1210  cache->SetJsonString(value_str);
1211 
1225  if (!GenerateAndPushJson(uuid_key,
1226  updDoc,
1227  true,
1228  cache)) {
1229  cache->EnableEtcdReadRetry(uuid_key, value_str);
1230  cache->SetJsonString("retry");
1231  } else {
1232  cache->DisableEtcdReadRetry(uuid_key);
1233  }
1234  if (!is_new) {
1235  GenerateAndPushJson(uuid_key,
1236  cacheDoc,
1237  false,
1238  cache);
1239  }
1240 }
1241 
1242 bool ConfigEtcdPartition::IsListOrMapPropEmpty(const string &uuid_key,
1243  const string &lookup_key) {
1244  UUIDCacheMap::iterator uuid_iter = uuid_cache_map_.find(uuid_key);
1245  if (uuid_iter == uuid_cache_map_.end()) {
1246  return true;
1247  }
1248  UUIDCacheEntry *cache = uuid_iter->second;
1249 
1250  return cache->ListOrMapPropEmpty(lookup_key);
1251 }
1252 
1254  return (config_reader_->IsSet());
1255 }
1256 
1258  CHECK_CONCURRENCY("config_client::Reader");
1259 
1260  int num_req_handled = 0;
1261 
1268  for (UUIDProcessSet::iterator it = uuid_process_set_.begin(), itnext;
1269  it != uuid_process_set_.end() &&
1270  !client()->mgr()->is_reinit_triggered();
1271  it = itnext) {
1272 
1273  itnext = it;
1274  ++itnext;
1275 
1276  UUIDProcessRequestType *obj_req = it->second;
1277 
1278  if (obj_req->oper == "CREATE" || obj_req->oper == "UPDATE") {
1279  ProcessUUIDUpdate(obj_req->uuid, obj_req->value);
1280  } else if (obj_req->oper == "DELETE") {
1281  ProcessUUIDDelete(obj_req->uuid);
1282  } else if (obj_req->oper == "EndOfConfig") {
1283  client()->BulkSyncDone();
1284  }
1285  RemoveObjReqEntry(obj_req->uuid);
1286 
1291  if (++num_req_handled == client()->GetMaxRequestsToYield()) {
1292  return false;
1293  }
1294  }
1295 
1296  // Clear the UUID read set if we are currently processing reinit request
1297  if (client()->mgr()->is_reinit_triggered()) {
1298  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
1299  "ETCD SM: Clear UUID process set due to reinit");
1300  uuid_process_set_.clear();
1301  }
1302  assert(uuid_process_set_.empty());
1303  return true;
1304 }
1305 
1307  UUIDProcessSet::iterator req_it =
1308  uuid_process_set_.find(client()->GetUUID(uuid));
1309  delete req_it->second;
1310  uuid_process_set_.erase(req_it);
1311 }
static const std::set< std::string > skip_properties
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 * 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 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)
bool EtcdReadRetryTimerExpired(const string uuid, const string value)
void SetJsonString(const string &value_str)
void DisableEtcdReadRetry(const string uuid)
bool ListOrMapPropEmpty(const string &prop) const
void SetListOrMapPropEmpty(const string &prop, bool empty)
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)
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)
std::string uuid_str_
std::string value_
The TaskScheduler keeps track of what tasks are currently schedulable. When a task is enqueued it is ...
Definition: task.h:307
int GetTaskId(const std::string &name)
Definition: task.cc:884
void Enqueue(Task *task)
Enqueues a task for running. Starts task if all policy rules are met else puts task in waitq....
Definition: task.cc:662
static TaskScheduler * GetInstance()
Definition: task.cc:574
Task is a class to describe a computational task within OpenSDN control plane applications....
Definition: task.h:82
static bool DeleteTimer(Timer *Timer)
Definition: timer.cc:222
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)
Definition: timer.cc:201
WatchAction action() const
Definition: eql_if.h:208
const std::string & key() const
Definition: eql_if.h:213
const kv_map & kvmap() const
Definition: eql_if.h:233
const std::string & value() const
Definition: eql_if.h:218
int err_code() const
Definition: eql_if.h:193
static ConnectionState * GetInstance()
#define CONFIG_CLIENT_DEBUG(obj,...)
#define CONFIG_CLIENT_WARN(obj,...)
static EventManager evm
uint8_t type
Definition: load_balance.h:2
static bool regex_search(const std::string &input, const regex &regex)
Definition: regex.h:26
static bool regex_match(const std::string &input, const regex &regex)
Definition: regex.h:35
Definition: task_int.h:11
#define CHECK_CONCURRENCY(...)
static std::string UTCUsecToString(uint64_t tstamp)
Definition: time_util.h:55
static uint64_t UTCTimestampUsec()
Definition: time_util.h:14
void STLDeleteValues(Container *container)
Definition: util.h:102
boost::uuids::uuid uuid