OpenSDN source code
config_json_parser.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 
6 #include "config_json_parser.h"
7 
8 #include <boost/lexical_cast.hpp>
9 #include <sandesh/request_pipeline.h>
10 #include <string>
11 
13 #include "ifmap/ifmap_log.h"
14 #include "ifmap/ifmap_log_types.h"
16 #include "ifmap/ifmap_server_show_types.h"
17 #include "base/autogen_util.h"
18 #include "schema/bgp_schema_types.h"
19 #include "schema/vnc_cfg_types.h"
20 #include "config-client-mgr/config_client_show_types.h"
21 #include "config-client-mgr/config_client_log_types.h"
25 
26 using contrail_rapidjson::Value;
27 using std::cout;
28 using std::endl;
29 using std::string;
30 
31 #define CONFIG_PARSE_ASSERT(t, condition, key, value) \
32  do { \
33  if (condition) \
34  break; \
35  IFMAP_WARN_LOG(ConfigurationMalformed ## t ## Warning ## Log, \
36  Category::IFMAP, key, value, adapter.type(), \
37  adapter.uuid()); \
38  IFMAP_TRACE(ConfigurationMalformed ## t ## Warning ## Trace, \
39  key, value, adapter.type(), adapter.uuid()); \
40  if (ConfigCass2JsonAdapter::assert_on_parse_error()) \
41  assert(false); \
42  return false; \
43  } while (false)
44 
46 }
47 
49 }
50 
52  ObjectTypeList FilterList;
53  bgp_schema_Server_GenerateObjectTypeList(&FilterList);
54  vnc_cfg_Server_GenerateObjectTypeList(&FilterList);
55  for (ObjectTypeList::iterator it = FilterList.begin();
56  it != FilterList.end(); it++) {
57  AddObjectType(*it);
58  }
59 }
60 
62  vnc_cfg_FilterInfo vnc_filter_info;
63  bgp_schema_FilterInfo bgp_schema_filter_info;
64 
65  bgp_schema_Server_GenerateGraphFilter(&bgp_schema_filter_info);
66  vnc_cfg_Server_GenerateGraphFilter(&vnc_filter_info);
67 
68  for (vnc_cfg_FilterInfo::iterator it = vnc_filter_info.begin();
69  it != vnc_filter_info.end(); it++) {
70  if (it->is_ref_) {
71  AddLinkName(make_pair(it->left_, it->right_),
72  make_pair(it->metadata_, it->linkattr_));
73  } else {
74  AddParentName(make_pair(it->left_, it->right_),
75  it->metadata_);
76  }
77  }
78 
79  for (bgp_schema_FilterInfo::iterator it = bgp_schema_filter_info.begin();
80  it != bgp_schema_filter_info.end(); it++) {
81  if (it->is_ref_) {
82  AddLinkName(make_pair(it->left_, it->right_),
83  make_pair(it->metadata_, it->linkattr_));
84  } else {
85  AddParentName(make_pair(it->left_, it->right_),
86  it->metadata_);
87  }
88  }
89 }
90 
92  WrapperFieldMap wrapper_field_map;
93  bgp_schema_Server_GenerateWrapperPropertyInfo(&wrapper_field_map);
94  vnc_cfg_Server_GenerateWrapperPropertyInfo(&wrapper_field_map);
95  for (WrapperFieldMap::iterator it = wrapper_field_map.begin();
96  it != wrapper_field_map.end(); it++) {
97  AddWrapperField(it->first, it->second);
98  }
99 }
100 
105 }
108 }
109 
110 void ConfigJsonParser::MetadataRegister(const string &metadata,
111  MetadataParseFn parser) {
112  pair<MetadataParseMap::iterator, bool> result =
113  metadata_map_.insert(make_pair(metadata, parser));
114  assert(result.second);
115 }
116 
117 void ConfigJsonParser::MetadataClear(const string &module) {
118  metadata_map_.clear();
119 }
120 
122  const IFMapTable::RequestKey &src) const {
124  retkey->id_type = src.id_type;
125  retkey->id_name = src.id_name;
126  // Tag each DB Request with current generation number
127  retkey->id_seq_num = GetGenerationNumber();
128  return retkey;
129 }
130 
132  IFMapTable::RequestKey *key) const {
133  // Type is the name of the document.
134  Value::ConstMemberIterator itr = adapter.document().MemberBegin();
135  CONFIG_PARSE_ASSERT(Type, autogen::ParseString(itr->name, &key->id_type),
136  "Name", "Bad name");
137 
138  key->id_type = itr->name.GetString();
139 
140  // Name is the fq_name field in the document.
141  const Value &value_node = itr->value;
142  CONFIG_PARSE_ASSERT(FqName, value_node.HasMember("fq_name"), key->id_type,
143  "Missing FQ name");
144  const Value &fq_name_node = value_node["fq_name"];
145  CONFIG_PARSE_ASSERT(FqName, fq_name_node.IsArray(), key->id_type,
146  "FQ name is not an array");
147  CONFIG_PARSE_ASSERT(FqName, fq_name_node.Size(),
148  key->id_type, "FQ name array is empty");
149 
150  size_t i = 0;
151 
152  // Iterate over all items except the last one.
153  for (; i < fq_name_node.Size() - 1; ++i) {
154  key->id_name += fq_name_node[i].GetString();
155  key->id_name += string(":");
156  }
157  key->id_name += fq_name_node[i].GetString();
158 
159  return true;
160 }
161 
163  const Value &key_node, const Value &value_node,
164  const IFMapTable::RequestKey &key, IFMapOrigin::Origin origin,
165  RequestList *req_list, bool add_change) const {
166  string metaname = key_node.GetString();
167  MetadataParseMap::const_iterator loc = metadata_map_.find(metaname);
168  if (loc == metadata_map_.end()) {
169  return true;
170  }
171 
172  // Treat updates with NULL value as deletes.
173  if (add_change && value_node.IsNull())
174  add_change = false;
175  std::unique_ptr<AutogenProperty> pvalue;
176  if (add_change) {
177  bool success = (loc->second)(value_node, &pvalue);
178  CONFIG_PARSE_ASSERT(Property, success, metaname,
179  "No entry in metadata map");
180  } else {
181  const string key = metaname;
182  if (!IsListOrMapPropEmpty(adapter.uuid(), key)) {
183  return true;
184  }
185  }
186  std::replace(metaname.begin(), metaname.end(), '_', '-');
187  InsertRequestIntoQ(origin, "", "", metaname, pvalue, key,
188  add_change, req_list);
189  return true;
190 }
191 
193  const IFMapTable::RequestKey &key, IFMapOrigin::Origin origin,
194  RequestList *req_list, bool add_change) const {
195 
196  Value::ConstMemberIterator doc_itr = adapter.document().MemberBegin();
197  const Value &value_node = doc_itr->value;
198  for (Value::ConstMemberIterator itr = value_node.MemberBegin();
199  itr != value_node.MemberEnd(); ++itr) {
200  ParseOneProperty(adapter, itr->name, itr->value, key, origin,
201  req_list, add_change);
202  }
203 
204  return true;
205 }
206 
208  const Value &ref_entry, IFMapOrigin::Origin origin,
209  const string &refer, const IFMapTable::RequestKey &key,
210  RequestList *req_list, bool add_change) const {
211  const Value& to_node = ref_entry["to"];
212 
213  string from_underscore = key.id_type;
214  std::replace(from_underscore.begin(), from_underscore.end(), '-', '_');
215  string link_name =
216  GetLinkName(from_underscore, refer);
217  CONFIG_PARSE_ASSERT(Reference, !link_name.empty(), refer,
218  "Link name is empty");
219  string metaname = link_name;
220  std::replace(metaname.begin(), metaname.end(), '-', '_');
221 
222  MetadataParseMap::const_iterator loc = metadata_map_.find(metaname);
223  CONFIG_PARSE_ASSERT(Reference, loc != metadata_map_.end(), metaname,
224  "No entry in metadata map");
225 
226  std::unique_ptr<AutogenProperty> pvalue;
227  if (ref_entry.HasMember("attr")) {
228  const Value& attr_node = ref_entry["attr"];
229  bool success = (loc->second)(attr_node, &pvalue);
230  CONFIG_PARSE_ASSERT(ReferenceLinkAttributes, success, metaname,
231  "Link attribute parse error");
232  }
233 
234  string neigh_name;
235  neigh_name += to_node.GetString();
236 
237  InsertRequestIntoQ(origin, refer, neigh_name,
238  link_name, pvalue, key, add_change, req_list);
239 
240  return true;
241 }
242 
244  const Value &arr, const IFMapTable::RequestKey &key,
245  IFMapOrigin::Origin origin, RequestList *req_list,
246  const string &key_str, size_t pos, bool add_change) const {
247  string refer = key_str.substr(0, pos);
248  CONFIG_PARSE_ASSERT(Reference, arr.IsArray(), refer, "Invalid referene");
249  for (size_t i = 0; i < arr.Size(); ++i)
250  ParseRef(adapter, arr[i], origin, refer, key, req_list, add_change);
251  return true;
252 }
253 
255  const IFMapTable::RequestKey &key, IFMapOrigin::Origin origin,
256  RequestList *req_list, bool add_change) const {
257  Value::ConstMemberIterator doc_itr = adapter.document().MemberBegin();
258  const Value &properties = doc_itr->value;
259  for (Value::ConstMemberIterator itr = properties.MemberBegin();
260  itr != properties.MemberEnd(); ++itr) {
261  string key_str = itr->name.GetString();
262  // Skip all the back-refs.
263  if (key_str.find("back_refs") != string::npos) {
264  continue;
265  }
266  size_t pos = key_str.find("_refs");
267  if (pos != string::npos) {
268  ParseOneRef(adapter, itr->value, key, origin, req_list, key_str,
269  pos, add_change);
270  continue;
271  }
272  if (key_str.compare("parent_type") == 0) {
273  const Value& ptype_node = itr->value;
274  CONFIG_PARSE_ASSERT(Parent, ptype_node.IsString(), key_str,
275  "Invalid parent type");
276  pos = key.id_name.find_last_of(":");
277  if (pos != string::npos) {
278  string parent_type = ptype_node.GetString();
279  // Get the parent name from our name.
280  string parent_name = key.id_name.substr(0, pos);
281  string metaname =
282  GetParentName(parent_type,key.id_type);
283  CONFIG_PARSE_ASSERT(Parent, !metaname.empty(), parent_type,
284  "Missing link name");
285  std::unique_ptr<AutogenProperty > pvalue;
286  InsertRequestIntoQ(origin, parent_type,
287  parent_name, metaname, pvalue, key, add_change, req_list);
288  } else {
289  continue;
290  }
291  }
292  }
293 
294  return true;
295 }
296 
298  IFMapOrigin::Origin origin, RequestList *req_list,
299  IFMapTable::RequestKey *key, bool add_change) const {
300  // Update the name and the type into 'key'.
301  if (!ParseNameType(adapter, key)) {
302  return false;
303  }
304 
305  // For each property, we will clone 'key' to create our DBRequest's i.e.
306  // 'key' will never become part of any DBRequest.
307  if (!ParseProperties(adapter, *key, origin, req_list, add_change)){
308  return false;
309  }
310 
311  if (!ParseLinks(adapter, *key, origin, req_list, add_change)) {
312  return false;
313  }
314 
315  return true;
316 }
317 
319  const string &neigh_type, const string &neigh_name,
320  const string &metaname, std::unique_ptr<AutogenProperty> &pvalue,
321  const IFMapTable::RequestKey &key, bool add_change,
322  RequestList *req_list) const {
323 
325  new IFMapServerTable::RequestData(origin, neigh_type, neigh_name);
326  data->metadata = metaname;
327  data->content.reset(pvalue.release());
328 
329  DBRequest *db_request = new DBRequest();
330  db_request->oper = (add_change ? DBRequest::DB_ENTRY_ADD_CHANGE :
332  db_request->key.reset(CloneKey(key));
333  db_request->data.reset(data);
334 
335  req_list->push_back(db_request);
336 }
337 
339  while (!req_list->empty()) {
340  unique_ptr<DBRequest> req(req_list->front());
341  req_list->pop_front();
343  static_cast<IFMapTable::RequestKey *>(req->key.get());
344 
346  key->id_type);
347  if (table != NULL) {
348  table->Enqueue(req.get());
349  } else {
350  IFMAP_TRACE(IFMapTblNotFoundTrace, "Cant find table", key->id_type);
351  }
352  }
353 }
354 
356  bool add_change) {
357  RequestList req_list;
358 
359  if (adapter.document().HasParseError() || !adapter.document().IsObject()) {
360  size_t pos = adapter.document().GetErrorOffset();
361  // GetParseError returns const char *
362  IFMAP_WARN(IFMapJsonLoadError,
363  "Error in parsing JSON message at position",
364  pos, "with error description",
365  boost::lexical_cast<string>(
366  adapter.document().GetParseError()), adapter.uuid());
367  return false;
368  } else {
369  unique_ptr<IFMapTable::RequestKey> key(new IFMapTable::RequestKey());
370  if (!ParseDocument(adapter, IFMapOrigin::CASSANDRA, &req_list, key.get(), add_change)) {
371  STLDeleteValues(&req_list);
372  return false;
373  }
374  EnqueueListToTables(&req_list);
375  }
376  return true;
377 }
378 
380  const RequestPipeline::PipeSpec ps,
381  int stage, int instNum,
383  const ConfigClientInfoReq *request =
384  static_cast<const ConfigClientInfoReq *>(ps.snhRequest_.get());
385  ConfigClientInfoResp *response = new ConfigClientInfoResp();
386  IFMapSandeshContext *sctx =
387  static_cast<IFMapSandeshContext *>(request->module_context("IFMap"));
388 
389  ConfigClientManager *config_mgr =
390  sctx->ifmap_server()->get_config_manager();
391 
392  if (config_mgr->config_amqp_client()) {
393  ConfigAmqpConnInfo amqp_conn_info;
394  config_mgr->config_amqp_client()->GetConnectionInfo(amqp_conn_info);
395  response->set_amqp_conn_info(amqp_conn_info);
396  }
397 
398  ConfigDBConnInfo db_conn_info;
399  config_mgr->config_db_client()->GetConnectionInfo(db_conn_info);
400 
401  ConfigClientManagerInfo client_mgr_info;
402  config_mgr->GetClientManagerInfo(client_mgr_info);
403 
404  response->set_client_manager_info(client_mgr_info);
405  response->set_db_conn_info(db_conn_info);
406  response->set_context(request->context());
407  response->set_more(false);
408  response->Response();
409  return true;
410 }
411 
412 void ConfigClientInfoReq::HandleRequest() const {
415 
416  s0.taskId_ = scheduler->GetTaskId("config::SandeshCmd");
418  s0.instances_.push_back(0);
419 
420  RequestPipeline::PipeSpec ps(this);
421  ps.stages_= boost::assign::list_of(s0).convert_to_container<
422  std::vector<RequestPipeline::StageSpec> >();
423  RequestPipeline rp(ps);
424 }
425 
427  const RequestPipeline::PipeSpec ps,
428  int stage, int instNum,
430  const ConfigClientReinitReq *request =
431  static_cast<const ConfigClientReinitReq *>(ps.snhRequest_.get());
432  ConfigClientReinitResp *response = new ConfigClientReinitResp();
433  IFMapSandeshContext *sctx =
434  static_cast<IFMapSandeshContext *>(request->module_context("IFMap"));
435 
436  ConfigClientManager *config_mgr =
437  sctx->ifmap_server()->get_config_manager();
438 
439  config_mgr->ReinitConfigClient();
440 
441  response->set_success(true);
442  response->set_context(request->context());
443  response->set_more(false);
444  response->Response();
445  return true;
446 }
447 
448 void ConfigClientReinitReq::HandleRequest() const {
451 
452  s0.taskId_ = scheduler->GetTaskId("config::SandeshCmd");
454  s0.instances_.push_back(0);
455 
456  RequestPipeline::PipeSpec ps(this);
457  ps.stages_= boost::assign::list_of(s0).convert_to_container<
458  std::vector<RequestPipeline::StageSpec> >();
459  RequestPipeline rp(ps);
460 }
void GetConnectionInfo(ConfigAmqpConnInfo &info) const
const std::string & uuid() const
const contrail_rapidjson::Document & document() const
void ReinitConfigClient(const ConfigClientOptions &config)
ConfigDbClient * config_db_client() const
ConfigAmqpClient * config_amqp_client() const
void GetClientManagerInfo(ConfigClientManagerInfo &info) const
virtual void GetConnectionInfo(ConfigDBConnInfo &status) const
void AddObjectType(std::string object)
uint64_t GetGenerationNumber() const
bool IsListOrMapPropEmpty(const std::string &uuid_key, const std::string &lookup_key) const
std::map< std::string, std::string > WrapperFieldMap
std::set< std::string > ObjectTypeList
void AddLinkName(LinkMemberPair member_pair, LinkDataPair data_pair)
void AddWrapperField(std::string key, std::string value)
std::string GetLinkName(const std::string &left, const std::string &right) const
void AddParentName(LinkMemberPair member_pair, std::string s)
std::string GetParentName(const std::string &left, const std::string &right) const
bool ParseOneProperty(const ConfigCass2JsonAdapter &adapter, const contrail_rapidjson::Value &key_node, const contrail_rapidjson::Value &value_node, const IFMapTable::RequestKey &key, IFMapOrigin::Origin origin, RequestList *req_list, bool add_change) const
boost::function< bool(const contrail_rapidjson::Value &, std::unique_ptr< AutogenProperty > *) > MetadataParseFn
virtual void SetupGraphFilter()
void InsertRequestIntoQ(IFMapOrigin::Origin origin, const std::string &neigh_type, const std::string &neigh_name, const std::string &metaname, std::unique_ptr< AutogenProperty > &pvalue, const IFMapTable::RequestKey &key, bool add_change, RequestList *req_list) const
MetadataParseMap metadata_map_
bool ParseLinks(const ConfigCass2JsonAdapter &adapter, const IFMapTable::RequestKey &key, IFMapOrigin::Origin origin, RequestList *req_list, bool add_change) const
IFMapServer * ifmap_server_
void MetadataClear(const std::string &module)
bool ParseNameType(const ConfigCass2JsonAdapter &adapter, IFMapTable::RequestKey *key) const
bool ParseDocument(const ConfigCass2JsonAdapter &adapter, IFMapOrigin::Origin origin, RequestList *req_list, IFMapTable::RequestKey *key, bool add_change) const
bool ParseProperties(const ConfigCass2JsonAdapter &adapter, const IFMapTable::RequestKey &key, IFMapOrigin::Origin origin, RequestList *req_list, bool add_change) const
void MetadataRegister(const std::string &metadata, MetadataParseFn parser)
void EnqueueListToTables(RequestList *req_list) const
virtual bool Receive(const ConfigCass2JsonAdapter &adapter, bool add_change)
void SetupSchemaWrapperPropertyInfo()
bool ParseRef(const ConfigCass2JsonAdapter &adapter, const contrail_rapidjson::Value &ref_entry, IFMapOrigin::Origin origin, const std::string &refer, const IFMapTable::RequestKey &key, RequestList *req_list, bool add_change) const
bool ParseOneRef(const ConfigCass2JsonAdapter &adapter, const contrail_rapidjson::Value &arr, const IFMapTable::RequestKey &key, IFMapOrigin::Origin origin, RequestList *req_list, const std::string &key_str, size_t pos, bool add_change) const
virtual void EndOfConfig()
std::list< struct DBRequest * > RequestList
IFMapTable::RequestKey * CloneKey(const IFMapTable::RequestKey &src) const
bool Enqueue(DBRequest *req)
Definition: db_table.cc:221
IFMapServer * ifmap_server()
DB * database()
Definition: ifmap_server.h:83
ConfigClientManager * get_config_manager()
Definition: ifmap_server.h:93
void CleanupStaleEntries()
static IFMapTable * FindTable(DB *db, const std::string &element_type)
Definition: ifmap_table.cc:40
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
static TaskScheduler * GetInstance()
Definition: task.cc:574
#define CONFIG_PARSE_ASSERT(t, condition, key, value)
static bool ConfigClientInfoHandleRequest(const Sandesh *sr, const RequestPipeline::PipeSpec ps, int stage, int instNum, RequestPipeline::InstData *data)
static bool ConfigClientReinitHandleRequest(const Sandesh *sr, const RequestPipeline::PipeSpec ps, int stage, int instNum, RequestPipeline::InstData *data)
#define IFMAP_TRACE(obj,...)
Definition: ifmap_log.h:27
#define IFMAP_WARN(obj,...)
Definition: ifmap_log.h:73
static bool ParseString(const contrail_rapidjson::Value &node, std::string *s)
Definition: autogen_util.h:32
DBOperation oper
Definition: db_table.h:43
@ DB_ENTRY_DELETE
Definition: db_table.h:40
@ DB_ENTRY_ADD_CHANGE
Definition: db_table.h:39
std::unique_ptr< DBRequestKey > key
Definition: db_table.h:49
std::unique_ptr< DBRequestData > data
Definition: db_table.h:50
std::unique_ptr< AutogenProperty > content
boost::shared_ptr< const SandeshRequest > snhRequest_
std::vector< int > instances_
void STLDeleteValues(Container *container)
Definition: util.h:102