OpenSDN source code
config_cassandra_client.cc
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2016 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 <boost/algorithm/string/join.hpp>
11 #include <boost/algorithm/string/predicate.hpp>
12 #include <boost/foreach.hpp>
13 #include <boost/functional/hash.hpp>
14 #include <boost/ptr_container/ptr_map.hpp>
15 #include <boost/uuid/uuid.hpp>
16 #include <map>
17 #include <set>
18 #include <string>
19 #include <utility>
20 #include <vector>
21 
22 #include "base/connection_info.h"
23 #include "base/logging.h"
24 #include "base/regex.h"
25 #include "base/task.h"
26 #include "base/task_annotations.h"
27 #include "base/task_trigger.h"
29 #include "io/event_manager.h"
31 #include "config_factory.h"
32 #include "config_client_log.h"
33 #include "config_client_log_types.h"
34 #include "config_client_show_types.h"
35 #include "sandesh/common/vns_constants.h"
36 
37 using contrail::regex;
40 using std::unique_ptr;
41 using std::multimap;
42 using std::set;
43 using std::string;
44 
45 const string ConfigCassandraClient::kUuidTableName = "obj_uuid_table";
46 const string ConfigCassandraClient::kFqnTableName = "obj_fq_name_table";
47 const string ConfigCassandraClient::kCassClientTaskId = "config_client::Reader";
49  "config_client::ObjectProcessor";
50 
53  int num_workers)
54  : ConfigDbClient(mgr, evm, options), num_workers_(num_workers) {
55  dbif_.reset(ConfigStaticObjectFactory::CreateRef<cass::cql::CqlIf>(
56  evm, config_db_ips(),
59  static_cast<bool>(options.config_db_use_ssl), options.config_db_ca_certs));
60 
61  // Initialized the casssadra connection status;
64 
65  for (int i = 0; i < num_workers_; i++) {
66  partitions_.push_back(
67  ConfigStaticObjectFactory::Create<ConfigCassandraPartition>
68  (this, static_cast<size_t>(i)));
69  }
70 
71  fq_name_reader_.reset(new
73  TaskScheduler::GetInstance()->GetTaskId("config_client::DBReader"),
74  0));
75 }
76 
78  if (dbif_) {
79  // dbif_->Db_Uninit(....);
80  }
81 
83 }
84 
87  while (true) {
88  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug, "Cassandra SM: Db Init");
89  if (!dbif_->Db_Init()) {
90  CONFIG_CLIENT_DEBUG(ConfigCassInitErrorMessage,
91  "Database initialization failed");
92  if (!InitRetry()) return;
93  continue;
94  }
95  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
96  "Cassandra SM: Db SetTableSpace");
97  if (!dbif_->Db_SetTablespace(
98  g_vns_constants.API_SERVER_KEYSPACE_NAME)) {
99  CONFIG_CLIENT_DEBUG(ConfigCassInitErrorMessage,
100  "Setting database keyspace failed");
101  if (!InitRetry()) return;
102  continue;
103  }
104  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
105  "Cassandra SM: Db UseColumnFamily uuidTableName");
106  if (!dbif_->Db_UseColumnfamily(kUuidTableName)) {
107  if (!InitRetry()) return;
108  continue;
109  }
110  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
111  "Cassandra SM: Db UseColumnFamily fqnTableName");
112  if (!dbif_->Db_UseColumnfamily(kFqnTableName)) {
113  if (!InitRetry()) return;
114  continue;
115  }
116  break;
117  }
119  BulkDataSync();
120 }
121 
123  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug, "Cassandra SM: DB uninit");
124  dbif_->Db_Uninit();
125  // If reinit is triggered, return false to abort connection attempt
126  if (mgr()->is_reinit_triggered()) return false;
127  usleep(GetInitRetryTimeUSec());
128  return true;
129 }
130 
133  int worker_id = HashUUID(uuid);
134  return partitions_[worker_id];
135 }
136 
138 ConfigCassandraClient::GetPartition(const string &uuid) const {
139  int worker_id = HashUUID(uuid);
140  return partitions_[worker_id];
141 }
142 
145  assert(worker_id < num_workers_);
146  return partitions_[worker_id];
147 }
148 
149 int ConfigCassandraClient::HashUUID(const string &uuid_str) const {
150  boost::hash<string> string_hash;
151  return string_hash(uuid_str) % num_workers_;
152 }
153 
154 bool ConfigCassandraPartition::ReadObjUUIDTable(const set<string> &req_list) {
155  GenDb::ColListVec col_list_vec;
156 
157  set<string> uuid_list = req_list;
158  vector<GenDb::DbDataValueVec> keys;
159  for (set<string>::const_iterator it = uuid_list.begin();
160  it != uuid_list.end(); it++) {
162  key.push_back(GenDb::Blob(reinterpret_cast<const uint8_t *>
163  (it->c_str()), it->size()));
164  keys.push_back(key);
165  }
166 
167  GenDb::Blob col_filter(reinterpret_cast<const uint8_t *>("d"), 1);
168  GenDb::ColumnNameRange crange;
169  crange.start_ =
170  boost::assign::list_of(GenDb::DbDataValue(col_filter)).convert_to_container<GenDb::DbDataValueVec>();
171 
172  GenDb::FieldNamesToReadVec field_vec;
173  field_vec.push_back(boost::make_tuple("key", true, false, false));
174  field_vec.push_back(boost::make_tuple("column1", false, true, false));
175  field_vec.push_back(boost::make_tuple("value", false, false, true));
176 
177  if (client()->dbif_->Db_GetMultiRow(&col_list_vec,
179  crange, field_vec,
182  BOOST_FOREACH(const GenDb::ColList &col_list, col_list_vec) {
183  assert(col_list.rowkey_.size() == 1);
184  assert(col_list.rowkey_[0].which() == GenDb::DB_VALUE_BLOB);
185  if (col_list.columns_.size()) {
186  GenDb::Blob uuid(boost::get<GenDb::Blob>(col_list.rowkey_[0]));
187  string uuid_str(reinterpret_cast<const char *>(uuid.data()),
188  uuid.size());
189  ProcessObjUUIDTableEntry(uuid_str, col_list);
190  uuid_list.erase(uuid_str);
191  }
192  }
193  } else {
194  // Failure is returned due to connectivity issue or consistency
195  // issues in reading from cassandra
197  CONFIG_CLIENT_WARN(ConfigClientGetRowError,
198  "GetMultiRow failed for table",
200  //
201  // Task is rescheduled to read the request queue
202  // Due to a bug CQL driver from datastax, connection status is
203  // not notified asynchronously. Because of this, polling is the only
204  // choice to determine the cql connection status.
205  // Since there are dedicated threads to read config,
206  // and it is ok to retry by rescheduling the reader task
207  // TODO: Sleep or No Sleep?
208  //
209  return false;
210  }
211 
212  // Delete all stale entries from the data base.
213  BOOST_FOREACH(string uuid_key, uuid_list) {
214  CONFIG_CLIENT_WARN(ConfigClientGetRowError, "Missing row in the table",
216  HandleObjectDelete(uuid_key, false);
217  }
218 
219  // Clear the uuid list.
220  uuid_list.clear();
221  return true;
222 }
223 
224 // Notes on list map property processing:
225 // Separate entries per list/map keys are stored in the ObjUuidCache partition
226 // based on the uuid.
227 // The cache map entries contain a refreshed bit and timestamp in addition to
228 // the values etc.
229 // A set containing list/map property names (updated_list_map_properties) that
230 // have key/value pairs with a new timestamp, a second set
231 // (candidate_list_map_properties) also containing list/map property names that
232 // may require an update given some key/value pairs have been deleted, and a
233 // multimap (list_map_properties) for all the list/map key value pairs in the
234 // new configuration, are build and held in the context(temporary).
235 // These lists are used to determine which list/map properties need to be pushed
236 // to the backend, they are built as columns are parsed. Once all columns are
237 // parsed,
238 // in ListMapPropReviseUpdateList, for each property name in
239 // candidate_list_map_properties we check it is already in the
240 // updated_list_map_property list, if not we proceed to find at least one stale
241 // list/map key value pair with the property name in the ObJUuidCache, if one is
242 // found that requires an update, the property name is added to
243 // updated_list_map_properties.
244 // Once updated_list_map_properties is revised, we iterate through each property
245 // name in it and push all matching key/value pairs in list_map_properties.
246 // ConfigCass2JsonAdapter groups the key value pairs belonging to the same
247 // property so that a single DB request is sent to the
248 // backend.
249 // Deletes are handled by FormDeleteRequestList. Note that deletes are sent
250 // only when all key/value pairs for a given list/map property are removed.
251 // Additionally, the resulting DB request only resets the property_set bit, it
252 // does not clear the entries in the backend.
253 //
254 // parent_or_ref_fq_name_unknown indicates that at least one parent or
255 // ref cannot be found in the FQNameCache, this can happen if the parent or
256 // referred object is not yet read.
260  }
261  std::multimap<string, JsonAdapterDataType> list_map_properties;
264  string obj_type;
265  string fq_name;
269 
270 private:
272 };
273 
275  const GenDb::ColList &col_list) {
276  CassColumnKVVec cass_data_vec;
277 
279 
281 
282  ParseObjUUIDTableEntry(uuid_key, col_list, &cass_data_vec, context);
283  // Ignore draft objects.
284  if (context.ignore_object) {
285  client()->PurgeFQNameCache(uuid_key);
286  DeleteCacheMap(uuid_key);
287  return false;
288  }
289  // If type or fq-name is not present in the db object, ignore the object
290  // and trigger delete of the object.
291  if (context.obj_type.empty() || !context.fq_name_present) {
292  // Handle as delete
293  CONFIG_CLIENT_WARN(ConfigClientGetRowError,
294  "Parsing row response for type/fq_name failed for table",
296  obj->DisableCassandraReadRetry(uuid_key);
297  HandleObjectDelete(uuid_key, false);
298  return false;
299  }
300 
301  obj->SetFQName(context.fq_name);
302  obj->SetObjType(context.obj_type);
303 
304  if (context.parent_or_ref_fq_name_unknown) {
305  obj->EnableCassandraReadRetry(uuid_key);
306  } else {
307  obj->DisableCassandraReadRetry(uuid_key);
308  }
309 
310  ListMapPropReviseUpdateList(uuid_key, context);
311 
312  // Read the context for map and list properties
313  if (context.updated_list_map_properties.size()) {
314  for (set<string>::iterator it =
315  context.updated_list_map_properties.begin();
316  it != context.updated_list_map_properties.end(); it++) {
317  pair<multimap<string, JsonAdapterDataType>::iterator,
318  multimap<string, JsonAdapterDataType>::iterator> ret =
319  context.list_map_properties.equal_range(*it);
320  for (multimap<string, JsonAdapterDataType>::iterator mit =
321  ret.first; mit != ret.second; mit++) {
322  cass_data_vec.push_back(mit->second);
323  }
324  }
325  }
326  GenerateAndPushJson(uuid_key, context.obj_type, cass_data_vec, true);
327  HandleObjectDelete(uuid_key, true);
328  return true;
329 }
330 
332  const GenDb::ColList &col_list, CassColumnKVVec *cass_data_vec,
333  ConfigCassandraParseContext &context) {
334  BOOST_FOREACH(const GenDb::NewCol &ncol, col_list.columns_) {
335  assert(ncol.name->size() == 1);
336  assert(ncol.value->size() == 1);
337  assert(ncol.timestamp->size() == 1);
338 
339  const GenDb::DbDataValue &dname(ncol.name->at(0));
340  assert(dname.which() == GenDb::DB_VALUE_BLOB);
341  GenDb::Blob dname_blob(boost::get<GenDb::Blob>(dname));
342  string key(reinterpret_cast<const char *>(dname_blob.data()),
343  dname_blob.size());
344 
345  const GenDb::DbDataValue &dvalue(ncol.value->at(0));
346  assert(dvalue.which() == GenDb::DB_VALUE_STRING);
347  string value(boost::get<string>(dvalue));
348 
349  const GenDb::DbDataValue &dtimestamp(ncol.timestamp->at(0));
350  assert(dtimestamp.which() == GenDb::DB_VALUE_UINT64);
351  uint64_t timestamp = boost::get<uint64_t>(dtimestamp);
352  ParseObjUUIDTableEachColumnBuildContext(uuid, key, value, timestamp,
353  cass_data_vec, context);
354  }
355 }
356 
358  const string &uuid, const string &key, const string &value,
359  uint64_t timestamp, CassColumnKVVec *cass_data_vec,
360  ConfigCassandraParseContext &context) {
361  // Check whether there was an update to property of ref
362  JsonAdapterDataType adapter(key, value);
363  if (StoreKeyIfUpdated(uuid, &adapter, timestamp, context)) {
364  // Field is updated.. enqueue to parsing
365  cass_data_vec->push_back(adapter);
366  }
367 }
368 
370  const string &uuid_key, const string &obj_type,
371  const CassColumnKVVec &cass_data_vec, bool add_change) {
372 
373  ConfigCass2JsonAdapter ccja(uuid_key, client(), obj_type,
374  cass_data_vec);
375  client()->mgr()->config_json_parser()->Receive(ccja, add_change);
376 }
377 
378 // Post shutdown during reinit, cleanup all previous states and connections
379 // 1. Disconnect from cassandra cluster
380 // 2. Clean FQ Name cache
381 // 3. Delete partitions which inturn will clear up the object cache and
382 // previously enqueued uuid read requests
384  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
385  "Cassandra SM: Post shutdown during re init");
386  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug, "Cassandra SM: Db Uninit");
387  dbif_->Db_Uninit();
390 }
391 
394  ConfigClientMgrDebug, "Cassandra SM: BulkDataSync Started");
396  fq_name_reader_->Set();
397  return true;
398 }
399 
401  // If FQNameReader task has been triggered return true.
402  if (fq_name_reader_->IsSet()) {
403  return true;
404  }
405 
410  BOOST_FOREACH(ConfigCassandraPartition *partition, partitions_) {
411  if (partition->IsTaskTriggered()) {
412  return true;
413  }
414  }
415  return false;
416 }
417 
419  for (ConfigClientManager::ObjectTypeList::const_iterator it =
420  mgr()->config_json_parser()->ObjectTypeListToRead().begin();
421  it != mgr()->config_json_parser()->ObjectTypeListToRead().end();
422  it++) {
423  string column_name;
424  while (true) {
425  // Ensure that FQName reader task aborts on reinit trigger.
426  if (mgr()->is_reinit_triggered()) {
427  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
428  "Cassandra SM: Abort FQName reader on reinit trigger");
429  return true;
430  }
431 
432  // Rowkey is obj-type
434  key.push_back(GenDb::Blob(reinterpret_cast<const uint8_t *>
435  (it->c_str()), it->size()));
436  GenDb::ColumnNameRange crange;
437  if (!column_name.empty()) {
438  GenDb::Blob col_filter(reinterpret_cast<const uint8_t *>
439  (column_name.c_str()), column_name.size());
440  // Start reading the next set of entries from where we ended in
441  // last read
442  crange.start_ =
443  boost::assign::list_of(
444  GenDb::DbDataValue(col_filter)).convert_to_container
446  crange.start_op_ = GenDb::Op::GT;
447  }
448 
449  // In large scale scenarios, each object type may have a large
450  // number of uuid entries. Read a fixed number of entries at a time
451  // to avoid cpu hogging by this thread.
452  crange.count_ = GetFQNameEntriesToRead();
453 
454  GenDb::FieldNamesToReadVec field_vec;
455  field_vec.push_back(boost::make_tuple("key", true, false, false));
456  field_vec.push_back(boost::make_tuple("column1", false, true,
457  false));
458 
459  GenDb::ColList col_list;
460  if (dbif_->Db_GetRow(&col_list, kFqnTableName, key,
461  GenDb::DbConsistency::QUORUM, crange, field_vec)) {
463 
464  // No entries for this obj-type
465  if (!col_list.columns_.size())
466  break;
467 
468  ObjTypeUUIDList uuid_list;
469  ParseFQNameRowGetUUIDList(*it, col_list, uuid_list,
470  &column_name);
471  EnqueueDBSyncRequest(uuid_list);
472 
473  // If we read less than what we sought, it means there are
474  // no more entries for current obj-type. We move to next
475  // obj-type.
476  if (col_list.columns_.size() < GetFQNameEntriesToRead())
477  break;
478  } else {
480  CONFIG_CLIENT_WARN(ConfigClientGetRowError,
481  "GetRow failed for table", kFqnTableName, *it);
482  usleep(GetInitRetryTimeUSec());
483  }
484  }
485  }
486  // At the end of task trigger
487  BOOST_FOREACH(ConfigCassandraPartition *partition, partitions_) {
488  ObjectProcessReq *req = new ObjectProcessReq("EndOfConfig", "", "");
489  partition->Enqueue(req);
490  }
491 
492  return true;
493 }
494 
496  const GenDb::ColList &col_list, ObjTypeUUIDList &uuid_list,
497  string *last_column) {
498  string column_name;
499  BOOST_FOREACH(const GenDb::NewCol &ncol, col_list.columns_) {
500  assert(ncol.name->size() == 1);
501  const GenDb::DbDataValue &dname(ncol.name->at(0));
502  assert(dname.which() == GenDb::DB_VALUE_BLOB);
503  GenDb::Blob dname_blob(boost::get<GenDb::Blob>(dname));
504  column_name = string(reinterpret_cast<const char *>(dname_blob.data()),
505  dname_blob.size());
506  UpdateFQNameCache(column_name, obj_type, uuid_list);
507  }
508 
509  *last_column = column_name;
510  return true;
511 }
512 
514  const string &obj_type, ObjTypeUUIDList &uuid_list) {
515  string uuid_str = FetchUUIDFromFQNameEntry(key);
516  if (uuid_str.empty())
517  return;
518  uuid_list.push_back(make_pair(obj_type, uuid_str));
519  AddFQNameCache(uuid_str, obj_type, key.substr(0, key.rfind(':')));
520 }
521 
523  const string &key) const {
524  size_t temp = key.rfind(':');
525  return (temp == string::npos) ? "" : key.substr(temp+1);
526 }
527 
529  const ObjTypeUUIDList &uuid_list) {
530  for (ObjTypeUUIDList::const_iterator it = uuid_list.begin();
531  it != uuid_list.end(); it++) {
532  EnqueueUUIDRequest("CREATE", it->first, it->second);
533  }
534  return true;
535 }
536 
538  const string &search_string, int inst_num, const string &last_uuid,
539  uint32_t num_entries, vector<ConfigDBUUIDCacheEntry> *entries) const {
540  return GetPartition(inst_num)->UUIDToObjCacheShow(search_string, last_uuid,
541  num_entries, entries);
542 }
543 
544 void ConfigCassandraClient::EnqueueUUIDRequest(string oper, string obj_type,
545  string uuid_str) {
546  ObjectProcessReq *req = new ObjectProcessReq(oper, uuid_str, obj_type);
548 }
549 
551  long num_config_readers_still_processing =
552  bulk_sync_status_.fetch_sub(1);
553  if (num_config_readers_still_processing == 1) {
554  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
555  "Cassandra SM: BulkSyncDone by all readers");
556  mgr()->EndOfConfig();
557  } else {
558  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
559  "Cassandra SM: One reader finished BulkSync");
560  }
561 }
562 
564  bool force_update) {
565  UpdateConnectionInfo(success, force_update);
566 
567  if (success) {
568  // Update connection info
570  process::ConnectionType::DATABASE, "Cassandra",
571  process::ConnectionStatus::UP,
572  dbif_->Db_GetEndpoints(), "Established Cassandra connection");
573  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
574  "Cassandra SM: Established Cassandra connection");
575  } else {
577  process::ConnectionType::DATABASE, "Cassandra",
578  process::ConnectionStatus::DOWN,
579  dbif_->Db_GetEndpoints(), "Lost Cassandra connection");
580  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
581  "Cassandra SM: Lost Cassandra connection");
582  }
583 }
584 
586  const string &lookup_key) {
587  return GetPartition(uuid_key)->IsListOrMapPropEmpty(uuid_key, lookup_key);
588 }
589 
591  ConfigCassandraClient *client, size_t idx)
592  : config_client_(client), worker_id_(idx) {
593  int task_id = TaskScheduler::GetInstance()->GetTaskId("config_client::Reader");
594  config_reader_.reset(new
596  task_id, idx));
597  task_id =
598  TaskScheduler::GetInstance()->GetTaskId("config_client::ObjectProcessor");
600  task_id, idx, bind(&ConfigCassandraPartition::RequestHandler, this, _1),
602 }
603 
605  obj_process_queue_->Shutdown();
606 }
607 
609  obj_process_queue_->Enqueue(req);
610 }
611 
613  AddUUIDToRequestList(req->oper_, req->value_, req->uuid_str_);
614  delete req;
615  return true;
616 }
617 
619  const string &obj_type,
620  const string &uuid_str) {
621  pair<UUIDProcessSet::iterator, bool> ret;
622  bool trigger = uuid_read_set_.empty();
624  new ObjectProcessRequestType(oper, obj_type, uuid_str);
625  ret = uuid_read_set_.insert(make_pair(client()->GetUUID(uuid_str), req));
626  if (ret.second) {
627  if (trigger) {
628  config_reader_->Set();
629  }
630  } else {
631  delete req;
632  ret.first->second->oper = oper;
633  ret.first->second->uuid = uuid_str;
634  }
635 }
636 
638  const string &uuid, bool add_change) {
639  if (!add_change) {
640  ConfigCassandraClient::ObjTypeFQNPair obj_type_fq_name_pair =
641  client()->UUIDToFQName(uuid, true);
642  if (obj_type_fq_name_pair.second == "ERROR") {
643  return;
644  }
645  }
646 
647  bool needNotify = false;
648  std::string obj_type("");
649  ObjectCacheMap::iterator uuid_iter = object_cache_map_.find(uuid);
650  if (uuid_iter == object_cache_map_.end()) {
651  assert(!add_change);
652  return;
653  }
654 
655  CassColumnKVVec cass_data_vec;
656  for (FieldDetailMap::iterator it =
657  uuid_iter->second->GetFieldDetailMap().begin(), itnext;
658  it != uuid_iter->second->GetFieldDetailMap().end();
659  it = itnext) {
660  itnext = it;
661  ++itnext;
662  if (it->first.key == "type") {
663  obj_type = it->first.value;
664  obj_type.erase(remove(obj_type.begin(),
665  obj_type.end(), '\"'), obj_type.end());
666  cass_data_vec.push_back(it->first);
667  }
668 
669  if (it->first.key == "fq_name") {
670  cass_data_vec.push_back(it->first);
671  }
672 
673  if (!add_change || !it->second.refreshed) {
674  if (it->first.key == "type" || it->first.key == "fq_name") {
675  continue;
676  }
677 
678  needNotify = true;
679  cass_data_vec.push_back(it->first);
680  if (add_change) {
681  uuid_iter->second->GetFieldDetailMap().erase(it);
682  }
683  }
684  }
685 
686  if (add_change != true) {
687  object_cache_map_.erase(uuid_iter);
688  }
689  if (needNotify) {
690  GenerateAndPushJson(uuid, obj_type, cass_data_vec, false);
691  }
692  if (!add_change) {
694  }
695 }
696 
698  const string &lookup_key) {
699  string key;
700  ObjectCacheMap::iterator uuid_iter = object_cache_map_.find(uuid_key);
701  if (uuid_iter == object_cache_map_.end()) {
702  return true;
703  }
704 
705  key = "propm:" + lookup_key;
706  FieldDetailMap::iterator lower_bound_it =
707  uuid_iter->second->GetFieldDetailMap().lower_bound(
708  JsonAdapterDataType(key, ""));
709  if (lower_bound_it != uuid_iter->second->GetFieldDetailMap().end() &&
710  boost::starts_with(lower_bound_it->first.key, key)) {
711  return false;
712  }
713  key = "propl:" + lookup_key;
714  lower_bound_it =
715  uuid_iter->second->GetFieldDetailMap().lower_bound(
716  JsonAdapterDataType(key, ""));
717  if (lower_bound_it != uuid_iter->second->GetFieldDetailMap().end() &&
718  boost::starts_with(lower_bound_it->first.key, key)) {
719  return false;
720  }
721  return true;
722 }
723 
725  return (config_reader_->IsSet());
726 }
727 
729  CHECK_CONCURRENCY("config_client::Reader");
730 
731  set<string> bunch_req_list;
732  int num_req_handled = 0;
733  // Config reader task should stop on reinit trigger
734  for (UUIDProcessSet::iterator it = uuid_read_set_.begin(), itnext;
735  it != uuid_read_set_.end() && !client()->mgr()->is_reinit_triggered();
736  it = itnext) {
737  itnext = it;
738  ++itnext;
739  ObjectProcessRequestType *obj_req = it->second;
740 
741  if (obj_req->oper == "CREATE" || obj_req->oper == "UPDATE" ||
742  obj_req->oper == "UPDATE-IMPLICIT") {
743  bunch_req_list.insert(obj_req->uuid);
744  bool is_last = (itnext == uuid_read_set_.end());
745  if (is_last ||
746  bunch_req_list.size() == client()->GetNumReadRequestToBunch()) {
747  if (!ReadObjUUIDTable(bunch_req_list)) {
748  return false;
749  }
750  num_req_handled += bunch_req_list.size();
751  RemoveObjReqEntries(bunch_req_list);
752  if (num_req_handled >= client()->GetMaxRequestsToYield()) {
753  return false;
754  }
755  }
756  continue;
757  } else if (obj_req->oper == "DELETE") {
758  HandleObjectDelete(obj_req->uuid, false);
759  } else if (obj_req->oper == "EndOfConfig") {
760  client()->BulkSyncDone();
761  }
762  RemoveObjReqEntry(obj_req->uuid);
763  if (++num_req_handled == client()->GetMaxRequestsToYield()) {
764  return false;
765  }
766  }
767 
768  // No need to read the object uuid table if reinit is triggered
769  if (!bunch_req_list.empty() && !client()->mgr()->is_reinit_triggered()) {
770  if (!ReadObjUUIDTable(bunch_req_list))
771  return false;
772  RemoveObjReqEntries(bunch_req_list);
773  }
774  // Clear the UUID read set if we are currently processing reinit request
775  if (client()->mgr()->is_reinit_triggered()) {
776  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
777  "Cassandra SM: Clear UUID read set due to reinit");
778  uuid_read_set_.clear();
779  }
780  assert(uuid_read_set_.empty());
781  return true;
782 }
783 
785  BOOST_FOREACH(string uuid, req_list) {
787  }
788  req_list.clear();
789 }
790 
792  UUIDProcessSet::iterator req_it =
793  uuid_read_set_.find(client()->GetUUID(uuid));
794  delete req_it->second;
795  uuid_read_set_.erase(req_it);
796 }
797 
798 
799 boost::asio::io_context *ConfigCassandraPartition::ioservice() {
800  return client()->event_manager()->io_service();
801 }
802 
805  ObjectCacheMap::iterator uuid_iter = object_cache_map_.find(uuid);
806  if (uuid_iter == object_cache_map_.end())
807  return NULL;
808  return uuid_iter->second;
809 }
810 
813  ObjectCacheMap::const_iterator uuid_iter = object_cache_map_.find(uuid);
814  if (uuid_iter == object_cache_map_.end())
815  return NULL;
816  return uuid_iter->second;
817 }
818 
820  const ObjCacheEntry *obj) const {
821  uint32_t retry_time_pow_of_two =
824  return ((1 << retry_time_pow_of_two) * kMinUUIDRetryTimeMSec);
825 }
826 
828  if (retry_timer_) {
830  }
831 }
832 
834  const string uuid) {
835  if (!retry_timer_) {
836  retry_timer_ = TimerManager::CreateTimer(
837  *parent_->client()->event_manager()->io_service(),
838  "UUID retry timer for " + uuid,
840  "config_client::Reader"),
841  parent_->worker_id_);
842  CONFIG_CLIENT_DEBUG(ConfigClientReadRetry,
843  "Created UUID read retry timer ", uuid);
844  }
845  retry_timer_->Cancel();
846  retry_timer_->Start(parent_->UUIDRetryTimeInMSec(this),
847  boost::bind(
849  this, uuid),
850  boost::bind(
852  this));
853  CONFIG_CLIENT_DEBUG(ConfigClientReadRetry,
854  "Start/restart UUID Read Retry timer due to configuration", uuid);
855 }
856 
858  const string uuid) {
859  if (retry_timer_) {
860  retry_timer_->Cancel();
861  TimerManager::DeleteTimer(retry_timer_);
862  retry_timer_ = NULL;
863  retry_count_ = 0;
864  CONFIG_CLIENT_DEBUG(ConfigClientReadRetry,
865  "UUID Read retry timer - deleted timer due to configuration",
866  uuid);
867  }
868 }
869 
871  if (retry_timer_)
872  return (retry_timer_->running());
873  return false;
874 }
875 
877  const string uuid) {
878  parent_->client()->mgr()->EnqueueUUIDRequest(
879  "UPDATE", GetObjType(), parent_->client()->uuid_str(uuid));
880  retry_count_++;
881  CONFIG_CLIENT_DEBUG(ConfigClientReadRetry, "timer expired ", uuid);
882  return false;
883 }
884 
885 void
887  std::string message = "Timer";
888  CONFIG_CLIENT_WARN(ConfigClientGetRowError,
889  "UUID Read Retry Timer error ", message, message);
890 }
891 
893  const string &uuid, ConfigCassandraParseContext &context) {
894  for (set<string>::iterator it =
895  context.candidate_list_map_properties.begin();
896  it != context.candidate_list_map_properties.end(); it++) {
897  if (context.updated_list_map_properties.find(*it) !=
898  context.updated_list_map_properties.end()) {
899  continue;
900  }
901  ObjectCacheMap::iterator uuid_iter = object_cache_map_.find(uuid);
902  assert(uuid_iter != object_cache_map_.end());
903  FieldDetailMap::iterator field_iter =
904  uuid_iter->second->GetFieldDetailMap().lower_bound(
905  JsonAdapterDataType(*it, ""));
906  assert(field_iter != uuid_iter->second->GetFieldDetailMap().end());
907  assert(it->compare(0, it->size() - 1, field_iter->first.key,
908  0, it->size() - 1) == 0);
909  while (it->compare(0, it->size() - 1, field_iter->first.key,
910  0, it->size() - 1) == 0) {
911  if (field_iter->second.refreshed == false) {
912  context.updated_list_map_properties.insert(*it);
913  break;
914  }
915  field_iter++;
916  }
917  }
918 }
919 
921  JsonAdapterDataType *adapter, uint64_t timestamp,
922  ConfigCassandraParseContext &context) {
923  ObjectCacheMap::iterator uuid_iter = object_cache_map_.find(uuid);
924  assert(uuid_iter != object_cache_map_.end());
925  size_t from_front_pos = adapter->key.find(':');
926  size_t from_back_pos = adapter->key.rfind(':');
927  string type_field = adapter->key.substr(0, from_front_pos+1);
928  bool is_ref = (type_field == ConfigCass2JsonAdapter::ref_prefix);
929  bool is_parent = (type_field == ConfigCass2JsonAdapter::parent_prefix);
930  bool is_propl = (type_field == ConfigCass2JsonAdapter::list_prop_prefix);
931  bool is_propm = (type_field == ConfigCass2JsonAdapter::map_prop_prefix);
932  bool is_prop = (type_field == ConfigCass2JsonAdapter::prop_prefix);
933  if (is_prop) {
934  string prop_name = adapter->key.substr(from_front_pos+1);
935  //
936  // properties like perms2 has no importance to control-node/dns
937  // This property is present on each config object. Hence skipping such
938  // properties gives performance improvement
939  //
940  if (ConfigClientManager::skip_properties.find(prop_name) !=
942  if ((prop_name.compare("draft_mode_state") == 0) &&
943  !adapter->value.empty()) {
944  context.ignore_object = true;
945  }
946  return false;
947  }
948  }
949 
950  string prop_name = "";
951  if (is_ref || is_parent) {
952  string ref_uuid = adapter->key.substr(from_back_pos+1);
953 
954  string ref_name = client()->UUIDToFQName(ref_uuid).second;
955  if (ref_name == "ERROR") {
956  context.parent_or_ref_fq_name_unknown = true;
957  CONFIG_CLIENT_DEBUG(ConfigClientReadRetry,
958  "Out of order parent or ref", uuid + ":" + adapter->key);
959  return false;
960  }
961  if (is_ref) {
962  adapter->ref_fq_name = ref_name;
963  }
964  } else if (is_propl || is_propm) {
965  prop_name = adapter->key.substr(0, from_back_pos);
966 
967  context.list_map_properties.insert(make_pair(prop_name, *adapter));
968  }
969 
970  if (adapter->key.compare("type") == 0) {
971  if (context.obj_type.empty()) {
972  context.obj_type = adapter->value;
973  context.obj_type.erase(remove(context.obj_type.begin(),
974  context.obj_type.end(), '\"'), context.obj_type.end());
975  }
976  } else if (adapter->key.compare("fq_name") == 0) {
977  context.fq_name_present = true;
978  if (context.fq_name.empty()) {
979  context.fq_name = adapter->value.substr(1, adapter->value.size()-2);
980  context.fq_name.erase(remove(context.fq_name.begin(),
981  context.fq_name.end(), '\"'), context.fq_name.end());
982  context.fq_name.erase(remove(context.fq_name.begin(),
983  context.fq_name.end(), ' '), context.fq_name.end());
984  replace(context.fq_name.begin(), context.fq_name.end(), ',', ':');
985  }
986  }
987  FieldDetailMap::iterator field_iter =
988  uuid_iter->second->GetFieldDetailMap().find(*adapter);
989  if (field_iter == uuid_iter->second->GetFieldDetailMap().end()) {
990  // seeing field for first time
991  FieldTimeStampInfo field_ts_info;
992  field_ts_info.refreshed = true;
993  field_ts_info.time_stamp = timestamp;
994  uuid_iter->second->GetFieldDetailMap().insert(make_pair
995  (*adapter, field_ts_info));
996  } else {
997  field_iter->second.refreshed = true;
998  if (client()->SkipTimeStampCheckForTypeAndFQName() &&
999  ((adapter->key.compare("type") == 0) ||
1000  (adapter->key.compare("fq_name") == 0))) {
1001  return true;
1002  }
1003  if (timestamp && field_iter->second.time_stamp == timestamp) {
1004  if (is_propl || is_propm) {
1005  context.candidate_list_map_properties.insert(prop_name);
1006  }
1007  return false;
1008  }
1009  field_iter->second.time_stamp = timestamp;
1010  }
1011  if (is_propl || is_propm) {
1012  context.updated_list_map_properties.insert(prop_name);
1013  return false;
1014  } else {
1015  return true;
1016  }
1017 }
1018 
1021  ObjectCacheMap::iterator uuid_iter = object_cache_map_.find(uuid);
1022  if (uuid_iter == object_cache_map_.end()) {
1023  ObjCacheEntry *obj;
1024  string tmp_uuid = uuid;
1025  obj = new ObjCacheEntry(this, UTCTimestampUsec());
1026  pair<ObjectCacheMap::iterator, bool> ret_uuid =
1027  object_cache_map_.insert(tmp_uuid, obj);
1028  assert(ret_uuid.second);
1029  uuid_iter = ret_uuid.first;
1030  } else {
1031  uuid_iter->second->SetLastReadTimeStamp(UTCTimestampUsec());
1032  }
1033  for (FieldDetailMap::iterator it =
1034  uuid_iter->second->GetFieldDetailMap().begin();
1035  it != uuid_iter->second->GetFieldDetailMap().end(); it++) {
1036  it->second.refreshed = false;
1037  }
1038  return uuid_iter->second;
1039 }
1040 
1042  ObjectCacheMap::const_iterator uuid_iter,
1043  ConfigDBUUIDCacheEntry *entry) const {
1044  entry->set_uuid(uuid);
1045  entry->set_timestamp(
1046  UTCUsecToString(uuid_iter->second->GetLastReadTimeStamp()));
1047  entry->set_retry_count(uuid_iter->second->GetRetryCount());
1048  entry->set_fq_name(uuid_iter->second->GetFQName());
1049  entry->set_obj_type(uuid_iter->second->GetObjType());
1050  entry->set_timer_running(uuid_iter->second->IsRetryTimerRunning());
1051  entry->set_timer_created(uuid_iter->second->IsRetryTimerCreated());
1052  vector<ConfigDBUUIDCacheData> fields;
1053  for (FieldDetailMap::const_iterator it =
1054  uuid_iter->second->GetFieldDetailMap().begin();
1055  it != uuid_iter->second->GetFieldDetailMap().end(); it++) {
1056  ConfigDBUUIDCacheData each_field;
1057  each_field.set_refresh(it->second.refreshed);
1058  each_field.set_field_name(it->first.key);
1059  each_field.set_timestamp(UTCUsecToString(it->second.time_stamp));
1060  fields.push_back(each_field);
1061  }
1062  entry->set_field_list(fields);
1063 }
1064 
1066  const string &search_string, const string &last_uuid, uint32_t num_entries,
1067  vector<ConfigDBUUIDCacheEntry> *entries) const {
1068  uint32_t count = 0;
1069  regex search_expr(search_string);
1070  for (ObjectCacheMap::const_iterator it =
1071  object_cache_map_.upper_bound(last_uuid);
1072  count < num_entries && it != object_cache_map_.end(); it++) {
1073  if (regex_search(it->first, search_expr) ||
1074  regex_search(it->second->GetObjType(), search_expr) ||
1075  regex_search(it->second->GetFQName(), search_expr)) {
1076  count++;
1077  ConfigDBUUIDCacheEntry entry;
1078  FillUUIDToObjCacheInfo(it->first, it, &entry);
1079  entries->push_back(entry);
1080  }
1081  }
1082  return true;
1083 }
static const std::string parent_prefix
static const std::string prop_prefix
static const std::string map_prop_prefix
static const std::string ref_prefix
static const std::string list_prop_prefix
ConfigCassandraPartition * GetPartition(const std::string &uuid)
virtual bool IsListOrMapPropEmpty(const string &uuid_key, const string &lookup_key)
std::atomic< long > bulk_sync_status_
bool EnqueueDBSyncRequest(const ObjTypeUUIDList &uuid_list)
static const std::string kUuidTableName
virtual bool UUIDToObjCacheShow(const std::string &search_string, int inst_num, const std::string &last_uuid, uint32_t num_entries, std::vector< ConfigDBUUIDCacheEntry > *entries) const
virtual int HashUUID(const std::string &uuid_str) const
std::list< ObjTypeUUIDType > ObjTypeUUIDList
boost::scoped_ptr< TaskTrigger > fq_name_reader_
virtual std::string FetchUUIDFromFQNameEntry(const std::string &key) const
static const std::string kFqnTableName
static const std::string kObjectProcessTaskId
void EnqueueUUIDRequest(std::string oper, std::string obj_type, std::string uuid_str)
void UpdateFQNameCache(const std::string &key, const std::string &obj_type, ObjTypeUUIDList &uuid_list)
void HandleCassandraConnectionStatus(bool success, bool force_update=false)
virtual bool IsTaskTriggered() const
bool ParseFQNameRowGetUUIDList(const std::string &obj_type, const GenDb::ColList &col_list, ObjTypeUUIDList &uuid_list, std::string *last_column)
static const std::string kCassClientTaskId
virtual uint32_t GetFQNameEntriesToRead() const
ConfigCassandraClient(ConfigClientManager *mgr, EventManager *evm, const ConfigClientOptions &options, int num_workers)
void EnableCassandraReadRetry(const std::string uuid)
bool CassReadRetryTimerExpired(const std::string uuid)
void DisableCassandraReadRetry(const std::string uuid)
void RemoveObjReqEntry(std::string &uuid)
static const uint32_t kMinUUIDRetryTimeMSec
void ParseObjUUIDTableEachColumnBuildContext(const std::string &uuid, const std::string &key, const std::string &value, uint64_t timestamp, CassColumnKVVec *cass_data_vec, ConfigCassandraParseContext &context)
ObjProcessWorkQType obj_process_queue_
void DeleteCacheMap(const std::string &uuid)
virtual bool ReadObjUUIDTable(const std::set< std::string > &uuid_list)
void AddUUIDToRequestList(const std::string &oper, const std::string &obj_type, const std::string &uuid_str)
bool RequestHandler(ObjectProcessReq *req)
ConfigCassandraClient * client()
bool IsListOrMapPropEmpty(const string &uuid_key, const string &lookup_key)
boost::asio::io_context * ioservice()
virtual void GenerateAndPushJson(const string &uuid_key, const string &obj_type, const CassColumnKVVec &cass_data_vec, bool add_change)
bool UUIDToObjCacheShow(const std::string &search_string, const std::string &last_uuid, uint32_t num_entries, std::vector< ConfigDBUUIDCacheEntry > *entries) const
virtual int UUIDRetryTimeInMSec(const ObjCacheEntry *obj) const
virtual void HandleObjectDelete(const string &uuid, bool add_change)
bool ProcessObjUUIDTableEntry(const std::string &uuid_key, const GenDb::ColList &col_list)
boost::shared_ptr< TaskTrigger > config_reader_
ObjCacheEntry * GetObjCacheEntry(const std::string &uuid)
ConfigCassandraPartition(ConfigCassandraClient *client, size_t idx)
void Enqueue(ObjectProcessReq *req)
ObjCacheEntry * MarkCacheDirty(const std::string &uuid)
static const uint32_t kMaxUUIDRetryTimePowOfTwo
void ListMapPropReviseUpdateList(const std::string &uuid, ConfigCassandraParseContext &context)
void RemoveObjReqEntries(std::set< std::string > &req_list)
bool StoreKeyIfUpdated(const std::string &uuid, JsonAdapterDataType *adapter, uint64_t timestamp, ConfigCassandraParseContext &context)
virtual void ParseObjUUIDTableEntry(const std::string &uuid, const GenDb::ColList &col_list, CassColumnKVVec *cass_data_vec, ConfigCassandraParseContext &context)
void FillUUIDToObjCacheInfo(const std::string &uuid, ObjectCacheMap::const_iterator uuid_iter, ConfigDBUUIDCacheEntry *entry) const
static const std::set< std::string > skip_properties
ConfigJsonParserBase * config_json_parser()
virtual std::string uuid_str(const std::string &uuid)
EventManager * event_manager()
std::pair< std::string, std::string > ObjTypeFQNPair
const std::vector< std::string > & config_db_ips() const
ObjTypeFQNPair UUIDToFQName(const std::string &uuid_str, bool deleted_ok=true) const
virtual uint32_t GetNumReadRequestToBunch() const
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)
const std::string & config_db_password() const
virtual void InitConnectionInfo()
virtual void PurgeFQNameCache(const std::string &uuid)
virtual void ClearFQNameCache()
ConfigClientManager * mgr()
const std::string & config_db_user() const
virtual const uint64_t GetInitRetryTimeUSec() const
const ObjectTypeList & ObjectTypeListToRead() const
virtual bool Receive(const ConfigCass2JsonAdapter &adapter, bool add_change)=0
boost::asio::io_context * io_service()
Definition: event_manager.h:43
virtual void SetFQName(std::string fq_name)
virtual void SetObjType(std::string obj_type)
std::string uuid_str_
std::string value_
int GetTaskId(const std::string &name)
Definition: task.cc:884
static TaskScheduler * GetInstance()
Definition: task.cc:574
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
static ConnectionState * GetInstance()
#define CONFIG_CLIENT_DEBUG(obj,...)
#define CONFIG_CLIENT_WARN(obj,...)
static EventManager evm
std::vector< JsonAdapterDataType > CassColumnKVVec
@ DB_VALUE_UINT64
Definition: gendb_if.h:91
@ DB_VALUE_STRING
Definition: gendb_if.h:90
@ DB_VALUE_BLOB
Definition: gendb_if.h:98
std::vector< DbDataValue > DbDataValueVec
Definition: gendb_if.h:101
boost::variant< boost::blank, std::string, uint64_t, uint32_t, boost::uuids::uuid, uint8_t, uint16_t, double, IpAddress, Blob > DbDataValue
Definition: gendb_if.h:86
std::vector< FieldNamesToReadInfo > FieldNamesToReadVec
Definition: gendb_if.h:239
boost::ptr_vector< ColList > ColListVec
Definition: gendb_if.h:209
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
std::multimap< string, JsonAdapterDataType > list_map_properties
DISALLOW_COPY_AND_ASSIGN(ConfigCassandraParseContext)
size_t size() const
Definition: gendb_if.h:64
const uint8_t * data() const
Definition: gendb_if.h:61
NewColVec columns_
Definition: gendb_if.h:200
DbDataValueVec rowkey_
Definition: gendb_if.h:199
DbDataValueVec start_
Definition: gendb_if.h:226
boost::scoped_ptr< DbDataValueVec > value
Definition: gendb_if.h:182
boost::scoped_ptr< DbDataValueVec > timestamp
Definition: gendb_if.h:184
boost::scoped_ptr< DbDataValueVec > name
Definition: gendb_if.h:181
#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