OpenSDN source code
session_stats_collector.cc
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2017 Juniper Networks, Inc. All rights reserved.
3  * Copyright Contributors to the OpenSDN project
4  */
5 
6 #include <bitset>
7 #include <pkt/flow_table.h>
9 #include <uve/stats_collector.h>
11 #include <sandesh/common/flow_types.h>
12 #include <init/agent_param.h>
15 #include <oper/tag.h>
17 #include <oper/global_vrouter.h>
19 #include <vrouter/flow_stats/flow_stats_types.h>
20 #include <cmn/agent_factory.h>
21 
22 // setting work queue max size as 4M
23 #define DEFAULT_SSC_REQUEST_QUEUE_SIZE 4*1024*1024
24 #define MAX_SSC_REQUEST_QUEUE_ITERATIONS 256
25 
27  "SessionStats", 4000));
28 
29 bool session_debug_ = false;
31  AgentUveBase *uve,
32  uint32_t instance_id,
33  FlowStatsManager *aging_module,
35  StatsCollector(TaskScheduler::GetInstance()->GetTaskId
36  (kTaskSessionStatsCollector), instance_id,
37  io, kSessionStatsTimerInterval, "Session stats collector"),
38  agent_uve_(uve),
39  task_id_(uve->agent()->task_scheduler()->GetTaskId
41  session_ep_iteration_key_(), session_agg_iteration_key_(),
42  session_iteration_key_(),
43  request_queue_(agent_uve_->agent()->task_scheduler()->
45  instance_id,
46  boost::bind(&SessionStatsCollector::RequestHandler,
47  this, _1),
50  session_msg_list_(agent_uve_->agent()->params()->max_endpoints_per_session_msg(),
51  SessionEndpoint()),
52  session_msg_index_(0), instance_id_(instance_id),
53  flow_stats_manager_(aging_module), parent_(obj), session_task_(NULL),
54  current_time_(GetCurrentTime()), session_task_starts_(0) {
55  request_queue_.set_name("Session stats collector event queue");
59  (boost::bind(&SessionStatsCollector::RequestHandlerEntry, this));
61  (boost::bind(&SessionStatsCollector::RequestHandlerExit, this, _1));
63  InitDone();
64 }
65 
68 }
69 
71  return UTCTimestampUsec();
72 }
73 
77 }
78 
80  if (agent_uve_->agent()->slo_table()) {
82  boost::bind(&SessionStatsCollector::SloNotify, this,
83  _1, _2));
84  }
85 }
86 
88  if (session_endpoint_map_.size() == 0) {
89  return true;
90  }
91 
92  // Start task to scan the entries
93  if (session_task_ == NULL) {
95 
96  if (session_debug_) {
97  LOG(DEBUG,
99  << " SessionTasks Num " << session_task_starts_
100  << " session_ep visited " << session_ep_visited_
101  << " Request count " << request_queue_.Length());
102  }
104  session_task_ = new SessionTask(this);
106  }
107  return true;
108 }
109 
110 
112  uint64_t curr_time = FlowStatsCollector::GetCurrentTime();
113  bool export_rate_calculated = false;
114  uint32_t exp_rate_without_sampling = 0;
115 
116  /* If flows are not being exported, no need to update threshold */
117  if (!session_export_count_) {
118  return true;
119  }
120 
121  // Calculate Flow Export rate
123  uint64_t diff_secs = 0;
124  uint64_t diff_micro_secs = curr_time -
126  if (diff_micro_secs) {
127  diff_secs = diff_micro_secs/1000000;
128  }
129  if (diff_secs) {
132  exp_rate_without_sampling =
135  export_rate_calculated = true;
136  }
137  } else {
140  return true;
141  }
142 
143  uint32_t cfg_rate = agent_->oper_db()->global_vrouter()->
144  flow_export_rate();
145  /* No need to update threshold when flow_export_rate is NOT calculated
146  * and configured flow export rate has not changed */
147  if (!export_rate_calculated &&
148  (cfg_rate == prev_cfg_flow_export_rate_)) {
149  return true;
150  }
151  uint64_t cur_t = threshold(), new_t = 0;
152  // Update sampling threshold based on flow_export_rate_
153  if (session_export_rate_ < ((double)cfg_rate) * 0.8) {
154  /* There are two reasons why we can be here.
155  * 1. None of the flows were sampled because we never crossed
156  * 80% of configured flow-export-rate.
157  * 2. In scale setups, the threshold was updated to high value because
158  * of which flow-export-rate has dropped drastically.
159  * Threshold should be updated here depending on which of the above two
160  * situations we are in. */
163  } else {
164  if (session_export_rate_ < ((double)cfg_rate) * 0.5) {
165  UpdateThreshold((threshold_ / 4), false);
166  } else {
167  UpdateThreshold((threshold_ / 2), false);
168  }
169  }
170  } else if (session_export_rate_ > (cfg_rate * 3)) {
171  UpdateThreshold((threshold_ * 4), true);
172  } else if (session_export_rate_ > (cfg_rate * 2)) {
173  UpdateThreshold((threshold_ * 3), true);
174  } else if (session_export_rate_ > ((double)cfg_rate) * 1.25) {
175  UpdateThreshold((threshold_ * 2), true);
176  }
177  prev_cfg_flow_export_rate_ = cfg_rate;
178  new_t = threshold();
179  FLOW_EXPORT_STATS_TRACE(session_export_rate_, exp_rate_without_sampling,
180  cur_t, new_t);
181  return true;
182 }
183 
185 // Utility methods to enqueue events into work-queue
188  boost::shared_ptr<SessionStatsReq>
190  GetCurrentTime()));
191  request_queue_.Enqueue(req);
192 }
193 
195  const RevFlowDepParams &params) {
196  boost::shared_ptr<SessionStatsReq>
198  GetCurrentTime(), params));
199  request_queue_.Enqueue(req);
200 }
201 
203  uint32_t bytes,
204  uint32_t packets,
205  uint32_t oflow_bytes,
206  const boost::uuids::uuid &u) {
207  boost::shared_ptr<SessionStatsReq>
209  bytes, packets, oflow_bytes, u));
210  request_queue_.Enqueue(req);
211 }
212 
213 void SessionStatsCollector::DispatchSessionMsg(const std::vector<SessionEndpoint> &lst) {
216  SESSION_ENDPOINT_OBJECT_LOG("", SandeshLevel::SYS_INFO, lst);
217 }
218 
221  if (session_msg_index_ ==
224  session_msg_index_ = 0;
225  }
226 }
227 
229  if (session_msg_index_ == 0) {
230  return;
231  }
232 
233  vector<SessionEndpoint>::const_iterator first = session_msg_list_.begin();
234  vector<SessionEndpoint>::const_iterator last = session_msg_list_.begin() +
236  vector<SessionEndpoint> new_list(first, last);
237  DispatchSessionMsg(new_list);
238  session_msg_index_ = 0;
239 }
240 
242  SessionEndpoint &obj = session_msg_list_[session_msg_index_];
243  obj = SessionEndpoint();
244  return session_msg_index_;
245 }
246 
249  return true;
250 }
251 
253 }
254 
255 bool SessionStatsCollector::RequestHandler(boost::shared_ptr<SessionStatsReq> req) {
256  FlowEntry *flow = req->flow();
257  FlowEntry *rflow = req->reverse_flow();
258  FLOW_LOCK(flow, rflow, FlowEvent::FLOW_MESSAGE);
259 
260  switch (req->event()) {
262  AddSession(flow, req->time());
263  break;
264  }
265 
267  DeleteSession(flow, flow->uuid(), req->time(), &req->params());
268  break;
269  }
270 
272  EvictedSessionStatsUpdate(req->flow(), req->bytes(), req->packets(),
273  req->oflow_bytes(), req->uuid());
274  break;
275  }
276 
277  default:
278  assert(0);
279  }
280 
281  return true;
282 }
283 
285  if (vmi_cfg_name != rhs.vmi_cfg_name) {
286  return vmi_cfg_name < rhs.vmi_cfg_name;
287  }
288  if (local_vn != rhs.local_vn) {
289  return local_vn < rhs.local_vn;
290  }
291  if (remote_vn != rhs.remote_vn) {
292  return remote_vn < rhs.remote_vn;
293  }
294  if (local_tagset != rhs.local_tagset) {
295  return local_tagset < rhs.local_tagset;
296  }
297  if (remote_tagset != rhs.remote_tagset) {
298  return remote_tagset < rhs.remote_tagset;
299  }
300  if (remote_prefix != rhs.remote_prefix) {
301  return remote_prefix < rhs.remote_prefix;
302  }
303  if (match_policy != rhs.match_policy) {
304  return match_policy < rhs.match_policy;
305  }
308  }
309  return is_si < rhs.is_si;
310 }
311 
313  if (vmi_cfg_name != rhs.vmi_cfg_name) {
314  return false;
315  }
316  if (local_vn != rhs.local_vn) {
317  return false;
318  }
319  if (remote_vn != rhs.remote_vn) {
320  return false;
321  }
322  if (local_tagset != rhs.local_tagset) {
323  return false;
324  }
325  if (remote_tagset != rhs.remote_tagset) {
326  return false;
327  }
328  if (remote_prefix != rhs.remote_prefix) {
329  return false;
330  }
331  if (match_policy != rhs.match_policy) {
332  return false;
333  }
335  return false;
336  }
337  if (is_si != rhs.is_si) {
338  return false;
339  }
340  return true;
341 }
342 
344  vmi_cfg_name = "";
345  local_vn = "";
346  remote_vn = "";
347  local_tagset.clear();
348  remote_tagset.clear();
349  remote_prefix = "";
350  match_policy = "";
351  is_client_session = false;
352  is_si = false;
353 }
354 
355 bool SessionAggKey::IsLess(const SessionAggKey &rhs) const {
356  if (local_ip != rhs.local_ip) {
357  return local_ip < rhs.local_ip;
358  }
359  if (server_port != rhs.server_port) {
360  return server_port < rhs.server_port;
361  }
362  return proto < rhs.proto;
363 }
364 
365 bool SessionAggKey::IsEqual(const SessionAggKey &rhs) const {
366  if (local_ip != rhs.local_ip) {
367  return false;
368  }
369  if (server_port != rhs.server_port) {
370  return false;
371  }
372  if (proto != rhs.proto) {
373  return false;
374  }
375  return true;
376 }
377 
379  local_ip = IpAddress();
380  server_port = 0;
381  proto = 0;
382 }
383 
384 bool SessionKey::IsLess(const SessionKey &rhs) const {
385  if (remote_ip != rhs.remote_ip) {
386  return remote_ip < rhs.remote_ip;
387  }
388  if (client_port != rhs.client_port) {
389  return client_port < rhs.client_port;
390  }
391  return uuid < rhs.uuid;
392 }
393 
394 bool SessionKey::IsEqual(const SessionKey &rhs) const {
395  if (remote_ip != rhs.remote_ip) {
396  return false;
397  }
398  if (client_port != rhs.client_port) {
399  return false;
400  }
401  if (uuid != rhs.uuid) {
402  return false;
403  }
404  return true;
405 }
406 
408  remote_ip = IpAddress();
409  client_port = 0;
410  uuid = boost::uuids::nil_uuid();
411 }
412 
414  SessionAggKey &session_agg_key,
415  SessionKey &session_key,
416  SessionEndpointKey &session_endpoint_key) {
417  /*
418  * For non local flows always get the key for forward flow entry
419  * If vms are in same compute node (local route)
420  * Vrouter A (Client) <==> Vrouter B (Server)
421  * A->B (Ingress + Forwarding + Local)
422  * B->A (Ingress + Reverse + Local)
423  *
424  * If vms are in different compute nodes
425  * Vrouter A (Client) <==> Vrouter B (Server)
426  * A->B (Ingress + Forwarding) A->B (Egresss + Forward)
427  * B->A (Egress + Reverse) B->A (Ingress + Reverse)
428  */
429 
430  /*
431  * If it is non local reverse flow then NOP, actual
432  * config will be handled in fwd flow
433  */
434  if ((!(fe->is_flags_set(FlowEntry::LocalFlow))) &&
436  return false;
437  }
438 
439  const Interface *itf = fe->intf_entry();
440  if (!itf) {
441  return false;
442  }
443 
444  if (itf->type() != Interface::VM_INTERFACE) {
445  return false;
446  }
447 
448  const VmInterface *vmi = static_cast<const VmInterface *>(itf);
449  if (vmi->cfg_name().empty()) {
450  return false;
451  }
452  const string &src_vn = !fe->data().origin_vn_src.empty() ?
453  fe->data().origin_vn_src :
454  fe->data().source_vn_match;
455  const string &dst_vn = !fe->data().origin_vn_dst.empty() ?
456  fe->data().origin_vn_dst :
457  fe->data().dest_vn_match;
458 
459  session_endpoint_key.vmi_cfg_name = vmi->cfg_name();
460  session_endpoint_key.local_tagset = fe->local_tagset();
461  session_endpoint_key.remote_tagset = fe->remote_tagset();
462  session_endpoint_key.remote_prefix = fe->RemotePrefix();
463  session_endpoint_key.match_policy = fe->fw_policy_name_uuid();
464  if (vmi->service_intf_type().empty()) {
465  session_endpoint_key.is_si = false;
466  } else {
467  session_endpoint_key.is_si= true;
468  }
469 
470  if (fe->IsClientFlow()) {
471  session_agg_key.local_ip = fe->key().src_addr;
472  session_agg_key.server_port = fe->key().dst_port;
473  session_key.remote_ip = fe->key().dst_addr;
474  session_key.client_port = fe->key().src_port;
475  session_endpoint_key.local_vn = src_vn;
476  session_endpoint_key.remote_vn = dst_vn;
477  session_endpoint_key.is_client_session = true;
478  } else if (fe->IsServerFlow()) {
479  /*
480  * If it is local flow, then reverse flow
481  * (Ingress + Reverse) will be used to create
482  * the server side session (Egress + Forward)
483  */
485  session_agg_key.local_ip = fe->key().src_addr;
486  session_agg_key.server_port = fe->key().src_port;
487  session_key.remote_ip = fe->key().dst_addr;
488  session_key.client_port = fe->key().dst_port;
489  session_endpoint_key.local_vn = src_vn;
490  session_endpoint_key.remote_vn = dst_vn;
491  } else {
492  session_agg_key.local_ip = fe->key().dst_addr;
493  session_agg_key.server_port = fe->key().dst_port;
494  session_key.remote_ip = fe->key().src_addr;
495  session_key.client_port = fe->key().src_port;
496  session_endpoint_key.local_vn = dst_vn;
497  session_endpoint_key.remote_vn = src_vn;
498  }
499  session_endpoint_key.is_client_session = false;
500  } else {
501  return false;
502  }
503  session_agg_key.proto = fe->key().protocol;
504  session_key.uuid = fe->uuid();
505  return true;
506 }
507 
509  SessionFlowStatsInfo *session_flow) const {
510  session_flow->flow = fe;
511  session_flow->gen_id= fe->gen_id();
512  session_flow->flow_handle = fe->flow_handle();
513  session_flow->uuid = fe->uuid();
514  session_flow->total_bytes = 0;
515  session_flow->total_packets = 0;
516 }
517 
519  uint64_t setup_time, SessionStatsInfo *session) const {
520  FlowEntry *rfe = fe->reverse_flow_entry();
521 
522  session->setup_time = setup_time;
523  session->teardown_time = 0;
524  session->exported_atleast_once = false;
525  UpdateSessionFlowStatsInfo(fe, &session->fwd_flow);
526  UpdateSessionFlowStatsInfo(rfe, &session->rev_flow);
527 }
528 
529 static void BuildTraceTagList(const TagList &slist, vector<string> *dlist) {
530  TagList::const_iterator it = slist.begin();
531  while (it != slist.end()) {
532  dlist->push_back(integerToString(*it));
533  ++it;
534  }
535 }
536 
537 static void TraceSession(const string &op, const SessionEndpointKey &ep,
538  const SessionAggKey &agg, const SessionKey &session,
539  bool rev_flow_params) {
540  SessionTraceInfo info;
541  info.vmi = ep.vmi_cfg_name;
542  info.local_vn = ep.local_vn;
543  info.remote_vn = ep.remote_vn;
544  BuildTraceTagList(ep.local_tagset, &info.local_tagset);
545  BuildTraceTagList(ep.remote_tagset, &info.remote_tagset);
546  info.remote_prefix = ep.remote_prefix;
547  info.match_policy = ep.match_policy;
548  info.is_si = ep.is_si;
549  info.is_client = ep.is_client_session;
550  info.local_ip = agg.local_ip.to_string();
551  info.server_port = agg.server_port;
552  info.protocol = agg.proto;
553  info.remote_ip = session.remote_ip.to_string();
554  info.client_port = session.client_port;
555  info.flow_uuid = to_string(session.uuid);
556  SESSION_STATS_TRACE(Trace, op, info, rev_flow_params);
557 }
558 
559 void SessionStatsCollector::AddSession(FlowEntry* fe, uint64_t setup_time) {
560  SessionAggKey session_agg_key;
561  SessionEndpointInfo::SessionAggMap::iterator session_agg_map_iter;
562  SessionPreAggInfo session_agg_info;
563  SessionStatsInfo session;
564  SessionKey session_key;
565  SessionPreAggInfo::SessionMap::iterator session_map_iter;
566  SessionEndpointInfo session_endpoint_info = {};
567  SessionEndpointKey session_endpoint_key;
568  SessionEndpointMap::iterator session_endpoint_map_iter;
569  FlowEntry *fe_fwd = fe;
570  bool success;
571 
572  if (NULL == fe->reverse_flow_entry()) {
573  return;
574  }
575 
576  if (!(fe->is_flags_set(FlowEntry::LocalFlow))) {
578  fe_fwd = fe->reverse_flow_entry();
579  }
580  }
581 
582  success = GetSessionKey(fe_fwd, session_agg_key, session_key,
583  session_endpoint_key);
584  if (!success) {
585  return;
586  }
587 
588  /*
589  * If the flow is part of session endpoint DB then
590  * delete the existing one
591  * Flow add comes for the existing flow for the following cases
592  * - flow uuid changes (add-delete-add : will be compressed)
593  * - any key changes from session endpoint, aggregate or session
594  */
595  FlowSessionMap::iterator flow_session_map_iter;
596  flow_session_map_iter = flow_session_map_.find(fe_fwd);
597  if (flow_session_map_iter != flow_session_map_.end()) {
598 
599  FlowToSessionMap &flow_to_session_map = flow_session_map_iter->second;
600  FlowToSessionMap rhs_flow_to_session_map(session_key,
601  session_agg_key,
602  session_endpoint_key);
603  if (!(flow_to_session_map.IsEqual(rhs_flow_to_session_map))) {
604  DeleteSession(fe_fwd, flow_to_session_map.session_key().uuid,
605  GetCurrentTime(), NULL);
606  }
607  }
608 
609  TraceSession("Add", session_endpoint_key, session_agg_key, session_key,
610  false);
611  UpdateSessionStatsInfo(fe_fwd, setup_time, &session);
612 
613  session_endpoint_map_iter = session_endpoint_map_.find(
614  session_endpoint_key);
615  if (session_endpoint_map_iter == session_endpoint_map_.end()) {
616  session_agg_info.session_map_.insert(make_pair(session_key, session));
617  session_endpoint_info.session_agg_map_.insert(
618  make_pair(session_agg_key, session_agg_info));
619  session_endpoint_map_.insert(make_pair(session_endpoint_key,
620  session_endpoint_info));
621  AddFlowToSessionMap(fe_fwd, session_key, session_agg_key,
622  session_endpoint_key);
623  } else {
624  session_agg_map_iter = session_endpoint_map_iter->
625  second.session_agg_map_.find(
626  session_agg_key);
627  if (session_agg_map_iter ==
628  session_endpoint_map_iter->second.session_agg_map_.end()) {
629  session_agg_info.session_map_.insert(make_pair(session_key, session));
630  session_endpoint_map_iter->second.session_agg_map_.insert(
631  make_pair(session_agg_key, session_agg_info));
632  AddFlowToSessionMap(fe_fwd, session_key, session_agg_key,
633  session_endpoint_key);
634  } else {
635  session_map_iter =
636  session_agg_map_iter->second.session_map_.find(session_key);
637  if (session_map_iter ==
638  session_agg_map_iter->second.session_map_.end()) {
639  session_agg_map_iter->second.session_map_.insert(
640  make_pair(session_key, session));
641  AddFlowToSessionMap(fe_fwd, session_key, session_agg_key,
642  session_endpoint_key);
643  } else {
644  /*
645  * existing flow should match with the incoming add flow
646  */
647  assert(session.fwd_flow.uuid == fe_fwd->uuid());
648  }
649  }
650  }
651 }
652 
654  const boost::uuids::uuid &del_uuid,
655  uint64_t teardown_time,
656  const RevFlowDepParams *params) {
657  SessionAggKey session_agg_key;
658  SessionEndpointInfo::SessionAggMap::iterator session_agg_map_iter;
659  SessionPreAggInfo session_agg_info;
660  SessionKey session_key;
661  SessionPreAggInfo::SessionMap::iterator session_map_iter;
662  SessionEndpointInfo session_endpoint_info;
663  SessionEndpointKey session_endpoint_key;
664  SessionEndpointMap::iterator session_endpoint_map_iter;
665  bool read_flow = true;
666 
667  if (del_uuid != fe->uuid()) {
668  read_flow = false;
669  }
670 
671  /*
672  * If the given flow uuid is different from the existing one
673  * then ignore the read from flow
674  */
675  FlowSessionMap::iterator flow_session_map_iter;
676 
677  flow_session_map_iter = flow_session_map_.find(fe);
678  if (flow_session_map_iter != flow_session_map_.end()) {
679  if (del_uuid != flow_session_map_iter->second.session_key().uuid) {
680  /* We had never seen ADD for del_uuid, ignore delete request. This
681  * can happen when the following events occur
682  * 1. Add with UUID x
683  * 2. Delete with UUID x
684  * 3. Add with UUID y
685  * 4. Delete with UUID y
686  * When events 2 and 3 are suppressed and we receive only 1 and 4
687  * In this case initiated delete for entry with UUID x */
688  read_flow = false;
689  /* Reset params because they correspond to entry with UUID y */
690  params = NULL;
691  }
692  session_endpoint_key = flow_session_map_iter->second.session_endpoint_key();
693  session_agg_key = flow_session_map_iter->second.session_agg_key();
694  session_key = flow_session_map_iter->second.session_key();
695  } else {
696  return;
697  }
698  if (params && params->action_info_.action == 0) {
699  params = NULL;
700  }
701 
702  bool params_valid = true;
703  if (params == NULL) {
704  params_valid = false;
705  }
706 
707  TraceSession("Del", session_endpoint_key, session_agg_key, session_key,
708  params_valid);
709  session_endpoint_map_iter = session_endpoint_map_.find(
710  session_endpoint_key);
711  if (session_endpoint_map_iter != session_endpoint_map_.end()) {
712  session_agg_map_iter = session_endpoint_map_iter->
713  second.session_agg_map_.find(
714  session_agg_key);
715  if (session_agg_map_iter !=
716  session_endpoint_map_iter->second.session_agg_map_.end()) {
717  session_map_iter =
718  session_agg_map_iter->second.session_map_.find(session_key);
719  if (session_map_iter !=
720  session_agg_map_iter->second.session_map_.end()) {
721  /*
722  * Process the stats collector
723  */
724  session_map_iter->second.teardown_time = teardown_time;
725  session_map_iter->second.deleted = true;
726  /* Don't read stats for evicted flow, during delete */
727  if (!session_map_iter->second.evicted) {
728  SessionStatsChangedUnlocked(session_map_iter,
729  &session_map_iter->second.del_stats);
730  }
731  if (read_flow) {
732  CopyFlowInfo(session_map_iter->second, params);
733  }
734 
735  assert(session_map_iter->second.fwd_flow.flow.get() == fe);
737  session_map_iter->second.fwd_flow.flow = NULL;
738  session_map_iter->second.rev_flow.flow = NULL;
739  }
740  }
741  }
742 }
743 
745  uint32_t bytes,
746  uint32_t packets,
747  uint32_t oflow_bytes,
748  const boost::uuids::uuid &u) {
749  FlowSessionMap::iterator flow_session_map_iter;
750  SessionInfo session_info;
751  SessionIpPort session_key;
752  SessionAggInfo session_agg_info;
753  SessionIpPortProtocol session_agg_key;
754  SessionEndpointMap::iterator session_ep_map_iter;
755  SessionEndpointInfo::SessionAggMap::iterator session_agg_map_iter;
756  SessionPreAggInfo::SessionMap::iterator session_map_iter;
757 
758  /* TODO: Evicted msg coming for reverse flow. We currently don't have
759  * mapping from reverse_flow to flow_session_map */
760  flow_session_map_iter = flow_session_map_.find(flow.get());
761  if (flow_session_map_iter == flow_session_map_.end()) {
762  return;
763  }
764 
765  if (flow_session_map_iter->second.session_key().uuid != u) {
766  return;
767  }
768 
769  SessionEndpointKey session_db_ep_key = flow_session_map_iter->second.session_endpoint_key();
770  SessionAggKey session_db_agg_key = flow_session_map_iter->second.session_agg_key();
771  SessionKey session_db_key = flow_session_map_iter->second.session_key();
772 
773  session_ep_map_iter = session_endpoint_map_.find(session_db_ep_key);
774  if (session_ep_map_iter != session_endpoint_map_.end()) {
775  session_agg_map_iter = session_ep_map_iter->
776  second.session_agg_map_.find(
777  session_db_agg_key);
778  if (session_agg_map_iter !=
779  session_ep_map_iter->second.session_agg_map_.end()) {
780  session_map_iter =
781  session_agg_map_iter->second.session_map_.find(session_db_key);
782  if (session_map_iter !=
783  session_agg_map_iter->second.session_map_.end()) {
784  /*
785  * update the latest statistics
786  */
787  SessionFlowStatsInfo &session_flow = session_map_iter->second.fwd_flow;
788  uint64_t k_bytes, total_bytes, diff_bytes = 0;
789  uint64_t k_packets, total_packets, diff_packets = 0;
790  k_bytes = FlowStatsCollector::GetFlowStats((oflow_bytes & 0xFFFF),
791  bytes);
792  k_packets = FlowStatsCollector::GetFlowStats((oflow_bytes & 0xFFFF0000),
793  packets);
794  total_bytes = GetUpdatedSessionFlowBytes(session_flow.total_bytes,
795  k_bytes);
796  total_packets = GetUpdatedSessionFlowPackets(session_flow.total_packets,
797  k_packets);
798  diff_bytes = total_bytes - session_flow.total_bytes;
799  diff_packets = total_packets - session_flow.total_packets;
800  session_flow.total_bytes = total_bytes;
801  session_flow.total_packets = total_packets;
802 
803  SessionStatsParams &estats = session_map_iter->second.
804  evict_stats;
805  session_map_iter->second.evicted = true;
806  estats.fwd_flow.valid = true;
807  estats.fwd_flow.diff_bytes = diff_bytes;
808  estats.fwd_flow.diff_packets = diff_packets;
809  }
810  }
811  }
812 }
813 
815  SessionKey session_key,
816  SessionAggKey session_agg_key,
817  SessionEndpointKey session_endpoint_key) {
818  FlowToSessionMap flow_to_session_map(session_key, session_agg_key,
819  session_endpoint_key);
820  std::pair<FlowSessionMap::iterator, bool> ret =
821  flow_session_map_.insert(make_pair(fe, flow_to_session_map));
822  if (ret.second == false) {
823  FlowToSessionMap &prev = ret.first->second;
824  assert(prev.session_key().uuid == fe->uuid());
825  }
826 }
827 
829  FlowSessionMap::iterator flow_session_map_iter;
830  flow_session_map_iter = flow_session_map_.find(fe);
831  if (flow_session_map_iter != flow_session_map_.end()) {
832  flow_session_map_.erase(flow_session_map_iter);
833  }
834 }
835 
837  const {
838  /* If rate is not configured, it will have -1 as value
839  * -1 as value. In this case, pick the rate from SLO */
840  if (rate == -1) {
841  rate = slo->rate();
842  }
843  return rate;
844 }
845 
847  SessionSloState *state) {
848  vector<autogen::SecurityLoggingObjectRuleEntryType>::const_iterator it;
849  it = slo->rules().begin();
850  while (it != slo->rules().end()) {
851  state->UpdateSessionSloStateRuleEntry(it->rule_uuid, it->rate);
852  it++;
853  }
854 
855  SloRuleList::const_iterator acl_it = slo->firewall_policy_list().begin();
856  while (acl_it != slo->firewall_policy_list().end()) {
857  AclKey key(acl_it->uuid_);
858  AclDBEntry *acl = static_cast<AclDBEntry *>(agent_uve_->agent()->
859  acl_table()->FindActiveEntry(&key));
860  if (acl) {
861  int index = 0;
862  int rate = ComputeSloRate(acl_it->rate_, slo);
863  const AclEntry *ae = acl->GetAclEntryAtIndex(index);
864  while (ae != NULL) {
865  state->UpdateSessionSloStateRuleEntry(ae->uuid(), rate);
866  index++;
867  ae = acl->GetAclEntryAtIndex(index);
868  }
869  }
870  acl_it++;
871  }
872 
873  SloRuleList::const_iterator fw_rule_it;
874  fw_rule_it = slo->firewall_rule_list().begin();
875  while (fw_rule_it != slo->firewall_rule_list().end()) {
876  const SloRuleInfo &item = *fw_rule_it;
877  int rate = ComputeSloRate(item.rate_, slo);
878  state->UpdateSessionSloStateRuleEntry(to_string(item.uuid_), rate);
879  fw_rule_it++;
880  }
881 
882 }
883 
885  DBEntryBase *e) {
886  SecurityLoggingObject *slo = static_cast<SecurityLoggingObject *>(e);
887  SessionSloState *state =
888  static_cast<SessionSloState *>(slo->GetState(partition->parent(),
890  if (slo->IsDeleted()) {
891  if (!state)
892  return;
893  slo->ClearState(partition->parent(), slo_listener_id_);
894  delete state;
895  return;
896  }
897 
898  if (!state) {
899  state = new SessionSloState();
900  slo->SetState(slo->get_table(), slo_listener_id_, state);
901  }
902  UpdateSloStateRules(slo, state);
903 }
904 
906  int rate,
908  SessionSloRuleMap *slo_rule_map) {
909  SessionSloRuleEntry slo_rule_entry(rate, slo->uuid());
910  std::pair<SessionSloRuleMap::iterator, bool> ret;
911  ret = slo_rule_map->insert(make_pair(uuid,
912  slo_rule_entry));
913 }
914 
916  const std::vector<autogen::SecurityLoggingObjectRuleEntryType> &list,
918  SessionSloRuleMap *slo_rule_map) {
919  vector<autogen::SecurityLoggingObjectRuleEntryType>::const_iterator it;
920  it = list.begin();
921  while (it != list.end()) {
922  AddSessionSloRuleEntry(it->rule_uuid, it->rate, slo, slo_rule_map);
923  it++;
924  }
925 }
926 
928  SessionSloRuleMap *r_map) {
929  const SloRuleList &list = slo->firewall_policy_list();
930  SloRuleList::const_iterator acl_it = list.begin();
931  while (acl_it != list.end()) {
932  AclKey key(acl_it->uuid_);
933  AclDBEntry *acl = static_cast<AclDBEntry *>(agent_uve_->agent()->
934  acl_table()->FindActiveEntry(&key));
935  if (acl) {
936  int index = 0;
937  const AclEntry *ae = acl->GetAclEntryAtIndex(index);
938  int rate = ComputeSloRate(acl_it->rate_, slo);
939  while (ae != NULL) {
940  AddSessionSloRuleEntry(ae->uuid(), rate, slo, r_map);
941  index++;
942  ae = acl->GetAclEntryAtIndex(index);
943  }
944  }
945  acl_it++;
946  }
947 }
948 
950  SessionSloRuleMap *rule_map) {
951  const SloRuleList &list = slo->firewall_rule_list();
952  SloRuleList::const_iterator it = list.begin();
953  while (it != list.end()) {
954  int rate = ComputeSloRate(it->rate_, slo);
955  AddSessionSloRuleEntry(to_string(it->uuid_), rate, slo, rule_map);
956  it++;
957  }
958 }
959 
961  SessionSloRuleMap *slo_rule_map) {
962  AddSloRules(slo->rules(), slo, slo_rule_map);
963  AddSloFirewallPolicies(slo, slo_rule_map);
964  AddSloFirewallRules(slo, slo_rule_map);
965 }
966 
968  SessionSloRuleMap *slo_rule_map) {
970  SecurityLoggingObject *slo = static_cast<SecurityLoggingObject *>
971  (agent_uve_->agent()->slo_table()->FindActiveEntry(&slo_key));
972  if (slo) {
973  if (slo->status()) {
974  AddSloEntryRules(slo, slo_rule_map);
975  }
976  }
977 }
978 
980  SessionSloRuleMap *slo_rule_map) {
981  UuidList::const_iterator sit = slo_list.begin();
982  while (sit != slo_list.end()) {
983  AddSloEntry(*sit, slo_rule_map);
984  sit++;
985  }
986 }
987 
989  SessionSloRuleMap *vmi_session_slo_rule_map,
990  SessionSloRuleMap *vn_session_slo_rule_map) {
991  if (fe == NULL) {
992  return;
993  }
994  const Interface *itf = fe->intf_entry();
995  if (!itf) {
996  return;
997  }
998  if (itf->type() != Interface::VM_INTERFACE) {
999  return;
1000  }
1001  const VmInterface *vmi = static_cast<const VmInterface *>(itf);
1002  AddSloList(vmi->slo_list(), vmi_session_slo_rule_map);
1003  if (vmi->vn()) {
1004  AddSloList(vmi->vn()->slo_list(), vn_session_slo_rule_map);
1005  }
1006  return;
1007 }
1008 
1010  const SessionStatsInfo &stats_info,
1011  const FlowEntry *fe,
1012  SessionSloRuleMap *global_session_slo_rule_map,
1013  SessionSloRuleMap *vmi_session_slo_rule_map,
1014  SessionSloRuleMap *vn_session_slo_rule_map) {
1015 
1016  vmi_session_slo_rule_map->clear();
1017  vn_session_slo_rule_map->clear();
1018  global_session_slo_rule_map->clear();
1019 
1020  if (agent_uve_->agent()->oper_db()->global_vrouter()->slo_uuid() !=
1021  boost::uuids::nil_uuid()) {
1022  AddSloEntry(
1024  global_session_slo_rule_map);
1025  }
1026 
1027  if (stats_info.deleted) {
1028  AddSloList(stats_info.export_info.vmi_slo_list, vmi_session_slo_rule_map);
1029  AddSloList(stats_info.export_info.vn_slo_list, vn_session_slo_rule_map);
1030  } else {
1031  MakeSloList(fe, vmi_session_slo_rule_map, vn_session_slo_rule_map);
1032  }
1033 }
1034 
1036  const boost::uuids::uuid &slo_uuid,
1037  const std::string &match_uuid,
1038  bool *match) {
1039  SecurityLoggingObjectKey slo_key(slo_uuid);
1040  SecurityLoggingObject *slo = static_cast<SecurityLoggingObject *>
1041  (agent_uve_->agent()->slo_table()->FindActiveEntry(&slo_key));
1042  if (slo) {
1043  SessionSloState *state =
1044  static_cast<SessionSloState *>(slo->GetState(agent_uve_->agent()->slo_table(),
1045  slo_listener_id_));
1046  if (state) {
1047  return state->UpdateSessionSloStateRuleRefCount(match_uuid, match);
1048  }
1049  }
1050  *match = false;
1051  return false;
1052 }
1053 
1055  const std::string &policy_uuid,
1056  const bool &deleted_flag,
1057  bool *match,
1058  const bool &exported_once) {
1059  SessionSloRuleMap::const_iterator it;
1060  if (!policy_uuid.empty()) {
1061  it = map.find(policy_uuid);
1062  if (it != map.end()) {
1063  /* Always logging tear down session, which is exported atleast once
1064  * earlier will be logged other tear down sessions will be reported
1065  * with SLO rate checking
1066  */
1067  if (deleted_flag && exported_once) {
1068  *match = true;
1069  return true;
1070  }
1071  return UpdateSloMatchRuleEntry(it->second.slo_uuid, policy_uuid, match);
1072  }
1073  }
1074  *match = false;
1075  return false;
1076 }
1077 
1079  const std::string &fw_policy_uuid,
1080  const std::string &nw_policy_uuid,
1081  const std::string &sg_policy_uuid,
1082  const bool &deleted_flag,
1083  bool *match,
1084  const bool &exported_once) {
1085  SessionSloRuleMap::const_iterator it;
1086  bool fw_logged = false, nw_logged = false, sg_logged = false;
1087  bool fw_match = false, nw_match = false, sg_match = false;
1088 
1089  fw_logged = CheckPolicyMatch(map, fw_policy_uuid, deleted_flag,
1090  &fw_match, exported_once);
1091  nw_logged = CheckPolicyMatch(map, nw_policy_uuid, deleted_flag,
1092  &nw_match, exported_once);
1093  sg_logged = CheckPolicyMatch(map, sg_policy_uuid, deleted_flag,
1094  &sg_match, exported_once);
1095 
1096  if (fw_match || nw_match || sg_match) {
1097  *match = true;
1098  } else {
1099  *match = false;
1100  }
1101 
1102  if (fw_logged || nw_logged || sg_logged) {
1103  return true;
1104  }
1105  return false;
1106 }
1107 
1109  const SessionStatsInfo &stats_info,
1110  const FlowEntry *fe,
1111  const std::string &fw_policy_uuid,
1112  const std::string &nw_policy_uuid,
1113  const std::string &sg_policy_uuid,
1114  const bool &deleted_flag,
1115  bool *logged,
1116  const bool &exported_once) {
1117 
1118  bool is_vmi_slo_logged, is_vn_slo_logged, is_global_slo_logged;
1119  bool vmi_slo_match, vn_slo_match, global_slo_match;
1120  SessionSloRuleMap vmi_session_slo_rule_map;
1121  SessionSloRuleMap vn_session_slo_rule_map;
1122  SessionSloRuleMap global_session_slo_rule_map;
1123 
1124  /*
1125  * Get the list of slos need to be matched for the given flow
1126  */
1127  BuildSloList(stats_info, fe,
1128  &global_session_slo_rule_map,
1129  &vmi_session_slo_rule_map,
1130  &vn_session_slo_rule_map);
1131  /*
1132  * Match each type of policy for the given flow against the slo list
1133  */
1134 
1135  is_vmi_slo_logged = FindSloMatchRule(vmi_session_slo_rule_map,
1136  fw_policy_uuid,
1137  nw_policy_uuid,
1138  sg_policy_uuid,
1139  deleted_flag,
1140  &vmi_slo_match,
1141  exported_once);
1142 
1143  is_vn_slo_logged = FindSloMatchRule(vn_session_slo_rule_map,
1144  fw_policy_uuid,
1145  nw_policy_uuid,
1146  sg_policy_uuid,
1147  deleted_flag,
1148  &vn_slo_match,
1149  exported_once);
1150 
1151  is_global_slo_logged = FindSloMatchRule(global_session_slo_rule_map,
1152  fw_policy_uuid,
1153  nw_policy_uuid,
1154  sg_policy_uuid,
1155  deleted_flag,
1156  &global_slo_match,
1157  exported_once);
1158  if ((is_vmi_slo_logged) ||
1159  (is_vn_slo_logged) ||
1160  (is_global_slo_logged)) {
1161  *logged = true;
1162  }
1163  if (vmi_slo_match || vn_slo_match || global_slo_match) {
1164  return true;
1165  } else {
1166  return false;
1167  }
1168 }
1169 
1171  const SessionFlowExportInfo &flow_info,
1172  std::string &fw_policy_uuid,
1173  std::string &nw_policy_uuid,
1174  std::string &sg_policy_uuid) {
1175  fw_policy_uuid = flow_info.aps_rule_uuid;
1176  sg_policy_uuid = flow_info.sg_rule_uuid;
1177  nw_policy_uuid = flow_info.nw_ace_uuid;
1178  return;
1179 }
1180 
1182  const FlowEntry *fe,
1183  std::string &fw_policy_uuid,
1184  std::string &nw_policy_uuid,
1185  std::string &sg_policy_uuid) {
1186  fw_policy_uuid = fe->fw_policy_uuid();
1187  sg_policy_uuid = fe->sg_rule_uuid();
1188  nw_policy_uuid = fe->nw_ace_uuid();
1189  return;
1190 }
1191 
1193  const SessionStatsInfo &stats_info,
1194  const FlowEntry *fe,
1195  bool *logged,
1196  const bool &exported_once) {
1197 
1198  bool matched = false, deleted_flag=false;
1199  std::string fw_policy_uuid = "", nw_policy_uuid = "", sg_policy_uuid = "";
1200 
1202  fw_policy_uuid,
1203  nw_policy_uuid,
1204  sg_policy_uuid);
1205 
1206  matched = MatchSloForFlow(stats_info,
1207  fe,
1208  fw_policy_uuid,
1209  nw_policy_uuid,
1210  sg_policy_uuid,
1211  deleted_flag,
1212  logged,
1213  exported_once);
1214 
1215  return matched;
1216 }
1217 
1219  const SessionStatsInfo &stats_info,
1220  const SessionFlowExportInfo &flow_info,
1221  bool *logged,
1222  const bool &exported_once) {
1223 
1224  bool matched = false, deleted_flag = true;
1225  std::string fw_policy_uuid = "", nw_policy_uuid = "", sg_policy_uuid = "";
1226 
1227  GetPolicyIdFromDeletedFlow(flow_info,
1228  fw_policy_uuid,
1229  nw_policy_uuid,
1230  sg_policy_uuid);
1231 
1232  matched = MatchSloForFlow(stats_info,
1233  NULL,
1234  fw_policy_uuid,
1235  nw_policy_uuid,
1236  sg_policy_uuid,
1237  deleted_flag,
1238  logged,
1239  exported_once);
1240 
1241  return matched;
1242 }
1243 
1245  const SessionStatsInfo &stats_info) {
1246 
1247  bool logged = false;
1248  const SessionExportInfo &info = stats_info.export_info;
1249 
1250  /*
1251  * Deleted flow need to to be just checked whether SLO rules matched
1252  * If SLO is macthed, it should be logged irrespective of the rate
1253  */
1254  if (DeletedFlowLogging(stats_info,
1255  info.fwd_flow,
1256  &logged,
1257  stats_info.exported_atleast_once)) {
1258  CheckFlowLogging(logged);
1259  } else if (DeletedFlowLogging(stats_info,
1260  info.rev_flow,
1261  &logged,
1262  stats_info.exported_atleast_once)) {
1263  CheckFlowLogging(logged);
1264  }
1265  return false;
1266 }
1267 
1269  const SessionStatsInfo &stats_info) {
1270  bool logged = false;
1271 
1272  /*
1273  * FWD and REV flow of the Session need to be checked for SLO
1274  * separately. If FWD flow matches or logged then rev flow
1275  * is not required to check for SLO match.
1276  * REV flow will be checked for SLO only when FWD flow
1277  * is not matched for the SLO, since SLO is per session
1278  */
1279 
1280  if (FlowLogging(stats_info,
1281  stats_info.fwd_flow.flow.get(),
1282  &logged,
1283  stats_info.exported_atleast_once)) {
1284  CheckFlowLogging(logged);
1285  } else if (FlowLogging(stats_info,
1286  stats_info.rev_flow.flow.get(),
1287  &logged,
1288  stats_info.exported_atleast_once)) {
1289  CheckFlowLogging(logged);
1290  }
1291  return false;
1292 }
1293 
1295  const SessionStatsInfo &stats_info) {
1296 
1297  if (!agent_uve_->agent()->global_slo_status()) {
1298  /* SLO is not enabled */
1300  return false;
1301  }
1302 
1303  /*
1304  * Deleted flow will be logged if SLO is configured.
1305  * Normal case will be logged only when there is a change in the
1306  * stats. If there is no change in the session stats, it will
1307  * not be considered to SLO match and rate. This will avoid logging
1308  * of each session at least once. Also, idle session will not be
1309  * considered for the rate count
1310  */
1311 
1312  if (stats_info.deleted) {
1313  if(HandleDeletedFlowLogging(stats_info)) {
1314  return true;
1315  }
1316  } else if(HandleFlowLogging(stats_info)) {
1317  return true;
1318  }
1319 
1321  return false;
1322 }
1323 
1325  uint64_t k_flow_bytes) const {
1326  uint64_t oflow_bytes = 0xffff000000000000ULL & info_bytes;
1327  uint64_t old_bytes = 0x0000ffffffffffffULL & info_bytes;
1328  if (old_bytes > k_flow_bytes) {
1329  oflow_bytes += 0x0001000000000000ULL;
1330  }
1331  return (oflow_bytes |= k_flow_bytes);
1332 }
1333 
1335  uint64_t info_packets,
1336  uint64_t k_flow_pkts) const {
1337  uint64_t oflow_pkts = 0xffffff0000000000ULL & info_packets;
1338  uint64_t old_pkts = 0x000000ffffffffffULL & info_packets;
1339  if (old_pkts > k_flow_pkts) {
1340  oflow_pkts += 0x0000010000000000ULL;
1341  }
1342  return (oflow_pkts |= k_flow_pkts);
1343 }
1344 
1346  const boost::uuids::uuid &u,
1347  FlowEntry *fe) const {
1348  if (fe->uuid() != u) {
1349  return;
1350  }
1352  info->action);
1353  info->sg_rule_uuid = fe->sg_rule_uuid();
1354  info->nw_ace_uuid = fe->nw_ace_uuid();
1355  info->aps_rule_uuid = fe->fw_policy_uuid();
1358  }
1359 }
1360 
1362  const RevFlowDepParams *params) {
1363  SessionExportInfo &info = session.export_info;
1364  FlowEntry *fe = session.fwd_flow.flow.get();
1365  FlowEntry *rfe = session.rev_flow.flow.get();
1366  info.valid = true;
1367 
1368  const Interface *itf = fe->intf_entry();
1369  if ((itf != NULL) && (itf->type() == Interface::VM_INTERFACE)) {
1370  const VmInterface *vmi = static_cast<const VmInterface *>(itf);
1371  if (vmi != NULL) {
1372  info.vmi_slo_list = vmi->slo_list();
1373  if (vmi->vn()) {
1374  info.vn_slo_list = vmi->vn()->slo_list();
1375  }
1376  }
1377  }
1378 
1379  if (fe->IsIngressFlow()) {
1380  info.vm_cfg_name = fe->data().vm_cfg_name;
1381  } else if (rfe) {
1382  /* TODO: vm_cfg_name should be passed in RevFlowDepParams because rfe
1383  * may now point to different UUID altogether */
1384  info.vm_cfg_name = rfe->data().vm_cfg_name;
1385  }
1386  string rid = agent_uve_->agent()->router_id().to_string();
1388  info.other_vrouter = rid;
1389  } else {
1390  info.other_vrouter = fe->peer_vrouter();
1391  }
1392  info.underlay_proto = fe->tunnel_type().GetType();
1393  CopyFlowInfoInternal(&info.fwd_flow, session.fwd_flow.uuid, fe);
1394  if (params) {
1396  info.rev_flow.action);
1397  info.rev_flow.sg_rule_uuid = params->sg_uuid_;
1398  info.rev_flow.nw_ace_uuid = params->nw_ace_uuid_;
1399  if (FlowEntry::ShouldDrop(params->action_info_.action)) {
1401  drop_reason_);
1402  }
1403  } else if (rfe) {
1404  CopyFlowInfoInternal(&info.rev_flow, session.rev_flow.uuid, rfe);
1405  }
1406 }
1407 
1409 (const SessionFlowStatsParams &stats, SessionFlowInfo *flow_info,
1410  bool is_sampling, bool is_logging) const {
1411  if (!stats.valid) {
1412  return;
1413  }
1414  flow_info->set_tcp_flags(stats.tcp_flags);
1415  flow_info->set_underlay_source_port(stats.underlay_src_port);
1416  if (is_sampling) {
1417  flow_info->set_sampled_pkts(stats.diff_packets);
1418  flow_info->set_sampled_bytes(stats.diff_bytes);
1419  }
1420  if (is_logging) {
1421  flow_info->set_logged_pkts(stats.diff_packets);
1422  flow_info->set_logged_bytes(stats.diff_bytes);
1423  }
1424 }
1425 
1427 (const SessionFlowStatsInfo &session_flow, const SessionStatsInfo &sinfo,
1428  const SessionFlowExportInfo &einfo, SessionFlowInfo *flow_info) const {
1429  FlowEntry *fe = session_flow.flow.get();
1430  std::string action_str, drop_reason = "";
1431 
1432  flow_info->set_flow_uuid(session_flow.uuid);
1433  flow_info->set_setup_time(sinfo.setup_time);
1434  if (sinfo.teardown_time) {
1435  flow_info->set_teardown_time(sinfo.teardown_time);
1436  flow_info->set_teardown_bytes(session_flow.total_bytes);
1437  flow_info->set_teardown_pkts(session_flow.total_packets);
1438  }
1439  if (sinfo.deleted) {
1440  if (!sinfo.export_info.valid) {
1441  return;
1442  }
1443  if (!einfo.action.empty()) {
1444  flow_info->set_action(einfo.action);
1445  }
1446  if (!einfo.sg_rule_uuid.empty()) {
1447  flow_info->set_sg_rule_uuid(StringToUuid(einfo.sg_rule_uuid));
1448  }
1449  if (!einfo.nw_ace_uuid.empty()) {
1450  flow_info->set_nw_ace_uuid(StringToUuid(einfo.nw_ace_uuid));
1451  }
1452  if (!einfo.drop_reason.empty()) {
1453  flow_info->set_drop_reason(einfo.drop_reason);
1454  }
1455  } else {
1457  action_str);
1458  flow_info->set_action(action_str);
1459  flow_info->set_sg_rule_uuid(StringToUuid(fe->sg_rule_uuid()));
1460  flow_info->set_nw_ace_uuid(StringToUuid(fe->nw_ace_uuid()));
1462  drop_reason = FlowEntry::DropReasonStr(fe->data().drop_reason);
1463  flow_info->set_drop_reason(drop_reason);
1464  }
1465  }
1466 }
1467 
1469  SessionPreAggInfo::SessionMap::iterator session_map_iter) {
1470  FlowEntry *fe = session_map_iter->second.fwd_flow.flow.get();
1471  FlowEntry *rfe = session_map_iter->second.rev_flow.flow.get();
1473  if (fe->deleted()) {
1474  DeleteSession(fe, session_map_iter->first.uuid,
1475  GetCurrentTime(), NULL);
1476  return true;
1477  }
1478  return false;
1479 }
1480 
1482  (SessionPreAggInfo::SessionMap::iterator session_map_iter,
1483  SessionStatsParams *params) const {
1484  FlowEntry *fe = session_map_iter->second.fwd_flow.flow.get();
1485  FlowEntry *rfe = session_map_iter->second.rev_flow.flow.get();
1487  return SessionStatsChangedUnlocked(session_map_iter, params);
1488 }
1489 
1491  (SessionPreAggInfo::SessionMap::iterator session_map_iter,
1492  SessionStatsParams *params) const {
1493 
1494  bool fwd_updated = FetchFlowStats(&session_map_iter->second.fwd_flow,
1495  &params->fwd_flow);
1496  bool rev_updated = FetchFlowStats(&session_map_iter->second.rev_flow,
1497  &params->rev_flow);
1498  return (fwd_updated || rev_updated);
1499 }
1500 
1502 (SessionFlowStatsInfo *info, SessionFlowStatsParams *params) const {
1503  vr_flow_stats k_stats;
1504  KFlowData kinfo;
1505  uint64_t k_bytes, bytes, k_packets;
1506  const vr_flow_entry *k_flow = NULL;
1507  KSyncFlowMemory *ksync_obj = agent_uve_->agent()->ksync()->
1508  ksync_flow_memory();
1509  /* Update gen-id and flow-handle before reading stats using them. For
1510  * reverse-flow, it is possible that flow-handle is not set yet
1511  */
1512  FlowEntry *fe = info->flow.get();
1513  if (fe && (info->uuid == fe->uuid())) {
1514  info->flow_handle = fe->flow_handle();
1515  info->gen_id = fe->gen_id();
1516  }
1517 
1518  k_flow = ksync_obj->GetKFlowStatsAndInfo(info->flow->key(),
1519  info->flow_handle,
1520  info->gen_id, &k_stats, &kinfo);
1521  if (!k_flow) {
1522  SandeshFlowKey skey;
1523  skey.set_nh(info->flow->key().nh);
1524  skey.set_sip(info->flow->key().src_addr.to_string());
1525  skey.set_dip(info->flow->key().dst_addr.to_string());
1526  skey.set_src_port(info->flow->key().src_port);
1527  skey.set_dst_port(info->flow->key().dst_port);
1528  skey.set_protocol(info->flow->key().protocol);
1529  SESSION_STATS_TRACE(Err, "Fetching stats failed", info->flow_handle,
1530  info->gen_id, skey);
1531  return false;
1532  }
1533 
1534  k_bytes = FlowStatsCollector::GetFlowStats(k_stats.flow_bytes_oflow,
1535  k_stats.flow_bytes);
1536  k_packets = FlowStatsCollector::GetFlowStats(k_stats.flow_packets_oflow,
1537  k_stats.flow_packets);
1538 
1539  bytes = 0x0000ffffffffffffULL & info->total_bytes;
1540 
1541  if (bytes != k_bytes) {
1542  uint64_t total_bytes = GetUpdatedSessionFlowBytes(info->total_bytes,
1543  k_bytes);
1544  uint64_t total_packets = GetUpdatedSessionFlowPackets
1545  (info->total_packets, k_packets);
1546  params->diff_bytes = total_bytes - info->total_bytes;
1547  params->diff_packets = total_packets - info->total_packets;
1548  info->total_bytes = total_bytes;
1549  info->total_packets = total_packets;
1550  params->tcp_flags = kinfo.tcp_flags;
1551  params->underlay_src_port = kinfo.underlay_src_port;
1552  params->valid = true;
1553  return true;
1554  }
1555  return false;
1556 }
1557 
1559  (SessionPreAggInfo::SessionMap::iterator session_map_iter,
1560  const SessionStatsParams &stats, SessionInfo *session_info,
1561  SessionIpPort *session_key, bool is_sampling, bool is_logging) const {
1562  FlowEntry *fe = session_map_iter->second.fwd_flow.flow.get();
1563  FlowEntry *rfe = session_map_iter->second.rev_flow.flow.get();
1565  FillSessionInfoUnlocked(session_map_iter, stats, session_info, session_key, NULL,
1566  true, is_sampling, is_logging);
1567 }
1568 
1570  (SessionPreAggInfo::SessionMap::iterator session_map_iter,
1571  SessionInfo *session_info, bool is_sampling, bool is_logging) const {
1572  const SessionStatsParams &estats = session_map_iter->second.evict_stats;
1573  if (!estats.fwd_flow.valid) {
1574  return;
1575  }
1576  if (is_logging) {
1577  session_info->forward_flow_info.set_logged_pkts(estats.fwd_flow.
1578  diff_packets);
1579  session_info->forward_flow_info.set_logged_bytes(estats.fwd_flow.
1580  diff_bytes);
1581  /* TODO: Evict stats for reverse flow is not supported yet */
1582  session_info->reverse_flow_info.set_logged_pkts(0);
1583  session_info->reverse_flow_info.set_logged_bytes(0);
1584  }
1585  if (is_sampling) {
1586  session_info->forward_flow_info.set_sampled_pkts(estats.fwd_flow.
1587  diff_packets);
1588  session_info->forward_flow_info.set_sampled_bytes(estats.fwd_flow.
1589  diff_bytes);
1590  /* TODO: Evict stats for reverse flow is not supported yet */
1591  session_info->reverse_flow_info.set_sampled_pkts(0);
1592  session_info->reverse_flow_info.set_sampled_bytes(0);
1593  }
1594 }
1595 
1597  (SessionPreAggInfo::SessionMap::iterator session_map_iter,
1598  const SessionStatsParams &stats,
1599  SessionInfo *session_info,
1600  SessionIpPort *session_key,
1601  const RevFlowDepParams *params,
1602  bool read_flow, bool is_sampling, bool is_logging) const {
1603  string rid = agent_uve_->agent()->router_id().to_string();
1604  FlowEntry *fe = session_map_iter->second.fwd_flow.flow.get();
1605  FlowEntry *rfe = session_map_iter->second.rev_flow.flow.get();
1606  boost::system::error_code ec;
1607  /*
1608  * Fill the session Key
1609  */
1610  session_key->set_ip(session_map_iter->first.remote_ip);
1611  session_key->set_port(session_map_iter->first.client_port);
1612  FillSessionFlowInfo(session_map_iter->second.fwd_flow,
1613  session_map_iter->second,
1614  session_map_iter->second.export_info.fwd_flow,
1615  &session_info->forward_flow_info);
1616  FillSessionFlowInfo(session_map_iter->second.rev_flow,
1617  session_map_iter->second,
1618  session_map_iter->second.export_info.rev_flow,
1619  &session_info->reverse_flow_info);
1620  bool first_time_export = false;
1621  if (!session_map_iter->second.exported_atleast_once) {
1622  first_time_export = true;
1623  /* Mark the flow as exported */
1624  session_map_iter->second.exported_atleast_once = true;
1625  }
1626 
1627  const bool &evicted = session_map_iter->second.evicted;
1628  const bool &deleted = session_map_iter->second.deleted;
1629  if (evicted) {
1630  const SessionStatsParams &estats = session_map_iter->second.evict_stats;
1631  FillSessionEvictStats(session_map_iter, session_info, is_sampling,
1632  is_logging);
1633  flow_stats_manager_->UpdateSessionExportStats(1, first_time_export,
1634  estats.sampled);
1635  } else {
1636  const SessionStatsParams *real_stats = &stats;
1637  if (deleted) {
1638  real_stats = &session_map_iter->second.del_stats;
1639  }
1640  FillSessionFlowStats(real_stats->fwd_flow,
1641  &session_info->forward_flow_info, is_sampling,
1642  is_logging);
1643  FillSessionFlowStats(real_stats->rev_flow,
1644  &session_info->reverse_flow_info, is_sampling,
1645  is_logging);
1646  flow_stats_manager_->UpdateSessionExportStats(1, first_time_export,
1647  real_stats->sampled);
1648  }
1649  if (deleted) {
1650  SessionExportInfo &info = session_map_iter->second.export_info;
1651  if (info.valid) {
1652  if (!info.vm_cfg_name.empty()) {
1653  session_info->set_vm(info.vm_cfg_name);
1654  }
1655  session_info->set_other_vrouter_ip(
1656  AddressFromString(info.other_vrouter, &ec));
1657  session_info->set_underlay_proto(info.underlay_proto);
1658  }
1659  } else {
1660  session_info->set_vm(fe->data().vm_cfg_name);
1662  session_info->set_other_vrouter_ip(AddressFromString(rid, &ec));
1663  } else {
1664  /* For Egress flows, pick VM name from reverse flow */
1665  if (!fe->IsIngressFlow() && rfe) {
1666  session_info->set_vm(rfe->data().vm_cfg_name);
1667  }
1668  session_info->set_other_vrouter_ip(
1669  AddressFromString(fe->peer_vrouter(), &ec));
1670  }
1671  session_info->set_underlay_proto(fe->tunnel_type().GetType());
1672  }
1673 }
1674 
1675 void SessionStatsCollector::UpdateAggregateStats(const SessionInfo &sinfo,
1676  SessionAggInfo *agg_info,
1677  bool is_sampling,
1678  bool is_logging) const {
1679  if (is_sampling) {
1680  agg_info->set_sampled_forward_bytes(agg_info->get_sampled_forward_bytes() +
1681  sinfo.get_forward_flow_info().get_sampled_bytes());
1682  agg_info->set_sampled_forward_pkts(agg_info->get_sampled_forward_pkts() +
1683  sinfo.get_forward_flow_info().get_sampled_pkts());
1684  agg_info->set_sampled_reverse_bytes(agg_info->get_sampled_reverse_bytes() +
1685  sinfo.get_reverse_flow_info().get_sampled_bytes());
1686  agg_info->set_sampled_reverse_pkts(agg_info->get_sampled_reverse_pkts() +
1687  sinfo.get_reverse_flow_info().get_sampled_pkts());
1688  }
1689  if (is_logging) {
1690  agg_info->set_logged_forward_bytes(agg_info->get_logged_forward_bytes() +
1691  sinfo.get_forward_flow_info().get_logged_bytes());
1692  agg_info->set_logged_forward_pkts(agg_info->get_logged_forward_pkts() +
1693  sinfo.get_forward_flow_info().get_logged_pkts());
1694  agg_info->set_logged_reverse_bytes(agg_info->get_logged_reverse_bytes() +
1695  sinfo.get_reverse_flow_info().get_logged_bytes());
1696  agg_info->set_logged_reverse_pkts(agg_info->get_logged_reverse_pkts() +
1697  sinfo.get_reverse_flow_info().get_logged_pkts());
1698  }
1699 }
1700 
1702 (SessionEndpointInfo::SessionAggMap::iterator it, SessionIpPortProtocol *key)
1703  const {
1704  /*
1705  * Fill the session agg key
1706  */
1707  key->set_local_ip(it->first.local_ip);
1708  key->set_service_port(it->first.server_port);
1709  key->set_protocol(it->first.proto);
1710 }
1711 
1713  SessionEndpoint *ep) const {
1714  UveTagData tinfo(UveTagData::SET);
1715  agent_uve_->BuildTagNamesFromList(list, &tinfo);
1716  if (!tinfo.application.empty()) {
1717  ep->set_application(tinfo.application);
1718  }
1719  if (!tinfo.tier.empty()) {
1720  ep->set_tier(tinfo.tier);
1721  }
1722  if (!tinfo.site.empty()) {
1723  ep->set_site(tinfo.site);
1724  }
1725  if (!tinfo.deployment.empty()) {
1726  ep->set_deployment(tinfo.deployment);
1727  }
1728  if (tinfo.label_set.size() != 0) {
1729  ep->set_labels(tinfo.label_set);
1730  }
1731  if (tinfo.custom_tag_set.size() != 0) {
1732  ep->set_custom_tags(tinfo.custom_tag_set);
1733  }
1734 }
1735 
1737  SessionEndpoint *ep) const {
1738  UveTagData tinfo(UveTagData::SET);
1739  agent_uve_->BuildTagIdsFromList(list, &tinfo);
1740  if (!tinfo.application.empty()){
1741  ep->set_remote_application(tinfo.application);
1742  }
1743  if (!tinfo.tier.empty()){
1744  ep->set_remote_tier(tinfo.tier);
1745  }
1746  if (!tinfo.site.empty()){
1747  ep->set_remote_site(tinfo.site);
1748  }
1749  if (!tinfo.deployment.empty()){
1750  ep->set_remote_deployment(tinfo.deployment);
1751  }
1752  if (tinfo.label_set.size() != 0) {
1753  ep->set_remote_labels(tinfo.label_set);
1754  }
1755  if (tinfo.custom_tag_set.size() != 0) {
1756  ep->set_remote_custom_tags(tinfo.custom_tag_set);
1757  }
1758 }
1759 
1760 void SessionStatsCollector::FillSessionEndpoint(SessionEndpointMap::iterator it,
1761  SessionEndpoint *session_ep)
1762  const {
1763  string rid = agent_uve_->agent()->router_id().to_string();
1764  boost::system::error_code ec;
1765 
1766  session_ep->set_vmi(it->first.vmi_cfg_name);
1767  session_ep->set_vn(it->first.local_vn);
1768  session_ep->set_remote_vn(it->first.remote_vn);
1769  session_ep->set_is_client_session(it->first.is_client_session);
1770  session_ep->set_is_si(it->first.is_si);
1771  if (!it->first.remote_prefix.empty()) {
1772  session_ep->set_remote_prefix(it->first.remote_prefix);
1773  }
1774  session_ep->set_security_policy_rule(it->first.match_policy);
1775  if (it->first.local_tagset.size() > 0) {
1776  FillSessionTags(it->first.local_tagset, session_ep);
1777  }
1778  if (it->first.remote_tagset.size() > 0) {
1779  FillSessionRemoteTags(it->first.remote_tagset, session_ep);
1780  }
1781  session_ep->set_vrouter_ip(AddressFromString(rid, &ec));
1782 }
1783 
1785  (const SessionEndpointMap::iterator &it) {
1786  SessionEndpointInfo::SessionAggMap::iterator session_agg_map_iter;
1787  SessionEndpointInfo::SessionAggMap::iterator prev_agg_iter;
1788  SessionPreAggInfo::SessionMap::iterator session_map_iter, prev;
1789 
1790  SessionInfo session_info;
1791  SessionIpPort session_key;
1792  uint32_t session_count = 0, session_agg_count = 0;
1793  bool exit = false, ep_completed = true;
1794 
1795  SessionEndpoint &session_ep = session_msg_list_[GetSessionMsgIdx()];
1796 
1797  session_agg_map_iter = it->second.session_agg_map_.
1798  lower_bound(session_agg_iteration_key_);
1799  while (session_agg_map_iter != it->second.session_agg_map_.end()) {
1800  SessionAggInfo session_agg_info;
1801  SessionIpPortProtocol session_agg_key;
1802  session_count = 0;
1803  session_map_iter = session_agg_map_iter->second.session_map_.
1804  lower_bound(session_iteration_key_);
1805  while (session_map_iter != session_agg_map_iter->second.session_map_.end()) {
1806  prev = session_map_iter;
1807  SessionStatsParams params;
1808  if (!session_map_iter->second.deleted &&
1809  !session_map_iter->second.evicted) {
1810  bool delete_marked = CheckAndDeleteSessionStatsFlow(session_map_iter);
1811  if (!delete_marked) {
1812  bool changed = SessionStatsChangedLocked(session_map_iter,
1813  &params);
1814  if (!changed && session_map_iter->second.exported_atleast_once) {
1815  ++session_map_iter;
1816  continue;
1817  }
1818  }
1819  }
1820 
1821  bool is_sampling = true;
1822  if (IsSamplingEnabled()) {
1823  is_sampling = SampleSession(session_map_iter, &params);
1824  }
1825  bool is_logging = CheckSessionLogging(session_map_iter->second);
1826 
1827  /* Ignore session export if sampling & logging drop the session */
1828  if (!is_sampling && !is_logging) {
1829  ++session_map_iter;
1830  if (prev->second.deleted) {
1831  session_agg_map_iter->second.session_map_.erase(prev);
1832  }
1833  continue;
1834  }
1835  if (session_map_iter->second.deleted) {
1836  FillSessionInfoUnlocked(session_map_iter, params, &session_info,
1837  &session_key, NULL, true, is_sampling,
1838  is_logging);
1839  } else {
1840  FillSessionInfoLocked(session_map_iter, params, &session_info,
1841  &session_key, is_sampling, is_logging);
1842  }
1843  session_agg_info.sessionMap.insert(make_pair(session_key,
1844  session_info));
1845  UpdateAggregateStats(session_info, &session_agg_info, is_sampling,
1846  is_logging);
1847  ++session_map_iter;
1848  ++session_count;
1849  if (prev->second.deleted) {
1850  session_agg_map_iter->second.session_map_.erase(prev);
1851  }
1852  if (session_count ==
1854  exit = true;
1855  break;
1856  }
1857  }
1858  if (session_count) {
1859  FillSessionAggInfo(session_agg_map_iter, &session_agg_key);
1860  session_ep.sess_agg_info.insert(make_pair(session_agg_key,
1861  session_agg_info));
1862  }
1863  if (exit) {
1864  break;
1865  }
1867  prev_agg_iter = session_agg_map_iter;
1868  session_agg_map_iter++;
1869  if (prev_agg_iter->second.session_map_.size() == 0) {
1870  it->second.session_agg_map_.erase(prev_agg_iter);
1871  }
1872  ++session_agg_count;
1873  if (session_agg_count ==
1875  break;
1876  }
1877  }
1878  /* Don't export SessionEndpoint if there are 0 aggregates */
1879  if (session_ep.sess_agg_info.size()) {
1880  FillSessionEndpoint(it, &session_ep);
1882  }
1883 
1884  if (session_count ==
1886  ep_completed = false;
1887  session_ep_iteration_key_ = it->first;
1888  session_agg_iteration_key_ = session_agg_map_iter->first;
1889  if (session_map_iter == session_agg_map_iter->second.session_map_.end()) {
1890  prev_agg_iter = session_agg_map_iter;
1891  ++session_agg_map_iter;
1892  if (prev_agg_iter->second.session_map_.size() == 0) {
1893  it->second.session_agg_map_.erase(prev_agg_iter);
1894  }
1895  if (session_agg_map_iter == it->second.session_agg_map_.end()) {
1896  /* session_iteration_key_ and session_agg_iteration_key_ are
1897  * both reset when ep_completed is returned as true in the
1898  * calling function */
1899  ep_completed = true;
1900  } else {
1902  session_agg_iteration_key_ = session_agg_map_iter->first;
1903  }
1904  } else {
1905  session_iteration_key_ = session_map_iter->first;
1906  }
1907  } else if (session_agg_count ==
1908  agent_uve_->agent()->params()->
1909  max_aggregates_per_session_endpoint()) {
1910  ep_completed = false;
1911  session_ep_iteration_key_ = it->first;
1912  if (session_agg_map_iter == it->second.session_agg_map_.end()) {
1913  /* session_iteration_key_ and session_agg_iteration_key_ are both
1914  * reset when ep_completed is returned as true in the calling
1915  * function */
1916  ep_completed = true;
1917  } else {
1918  session_agg_iteration_key_ = session_agg_map_iter->first;
1920  }
1921  }
1922  return ep_completed;
1923 }
1924 
1926  SessionEndpointMap::iterator it = session_endpoint_map_.
1927  lower_bound(session_ep_iteration_key_);
1928  if (it == session_endpoint_map_.end()) {
1929  it = session_endpoint_map_.begin();
1930  }
1931  if (it == session_endpoint_map_.end()) {
1932  return 0;
1933  }
1934 
1935  uint32_t count = 0;
1936  while (count < max_count) {
1937  if (it == session_endpoint_map_.end()) {
1938  break;
1939  }
1940 
1941  /* ProcessSessionEndpoint will build 1 SessionEndpoint message. This
1942  * may or may not include all aggregates and all sessions within each
1943  * aggregate. It returns true if the built message includes all
1944  * aggregates and all sessions of each aggregate */
1945  bool ep_completed = ProcessSessionEndpoint(it);
1946  ++count;
1947  if (ep_completed) {
1948  SessionEndpointMap::iterator prev = it;
1949  ++it;
1953  if (prev->second.session_agg_map_.size() == 0) {
1954  session_endpoint_map_.erase(prev);
1955  }
1956  }
1957  }
1958 
1959  //Send any pending session export messages
1961 
1962  // Update iterator for next pass
1963  if (it == session_endpoint_map_.end()) {
1965  } else {
1966  session_ep_iteration_key_ = it->first;
1967  }
1968 
1969  session_task_ = NULL;
1970  return count;
1971 }
1973 // Introspect routines
1975 //TBD
1976 
1978 // Session Stats task
1981  Task(ssc->task_id(), ssc->instance_id()), ssc_(ssc) {
1982 }
1983 
1985 }
1986 
1988  return "Session Stats Collector Task";
1989 }
1990 
1992  ssc_->RunSessionEndpointStats(kSessionsPerTask);
1993  return true;
1994 }
1995 
1997  int32_t cfg_rate = agent_uve_->agent()->oper_db()->global_vrouter()->
1998  flow_export_rate();
1999  if (cfg_rate == GlobalVrouter::kDisableSampling) {
2000  return false;
2001  }
2002  return true;
2003 }
2004 
2006  (SessionPreAggInfo::SessionMap::iterator session_map_iter,
2007  SessionStatsParams *params) const {
2008  int32_t cfg_rate = agent_uve_->agent()->oper_db()->global_vrouter()->
2009  flow_export_rate();
2010  /* If session export is disabled, update stats and return */
2011  if (!cfg_rate) {
2013  return false;
2014  }
2015  const bool &deleted = session_map_iter->second.deleted;
2016  const bool &evicted = session_map_iter->second.evicted;
2017  SessionStatsParams *stats = params;
2018  if (evicted) {
2019  stats = &session_map_iter->second.evict_stats;
2020  } else if (deleted) {
2021  stats = &session_map_iter->second.del_stats;
2022  }
2023  stats->sampled = false;
2024  /* For session-sampling diff_bytes should consider the diff bytes for both
2025  * forward and reverse flow */
2026  uint64_t diff_bytes = stats->fwd_flow.diff_bytes +
2027  stats->rev_flow.diff_bytes;
2028  const SessionStatsInfo &info = session_map_iter->second;
2029  /* Subject a flow to sampling algorithm only when all of below is met:-
2030  * a. actual session-export-rate is >= 80% of configured flow-export-rate.
2031  * This is done only for first time.
2032  * b. diff_bytes is lesser than the threshold
2033  * c. Flow-sample does not have teardown time or the sample for the flow is
2034  * not exported earlier.
2035  */
2036  bool subject_flows_to_algorithm = false;
2037  if ((diff_bytes < threshold()) &&
2038  (!info.teardown_time || !info.exported_atleast_once) &&
2040  flow_stats_manager_->session_export_rate() >= ((double)cfg_rate) * 0.8)
2042  subject_flows_to_algorithm = true;
2044  }
2045 
2046  if (subject_flows_to_algorithm) {
2047  double probability = diff_bytes/threshold();
2048  uint32_t num = rand() % threshold();
2049  if (num > diff_bytes) {
2050  /* Do not export the flow, if the random number generated is more
2051  * than the diff_bytes */
2053  /* The second part of the if condition below is not required but
2054  * added for better readability. It is not required because
2055  * exported_atleast_once() will always be false if teardown time is
2056  * set. If both teardown_time and exported_atleast_once are true we
2057  * will never be here */
2058  if (info.teardown_time && !info.exported_atleast_once) {
2059  /* This counter indicates the number of sessions that were
2060  * never exported */
2062  }
2063  return false;
2064  }
2065  stats->sampled = true;
2066  /* Normalize the diff_bytes and diff_packets reported using the
2067  * probability value */
2068  if (probability == 0) {
2069  stats->fwd_flow.diff_bytes = 0;
2070  stats->fwd_flow.diff_packets = 0;
2071  stats->rev_flow.diff_bytes = 0;
2072  stats->rev_flow.diff_packets = 0;
2073  } else {
2074  stats->fwd_flow.diff_bytes = stats->fwd_flow.diff_bytes/
2075  probability;
2076  stats->fwd_flow.diff_packets = stats->fwd_flow.diff_packets/
2077  probability;
2078  stats->rev_flow.diff_bytes = stats->rev_flow.diff_bytes/
2079  probability;
2080  stats->rev_flow.diff_packets = stats->rev_flow.diff_packets/
2081  probability;
2082  }
2083  }
2084 
2085  return true;
2086 }
2087 
2089  return flow_stats_manager_->threshold();
2090 }
2091 
2093 // SessionStatsCollectorObject methods
2096  FlowStatsManager *mgr) {
2097  for (int i = 0; i < kMaxSessionCollectors; i++) {
2098  uint32_t instance_id = mgr->AllocateIndex();
2099  boost::asio::io_context& io_ref =
2100  const_cast<boost::asio::io_context&>
2101  (*agent->event_manager()->io_service());
2102  collectors[i].reset(
2103  AgentStaticObjectFactory::CreateRef<SessionStatsCollector>(
2104  io_ref,
2105  agent->uve(), instance_id, mgr, this));
2106  }
2107 }
2108 
2110  if (idx >= 0 && idx < kMaxSessionCollectors) {
2111  return collectors[idx].get();
2112  }
2113  return NULL;
2114 }
2115 
2117  for (int i = 0; i < kMaxSessionCollectors; i++) {
2118  collectors[i]->set_expiry_time(time);
2119  }
2120 }
2121 
2123  /* Same expiry time would be configured for all the collectors. Pick value
2124  * from any one of them */
2125  return collectors[0]->expiry_time();
2126 }
2127 
2129  (const FlowEntry *flow) {
2130  uint8_t idx = 0;
2131  FlowTable *table = flow->flow_table();
2132  if (table) {
2133  idx = table->table_index() % kMaxSessionCollectors;
2134  }
2135  return collectors[idx].get();
2136 }
2137 
2139  for (int i = 0; i < kMaxSessionCollectors; i++) {
2140  collectors[i]->Shutdown();
2141  collectors[i].reset();
2142  }
2143 }
2144 
2146  size_t size = 0;
2147  for (int i = 0; i < kMaxSessionCollectors; i++) {
2148  size += collectors[i]->Size();
2149  }
2150  return size;
2151 }
2152 
2154  for (int i = 0; i < kMaxSessionCollectors; i++) {
2155  if (collectors[i].get()) {
2156  collectors[i].get()->RegisterDBClients();
2157  }
2158  }
2159 }
2160 
2162  FlowEntry *rflow = NULL;
2163  if (flow_.get()) {
2164  rflow = flow_->reverse_flow_entry();
2165  }
2166  return rflow;
2167 }
2168 
2170  if (!(session_key_.IsEqual(rhs.session_key()))) {
2171  return false;
2172  }
2173  if (!(session_agg_key_.IsEqual(rhs.session_agg_key()))) {
2174  return false;
2175  }
2176  if (!(session_endpoint_key_.IsEqual(rhs.session_endpoint_key()))) {
2177  return false;
2178  }
2179  return true;
2180 }
2181 
2183  SessionSloRuleStateMap::iterator it;
2184  it = session_rule_state_map_.find(uuid);
2185  if (it != session_rule_state_map_.end()) {
2186  session_rule_state_map_.erase(it);
2187  }
2188 }
2189 
2191  int rate) {
2192  SessionSloRuleStateMap::iterator it;
2193  it = session_rule_state_map_.find(uuid);
2194  if (it == session_rule_state_map_.end()) {
2195  SessionSloRuleState slo_state_rule_entry = {};
2196  slo_state_rule_entry.rate = rate;
2197  session_rule_state_map_.insert(make_pair(uuid, slo_state_rule_entry));
2198  } else {
2199  SessionSloRuleState &prev = it->second;
2200  if (prev.rate != rate) {
2201  prev.rate = rate;
2202  prev.ref_count = 0;
2203  }
2204  }
2205 
2206 }
2207 
2209  const std::string &uuid,
2210  bool *match) {
2211  SessionSloRuleStateMap::iterator it;
2212  bool is_logged = false;
2213  it = session_rule_state_map_.find(uuid);
2214  if (it != session_rule_state_map_.end()) {
2215  *match = true;
2216  if (it->second.ref_count == 0) {
2217  is_logged = true;
2218  }
2219  it->second.ref_count++;
2220  if (it->second.ref_count == it->second.rate) {
2221  it->second.ref_count = 0;
2222  }
2223  }
2224  return is_logged;
2225 }
boost::asio::ip::address IpAddress
Definition: address.h:14
IpAddress AddressFromString(const std::string &ip_address_str, boost::system::error_code *ec)
std::vector< boost::uuids::uuid > UuidList
Definition: agent.h:204
std::vector< uint64_t > TagList
Definition: agent.h:203
#define kTaskSessionStatsCollector
Definition: agent.h:332
#define kTaskSessionStatsCollectorEvent
Definition: agent.h:333
Definition: acl.h:92
const AclEntry * GetAclEntryAtIndex(uint32_t) const
Definition: acl.cc:889
const std::string & uuid() const
Definition: acl_entry.h:122
AgentDBEntry * FindActiveEntry(const DBEntry *key)
Definition: agent_db.cc:111
uint16_t max_sessions_per_aggregate() const
Definition: agent_param.h:440
uint16_t max_endpoints_per_session_msg() const
Definition: agent_param.h:446
uint16_t max_aggregates_per_session_endpoint() const
Definition: agent_param.h:443
void BuildTagIdsFromList(const TagList &tl, UveTagData *info) const
Agent * agent() const
void BuildTagNamesFromList(const TagList &tl, UveTagData *info) const
Definition: agent.h:361
bool MeasureQueueDelay()
Definition: agent.cc:1149
OperDB * oper_db() const
Definition: agent.cc:1017
AgentParam * params() const
Definition: agent.h:1227
AgentUveBase * uve() const
Definition: agent.cc:913
EventManager * event_manager() const
Definition: agent.h:1106
KSync * ksync() const
Definition: agent.cc:905
SecurityLoggingObjectTable * slo_table() const
Definition: agent.h:550
TaskScheduler * task_scheduler() const
Definition: agent.h:1123
bool global_slo_status() const
Definition: agent.h:1370
Ip4Address router_id() const
Definition: agent.h:669
DBState * GetState(DBTableBase *tbl_base, ListenerId listener) const
Definition: db_entry.cc:38
DBTableBase * get_table() const
Definition: db_entry.cc:120
void ClearState(DBTableBase *tbl_base, ListenerId listener)
Definition: db_entry.cc:74
bool IsDeleted() const
Definition: db_entry.h:49
void SetState(DBTableBase *tbl_base, ListenerId listener, DBState *state)
Definition: db_entry.cc:23
ListenerId Register(ChangeCallback callback, const std::string &name="unspecified")
Definition: db_table.cc:208
DBTableBase * parent()
boost::asio::io_context * io_service()
Definition: event_manager.h:43
FlowEntry * reverse_flow_entry()
Definition: flow_entry.h:603
const FlowKey & key() const
Definition: flow_entry.h:595
const boost::uuids::uuid & uuid() const
Definition: flow_entry.h:632
const std::string fw_policy_uuid() const
Definition: flow_entry.cc:3684
const Interface * intf_entry() const
Definition: flow_entry.h:653
FlowData & data()
Definition: flow_entry.h:596
const TagList & remote_tagset() const
Definition: flow_entry.cc:3563
bool is_flags_set(const FlowEntryFlags &flags) const
Definition: flow_entry.h:611
uint32_t flow_handle() const
Definition: flow_entry.h:601
static bool ShouldDrop(uint32_t action)
Definition: flow_entry.cc:1114
TunnelType tunnel_type() const
Definition: flow_entry.h:644
uint8_t gen_id() const
Definition: flow_entry.h:600
const std::string RemotePrefix() const
Definition: flow_entry.cc:3589
const std::string & nw_ace_uuid() const
Definition: flow_entry.h:637
const std::string fw_policy_name_uuid() const
Definition: flow_entry.cc:3688
const std::string & peer_vrouter() const
Definition: flow_entry.h:643
const std::string & sg_rule_uuid() const
Definition: flow_entry.h:634
bool IsServerFlow()
Definition: flow_entry.cc:1450
bool IsIngressFlow() const
Definition: flow_entry.h:686
FlowTable * flow_table() const
Definition: flow_entry.h:598
static std::string DropReasonStr(uint16_t reason)
Definition: flow_entry.cc:1479
bool deleted()
Definition: flow_entry.h:681
const TagList & local_tagset() const
Definition: flow_entry.cc:3556
bool IsClientFlow()
Definition: flow_entry.cc:1423
@ FLOW_MESSAGE
Definition: flow_event.h:24
static uint64_t GetCurrentTime()
static uint64_t GetFlowStats(const uint16_t &oflow_data, const uint32_t &data)
std::atomic< uint64_t > session_export_disable_drops_
void FreeIndex(uint32_t idx)
void UpdateSessionSampleExportStats(uint32_t count)
uint32_t prev_cfg_flow_export_rate_
std::atomic< uint64_t > session_global_slo_logging_drops_
uint64_t threshold() const
std::atomic< bool > sessions_sampled_atleast_once_
static const uint32_t kDefaultFlowSamplingThreshold
uint32_t session_export_count_reset()
std::atomic< uint64_t > session_slo_logging_drops_
void set_sessions_sampled_atleast_once()
std::atomic< uint32_t > session_export_count_
std::atomic< uint64_t > session_export_drops_
void UpdateSessionExportStats(uint32_t count, bool first_export, bool sampled)
std::atomic< uint64_t > session_export_sampling_drops_
uint32_t session_export_count() const
uint64_t prev_flow_export_rate_compute_time_
void UpdateThreshold(uint64_t new_value, bool check_oflow)
uint32_t session_export_rate() const
uint32_t session_export_without_sampling_reset()
void UpdateSessionMsgExportStats(uint32_t count)
static void GetFlowSandeshActionParams(const FlowAction &action_info, std::string &action_str)
Definition: flow_table.cc:938
uint16_t table_index() const
Definition: flow_table.h:209
SessionEndpointKey session_endpoint_key()
SessionAggKey session_agg_key()
bool IsEqual(FlowToSessionMap &rhs)
boost::uuids::uuid slo_uuid() const
static const int32_t kDisableSampling
@ VM_INTERFACE
Definition: interface.h:38
Type type() const
Definition: interface.h:115
const vr_flow_entry * GetKFlowStatsAndInfo(const FlowKey &key, uint32_t idx, uint8_t gen_id, vr_flow_stats *stats, KFlowData *info) const
GlobalVrouter * global_vrouter() const
Definition: operdb_init.h:55
const boost::uuids::uuid & uuid() const
SloRuleList & firewall_rule_list()
SloRuleList & firewall_policy_list()
const std::vector< autogen::SecurityLoggingObjectRuleEntryType > & rules() const
void DeleteSessionSloStateRuleEntry(std::string uuid)
bool UpdateSessionSloStateRuleRefCount(const std::string &uuid, bool *matc)
void UpdateSessionSloStateRuleEntry(std::string uuid, int rate)
SessionStatsCollector * FlowToCollector(const FlowEntry *flow)
SessionStatsCollectorObject(Agent *agent, FlowStatsManager *mgr)
SessionStatsCollector * GetCollector(uint8_t idx) const
std::string Description() const
Gives a description of the task.
bool Run()
Code to execute in a task. Returns true if task is completed. Return false to reschedule the task.
void FillSessionEvictStats(SessionPreAggInfo::SessionMap::iterator session_map_iter, SessionInfo *session_info, bool is_sampling, bool is_logging) const
void AddFlowToSessionMap(FlowEntry *fe, SessionKey session_key, SessionAggKey session_agg_key, SessionEndpointKey session_endpoint_key)
void FillSessionRemoteTags(const TagList &list, SessionEndpoint *ep) const
void GetPolicyIdFromFlow(const FlowEntry *fe, std::string &fw_policy_uuid, std::string &nw_policy_uuid, std::string &sg_policy_uuid)
bool SessionStatsChangedLocked(SessionPreAggInfo::SessionMap::iterator session_map_iter, SessionStatsParams *params) const
void FillSessionInfoLocked(SessionPreAggInfo::SessionMap::iterator session_map_iter, const SessionStatsParams &stats, SessionInfo *session_info, SessionIpPort *session_key, bool is_sampling, bool is_logging) const
void FillSessionFlowStats(const SessionFlowStatsParams &stats, SessionFlowInfo *flow_info, bool is_sampling, bool is_logging) const
void AddSloFirewallPolicies(SecurityLoggingObject *slo, SessionSloRuleMap *r_map)
bool MatchSloForFlow(const SessionStatsInfo &stats_info, const FlowEntry *fe, const std::string &fw_policy_uuid, const std::string &nw_policy_uuid, const std::string &sg_policy_uuid, const bool &deleted_flag, bool *logged, const bool &exported_once)
void AddSloEntry(const boost::uuids::uuid &uuid, SessionSloRuleMap *slo_rule_map)
void AddSloEntryRules(SecurityLoggingObject *slo, SessionSloRuleMap *slo_rule_map)
SessionAggKey session_agg_iteration_key_
void BuildSloList(const SessionStatsInfo &stats_info, const FlowEntry *fe, SessionSloRuleMap *global_session_slo_rule_map, SessionSloRuleMap *vmi_session_slo_rule_map, SessionSloRuleMap *vn_session_slo_rule_map)
SessionEndpointKey session_ep_iteration_key_
std::map< std::string, SessionSloRuleEntry > SessionSloRuleMap
void FillSessionTags(const TagList &list, SessionEndpoint *ep) const
std::vector< SessionEndpoint > session_msg_list_
void CopyFlowInfoInternal(SessionFlowExportInfo *info, const boost::uuids::uuid &u, FlowEntry *fe) const
void FillSessionFlowInfo(const SessionFlowStatsInfo &session_flow, const SessionStatsInfo &sinfo, const SessionFlowExportInfo &einfo, SessionFlowInfo *flow_info) const
bool CheckSessionLogging(const SessionStatsInfo &stats_info)
bool SessionStatsChangedUnlocked(SessionPreAggInfo::SessionMap::iterator session_map_iter, SessionStatsParams *params) const
void UpdateAggregateStats(const SessionInfo &sinfo, SessionAggInfo *agg_info, bool is_sampling, bool is_logging) const
void UpdateSloStateRules(SecurityLoggingObject *slo, SessionSloState *state)
bool RequestHandler(boost::shared_ptr< SessionStatsReq > req)
void UpdateSessionStatsInfo(FlowEntry *fe, uint64_t setup_time, SessionStatsInfo *session) const
bool SampleSession(SessionPreAggInfo::SessionMap::iterator session_map_iter, SessionStatsParams *params) const
static const uint32_t kSessionsPerTask
void CopyFlowInfo(SessionStatsInfo &session, const RevFlowDepParams *params)
bool FetchFlowStats(SessionFlowStatsInfo *info, SessionFlowStatsParams *params) const
void UpdateSessionStatsEvent(const FlowEntryPtr &flow, uint32_t bytes, uint32_t packets, uint32_t oflow_bytes, const boost::uuids::uuid &u)
void AddSloFirewallRules(SecurityLoggingObject *slo, SessionSloRuleMap *rule_map)
void EvictedSessionStatsUpdate(const FlowEntryPtr &flow, uint32_t bytes, uint32_t packets, uint32_t oflow_bytes, const boost::uuids::uuid &u)
void MakeSloList(const FlowEntry *fe, SessionSloRuleMap *vmi_session_slo_rule_map, SessionSloRuleMap *vn_session_slo_rule_map)
void UpdateSessionFlowStatsInfo(FlowEntry *fe, SessionFlowStatsInfo *session_flow) const
bool CheckPolicyMatch(const SessionSloRuleMap &map, const std::string &policy_uuid, const bool &deleted_flag, bool *match, const bool &exported_once)
uint32_t RunSessionEndpointStats(uint32_t max_count)
void FillSessionInfoUnlocked(SessionPreAggInfo::SessionMap::iterator session_map_iter, const SessionStatsParams &stats, SessionInfo *session_info, SessionIpPort *session_key, const RevFlowDepParams *params, bool read_flow, bool is_sampling, bool is_logging) const
void DeleteFlowToSessionMap(FlowEntry *fe)
void AddSloRules(const std::vector< autogen::SecurityLoggingObjectRuleEntryType > &list, SecurityLoggingObject *slo, SessionSloRuleMap *slo_rule_map)
bool DeletedFlowLogging(const SessionStatsInfo &stats_info, const SessionFlowExportInfo &flow_info, bool *logged, const bool &exported_once)
static uint64_t GetCurrentTime()
void FillSessionEndpoint(SessionEndpointMap::iterator it, SessionEndpoint *session_ep) const
bool CheckAndDeleteSessionStatsFlow(SessionPreAggInfo::SessionMap::iterator session_map_iter)
SessionStatsCollector(boost::asio::io_context &io, AgentUveBase *uve, uint32_t instance_id, FlowStatsManager *fsm, SessionStatsCollectorObject *obj)
void AddSession(FlowEntry *fe, uint64_t setup_time)
void DeleteSession(FlowEntry *fe, const boost::uuids::uuid &del_uuid, uint64_t teardown_time, const RevFlowDepParams *params)
SessionEndpointMap session_endpoint_map_
void FillSessionAggInfo(SessionEndpointInfo::SessionAggMap::iterator it, SessionIpPortProtocol *session_agg_key) const
void DeleteEvent(const FlowEntryPtr &flow, const RevFlowDepParams &params)
int ComputeSloRate(int rate, SecurityLoggingObject *slo) const
bool FindSloMatchRule(const SessionSloRuleMap &map, const std::string &fw_policy_uuid, const std::string &nw_policy_uuid, const std::string &sg_policy_uuid, const bool &deleted_flag, bool *match, const bool &exported_once)
virtual void DispatchSessionMsg(const std::vector< SessionEndpoint > &lst)
bool HandleFlowLogging(const SessionStatsInfo &stats_info)
void AddEvent(const FlowEntryPtr &flow)
uint64_t GetUpdatedSessionFlowPackets(uint64_t info_packets, uint64_t k_flow_pkts) const
bool ProcessSessionEndpoint(const SessionEndpointMap::iterator &it)
void GetPolicyIdFromDeletedFlow(const SessionFlowExportInfo &flow_info, std::string &fw_policy_uuid, std::string &nw_policy_uuid, std::string &sg_policy_uuid)
void SloNotify(DBTablePartBase *partition, DBEntryBase *e)
bool GetSessionKey(FlowEntry *fe, SessionAggKey &session_agg_key, SessionKey &session_key, SessionEndpointKey &session_endpoint_key)
DBTable::ListenerId slo_listener_id_
void AddSessionSloRuleEntry(const std::string &uuid, int rate, SecurityLoggingObject *slo, SessionSloRuleMap *slo_rule_map)
FlowStatsManager * flow_stats_manager_
void AddSloList(const UuidList &slo_list, SessionSloRuleMap *slo_rule_map)
bool HandleDeletedFlowLogging(const SessionStatsInfo &stats_info)
uint64_t GetUpdatedSessionFlowBytes(uint64_t info_bytes, uint64_t k_flow_bytes) const
bool FlowLogging(const SessionStatsInfo &stats_info, const FlowEntry *fe, bool *logged, const bool &exported_once)
bool UpdateSloMatchRuleEntry(const boost::uuids::uuid &slo_uuid, const std::string &match_uuid, bool *match)
FlowEntry * reverse_flow() const
The TaskScheduler keeps track of what tasks are currently schedulable. When a task is enqueued it is ...
Definition: task.h:307
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
Task is a class to describe a computational task within OpenSDN control plane applications....
Definition: task.h:82
Definition: trace.h:289
Type GetType() const
Definition: nexthop.h:304
const UuidList & slo_list() const
const std::string & service_intf_type() const
const std::string & cfg_name() const
const VnEntry * vn() const
const UuidList & slo_list() const
Definition: vn.h:226
bool Enqueue(QueueEntryT entry)
Definition: queue_task.h:249
size_t Length() const
Definition: queue_task.h:357
void Shutdown(bool delete_entries=true)
Definition: queue_task.h:153
void set_measure_busy_time(bool val) const
Definition: queue_task.h:380
void SetBounded(bool bounded)
Definition: queue_task.h:201
void SetExitCallback(TaskExitCallback on_exit)
Definition: queue_task.h:304
void set_name(const std::string &name)
Definition: queue_task.h:308
void SetEntryCallback(TaskEntryCallback on_entry)
Definition: queue_task.h:300
boost::intrusive_ptr< FlowEntry > FlowEntryPtr
Definition: flow_entry.h:126
#define FLOW_EXPORT_STATS_TRACE(...)
#define FLOW_LOCK(flow, rflow, flow_event)
Definition: flow_table.h:62
#define LOG(_Level, _Msg)
Definition: logging.h:35
Definition: io_utils.cc:12
boost::shared_ptr< TraceBuffer< SandeshTrace > > SandeshTraceBufferPtr
Definition: sandesh_trace.h:19
SandeshTraceBufferPtr SandeshTraceBufferCreate(const std::string &buf_name, size_t buf_size, bool trace_enable=true)
Definition: sandesh_trace.h:47
std::vector< SloRuleInfo > SloRuleList
SandeshTraceBufferPtr SessionStatsTraceBuf(SandeshTraceBufferCreate("SessionStats", 4000))
bool session_debug_
static void TraceSession(const string &op, const SessionEndpointKey &ep, const SessionAggKey &agg, const SessionKey &session, bool rev_flow_params)
static void BuildTraceTagList(const TagList &slist, vector< string > *dlist)
#define DEFAULT_SSC_REQUEST_QUEUE_SIZE
#define MAX_SSC_REQUEST_QUEUE_ITERATIONS
#define SESSION_STATS_TRACE(obj,...)
#define CheckFlowLogging(logged)
static boost::uuids::uuid StringToUuid(const std::string &str)
Definition: string_util.h:146
static const std::string integerToString(const NumberType &num)
Definition: string_util.h:20
Definition: acl.h:62
uint32_t action
Definition: acl.h:44
std::string origin_vn_dst
Definition: flow_entry.h:298
uint16_t drop_reason
Definition: flow_entry.h:336
MatchPolicy match_p
Definition: flow_entry.h:310
std::string source_vn_match
Definition: flow_entry.h:295
std::string vm_cfg_name
Definition: flow_entry.h:358
std::string origin_vn_src
Definition: flow_entry.h:297
std::string dest_vn_match
Definition: flow_entry.h:296
uint8_t protocol
Definition: flow_entry.h:216
IpAddress src_addr
Definition: flow_entry.h:214
IpAddress dst_addr
Definition: flow_entry.h:215
uint16_t src_port
Definition: flow_entry.h:217
uint16_t dst_port
Definition: flow_entry.h:218
uint16_t tcp_flags
uint16_t underlay_src_port
FlowAction action_info
Definition: flow_entry.h:278
FlowAction action_info_
Definition: flow_entry.h:67
std::string sg_uuid_
Definition: flow_entry.h:63
std::string nw_ace_uuid_
Definition: flow_entry.h:66
bool IsEqual(const SessionAggKey &rhs) const
bool IsLess(const SessionAggKey &rhs) const
bool IsEqual(const SessionEndpointKey &rhs) const
bool IsLess(const SessionEndpointKey &rhs) const
SessionFlowExportInfo fwd_flow
SessionFlowExportInfo rev_flow
bool IsEqual(const SessionKey &rhs) const
boost::uuids::uuid uuid
bool IsLess(const SessionKey &rhs) const
SessionExportInfo export_info
SessionFlowStatsInfo fwd_flow
SessionFlowStatsInfo rev_flow
SessionFlowStatsParams rev_flow
SessionFlowStatsParams fwd_flow
boost::uuids::uuid uuid_
std::set< string > label_set
std::string application
std::string tier
std::string site
std::string deployment
std::set< string > custom_tag_set
static std::string UTCUsecToString(uint64_t tstamp)
Definition: time_util.h:55
static uint64_t ClockMonotonicUsec()
Definition: time_util.h:30
static uint64_t UTCTimestampUsec()
Definition: time_util.h:14
boost::uuids::uuid uuid