//===========================================================================
//  @(#) $Name: arts++-1-1-a12 $
//  @(#) $Id: ArtsAsMatrixAggregator.cc,v 1.2 2004/04/21 23:51:31 kkeys Exp $
//===========================================================================
//  Copyright Notice
//
//  By accessing this software, arts++, you are duly informed
//  of and agree to be bound by the conditions described below in this
//  notice:
//
//  This software product, arts++, is developed by Daniel W. McRobb, and
//  copyrighted(C) 1998 by the University of California, San Diego
//  (UCSD), with all rights reserved.  UCSD administers the CAIDA grant,
//  NCR-9711092, under which part of this code was developed.
//
//  There is no charge for arts++ software.  You can redistribute it
//  and/or modify it under the terms of the GNU Lesser General Public
//  License, Version 2.1, February 1999, which is incorporated by
//  reference herein.
//
//  arts++ is distributed WITHOUT ANY WARRANTY, IMPLIED OR EXPRESS, OF
//  MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE or that the use
//  of it will not infringe on any third party's intellectual
//  property rights.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with arts++.  Copies can also be obtained from:
//
//    http://www.gnu.org/copyleft/lesser.html
//
//  or by writing to:
//
//  Free Software Foundation, Inc.
//  59 Temple Place, Suite 330
//  Boston, MA 02111-1307
//  USA
//
//  Or contact:
//
//    info@caida.org
//===========================================================================

#include <string>

#include "ArtsAsMatrixAggregator.hh"

using namespace std;

static const std::string rcsid = "@(#) $Name: arts++-1-1-a12 $ $Id: ArtsAsMatrixAggregator.cc,v 1.2 2004/04/21 23:51:31 kkeys Exp $";

//-------------------------------------------------------------------------
//         bool ArtsAsMatrixKeyValue::                      
//         operator < (const ArtsAsMatrixKeyValue keyValue) const 
//.........................................................................
//  
//-------------------------------------------------------------------------
bool ArtsAsMatrixKeyValue::
operator < (const ArtsAsMatrixKeyValue keyValue) const
{
  if (this->srcAs < keyValue.srcAs)
    return(true);
  if (this->srcAs > keyValue.srcAs)
    return(false);
  
  if (this->dstAs < keyValue.dstAs)
    return(true);
  if (this->dstAs > keyValue.dstAs)
    return(false);

  return(false);
}

//---------------------------------------------------------------------------
//        bool ArtsAsMatrixKeyValue::
//        operator == (const ArtsAsMatrixKeyValue keyValue) const
//...........................................................................
//
//---------------------------------------------------------------------------
bool ArtsAsMatrixKeyValue::
operator == (const ArtsAsMatrixKeyValue keyValue) const
{
  if (this->srcAs == keyValue.srcAs &&
      this->dstAs == keyValue.dstAs)
    return(true);
  return(false);
}

//-------------------------------------------------------------------------
//   ArtsAsMatrixAggregator::ArtsAsMatrixAggregator(const Arts & arts)   
//.........................................................................
//  
//-------------------------------------------------------------------------
ArtsAsMatrixAggregator::ArtsAsMatrixAggregator(const Arts & arts)
{
  assert(arts.Header().Identifier() == artsC_OBJECT_AS_MATRIX);
  
  this->_header = arts.Header();

  vector<ArtsAttribute>::const_iterator    inAttribute;

  for (inAttribute = arts.Attributes().begin();
       inAttribute != arts.Attributes().end(); ++inAttribute) {
    this->_attributes.push_back(*inAttribute);
  }

  counter_t               asMatrixCounter;
  ArtsAsMatrixKeyValue   key;
  vector<ArtsAsMatrixEntry>::const_iterator  inAsMatrixEntry;
  
  for (inAsMatrixEntry = arts.AsMatrixData()->AsEntries().begin();
       inAsMatrixEntry != arts.AsMatrixData()->AsEntries().end();
       ++inAsMatrixEntry) {
    key.srcAs = inAsMatrixEntry->Src();
    key.dstAs = inAsMatrixEntry->Dst();
    
    asMatrixCounter.Pkts = inAsMatrixEntry->Pkts();
    asMatrixCounter.Bytes = inAsMatrixEntry->Bytes();
    this->_asCounters[key] = asMatrixCounter;
  }
  this->_totalPkts = arts.AsMatrixData()->TotalPkts();
  this->_totalBytes = arts.AsMatrixData()->TotalBytes();
}

//-------------------------------------------------------------------------
//           void ArtsAsMatrixAggregator::Add(const Arts & arts)          
//.........................................................................
//  
//-------------------------------------------------------------------------
void ArtsAsMatrixAggregator::Add(const Arts & arts)
{
  assert(arts.Header().Identifier() == artsC_OBJECT_AS_MATRIX);

  vector<ArtsAttribute>::iterator          myHostAttribute;

  for (myHostAttribute = this->_attributes.begin();
         myHostAttribute != this->_attributes.end();
         ++myHostAttribute) {
    if (myHostAttribute->Identifier() == artsC_ATTR_HOST)
      break;
  }
  
  vector<ArtsAttribute>::iterator          myPeriodAttribute;
  vector<ArtsAttribute>::const_iterator    inPeriodAttribute;
  
  for (myPeriodAttribute = this->_attributes.begin();
         myPeriodAttribute != this->_attributes.end();
         ++myPeriodAttribute) {
    if (myPeriodAttribute->Identifier() == artsC_ATTR_PERIOD)
      break;
  }
  
  inPeriodAttribute = arts.FindPeriodAttribute();

  const uint32_t *myPeriod = myPeriodAttribute->Period();
  const uint32_t *inPeriod = inPeriodAttribute->Period();
  
  if (inPeriod[0] < myPeriod[0]) {
    myPeriodAttribute->Period(inPeriod[0],myPeriod[1]);
  }
  if (inPeriod[1] > myPeriod[1]) {
    myPeriodAttribute->Period(myPeriod[0],inPeriod[1]);
  }
    
  counter_t               asCounter;
  ArtsAsMatrixKeyValue   key;
  vector<ArtsAsMatrixEntry>::const_iterator        inAsEntry;
  map<ArtsAsMatrixKeyValue,counter_t,less<ArtsAsMatrixKeyValue> >::iterator   myAsEntry;

  for (inAsEntry = arts.AsMatrixData()->AsEntries().begin();
       inAsEntry != arts.AsMatrixData()->AsEntries().end();
       ++inAsEntry) {
    key.srcAs = inAsEntry->Src();
    key.dstAs = inAsEntry->Dst();
    
    myAsEntry = this->_asCounters.find(key);
    if (myAsEntry != this->_asCounters.end()) {
      (*myAsEntry).second.Pkts += inAsEntry->Pkts();
      (*myAsEntry).second.Bytes += inAsEntry->Bytes();
    }
    else {
      asCounter.Pkts = inAsEntry->Pkts();
      asCounter.Bytes = inAsEntry->Bytes();
      this->_asCounters[key] = asCounter;
    }
  }
  this->_totalPkts += arts.AsMatrixData()->TotalPkts();
  this->_totalBytes += arts.AsMatrixData()->TotalBytes();

  return;
}

//-------------------------------------------------------------------------
//  ArtsAsMatrix *ArtsAsMatrixAggregator::ConvertToArtsAsMatrix() const 
//.........................................................................
//  
//-------------------------------------------------------------------------
ArtsAsMatrix *ArtsAsMatrixAggregator::ConvertToArtsAsMatrix() const
{
  ArtsAsMatrixEntry  asEntry;
  map<ArtsAsMatrixKeyValue,counter_t,less<ArtsAsMatrixKeyValue> >::const_iterator  asCounter;

  ArtsAsMatrix *artsAsMatrix = new ArtsAsMatrix();
  assert(artsAsMatrix != (ArtsAsMatrix *)0);

  artsAsMatrix->Header() = this->_header;
  vector<ArtsAttribute>::const_iterator   inAttribute;

  for (inAttribute = this->_attributes.begin();
       inAttribute != this->_attributes.end(); ++inAttribute) {
    artsAsMatrix->Attributes().push_back(*inAttribute);
  }

  uint64_t  totalPkts = 0;
  uint64_t  totalBytes = 0;
  
  for (asCounter = this->_asCounters.begin();
       asCounter != this->_asCounters.end(); ++asCounter) {
    asEntry.Src((*asCounter).first.srcAs);
    asEntry.Dst((*asCounter).first.dstAs);
    asEntry.Pkts((*asCounter).second.Pkts);
    asEntry.Bytes((*asCounter).second.Bytes);
    artsAsMatrix->AsEntries().push_back(asEntry);
    totalPkts += asEntry.Pkts();
    totalBytes += asEntry.Bytes();
  }
  artsAsMatrix->TotalPkts(totalPkts);
  artsAsMatrix->TotalBytes(totalBytes);
  
  return(artsAsMatrix);
}

//-------------------------------------------------------------------------
//     vector<ArtsAsMatrixEntry> *                       
//     ArtsAsMatrixAggregator::TopSourcesByBytes(uint16_t numSources) 
//.........................................................................
//  
//-------------------------------------------------------------------------
vector<ArtsAsMatrixEntry> *
ArtsAsMatrixAggregator::TopSourcesByBytes(uint16_t numSources)
{
  map<uint16_t,counter_t,less<uint16_t> >  srcAsMap;
  map<ArtsAsMatrixKeyValue,counter_t,less<ArtsAsMatrixKeyValue> >::iterator aggMapIter;
  
  //  load a map keyed by source AS, with a counter_t as the value.
  map<uint16_t,counter_t,less<uint16_t> >::iterator  srcAsMapIter;
  for (aggMapIter = this->_asCounters.begin();
       aggMapIter != this->_asCounters.end(); ++aggMapIter) {
    srcAsMapIter = srcAsMap.find((*aggMapIter).first.srcAs);
    if (srcAsMapIter == srcAsMap.end()) {
      srcAsMap[(*aggMapIter).first.srcAs].Pkts = (*aggMapIter).second.Pkts;
      srcAsMap[(*aggMapIter).first.srcAs].Bytes = (*aggMapIter).second.Bytes;
    }
    else {
      (*srcAsMapIter).second.Pkts += (*aggMapIter).second.Pkts;
      (*srcAsMapIter).second.Bytes += (*aggMapIter).second.Bytes;
    }
  }

  //  Now I have a map<uint16_t,counter_t> with src AS as key and
  //  counter_t as value.  Put it in a vector of ArtsAsMatrixEntry
  //  so I can sort it by byte count.
  ArtsAsMatrixEntry           srcAsEntry;
  vector<ArtsAsMatrixEntry>   srcAsVector;

  srcAsVector.reserve(srcAsMap.size());
  map<uint16_t,counter_t,less<uint16_t> >::iterator  srcMapIter;
  
  for (srcMapIter = srcAsMap.begin();
       srcMapIter != srcAsMap.end(); ++srcMapIter) {
    srcAsEntry.Src((*srcMapIter).first);
    srcAsEntry.Dst(0);
    srcAsEntry.Pkts((*srcMapIter).second.Pkts);
    srcAsEntry.Bytes((*srcMapIter).second.Bytes);
    srcAsVector.push_back(srcAsEntry);
  }

  // now sort the vector by the byte counters.
  sort(srcAsVector.begin(),srcAsVector.end(),
       ArtsAsMatrixEntryGreaterBytes());

  //  build the final vector we wish to return.
  vector<ArtsAsMatrixEntry>  *retVector;

  if (srcAsVector.size() < numSources)
    numSources = srcAsVector.size();
  
  retVector = new vector<ArtsAsMatrixEntry>(srcAsVector.begin(),
                                            srcAsVector.begin() + numSources);
  assert(retVector != (vector<ArtsAsMatrixEntry> *)0);
  return(retVector);
}


//-------------------------------------------------------------------------
//   vector<ArtsAsMatrixEntry> *                       
//   ArtsAsMatrixAggregator::TopDestinationsByBytes(uint16_t numDests) 
//.........................................................................
//  
//-------------------------------------------------------------------------
vector<ArtsAsMatrixEntry> *
ArtsAsMatrixAggregator::TopDestinationsByBytes(uint16_t numDests)
{
  map<uint16_t,counter_t,less<uint16_t> >  dstAsMap;
  map<ArtsAsMatrixKeyValue,counter_t,less<ArtsAsMatrixKeyValue> >::iterator aggMapIter;
  
  //  load a map keyed by source AS, with a counter_t as the value.
  map<uint16_t,counter_t,less<uint16_t> >::iterator  dstAsMapIter;
  for (aggMapIter = this->_asCounters.begin();
       aggMapIter != this->_asCounters.end(); ++aggMapIter) {
    dstAsMapIter = dstAsMap.find((*aggMapIter).first.dstAs);
    if (dstAsMapIter == dstAsMap.end()) {
      dstAsMap[(*aggMapIter).first.dstAs].Pkts = (*aggMapIter).second.Pkts;
      dstAsMap[(*aggMapIter).first.dstAs].Bytes = (*aggMapIter).second.Bytes;
    }
    else {
      (*dstAsMapIter).second.Pkts += (*aggMapIter).second.Pkts;
      (*dstAsMapIter).second.Bytes += (*aggMapIter).second.Bytes;
    }
  }

  //  Now I have a map<uint16_t,counter_t> with dst AS as key and
  //  counter_t as value.  Put it in a vector of ArtsAsMatrixEntry
  //  so I can sort it by byte count.
  ArtsAsMatrixEntry           dstAsEntry;
  vector<ArtsAsMatrixEntry>   dstAsVector;

  dstAsVector.reserve(dstAsMap.size());
  map<uint16_t,counter_t,less<uint16_t> >::iterator  dstMapIter;
  
  for (dstMapIter = dstAsMap.begin();
       dstMapIter != dstAsMap.end(); ++dstMapIter) {
    dstAsEntry.Dst((*dstMapIter).first);
    dstAsEntry.Src(0);
    dstAsEntry.Pkts((*dstMapIter).second.Pkts);
    dstAsEntry.Bytes((*dstMapIter).second.Bytes);
    dstAsVector.push_back(dstAsEntry);
  }

  // now sort the vector by the byte counters.
  sort(dstAsVector.begin(),dstAsVector.end(),
       ArtsAsMatrixEntryGreaterBytes());

  //  build the final vector we wish to return.
  vector<ArtsAsMatrixEntry>  *retVector;

  if (dstAsVector.size() < numDests)
    numDests = dstAsVector.size();
  
  retVector = new vector<ArtsAsMatrixEntry>(dstAsVector.begin(),
                                            dstAsVector.begin() + numDests);
  assert(retVector != (vector<ArtsAsMatrixEntry> *)0);
  return(retVector);
}

//-------------------------------------------------------------------------
//            uint64_t ArtsAsMatrixAggregator::TotalPkts() const           
//.........................................................................
//  
//-------------------------------------------------------------------------
uint64_t ArtsAsMatrixAggregator::TotalPkts() const
{
  return(this->_totalPkts);
}

//-------------------------------------------------------------------------
//           uint64_t ArtsAsMatrixAggregator::TotalBytes() const           
//.........................................................................
//  
//-------------------------------------------------------------------------
uint64_t ArtsAsMatrixAggregator::TotalBytes() const
{
  return(this->_totalBytes);
}

//-------------------------------------------------------------------------
//             const vector<ArtsAttribute> & Attributes() const            
//.........................................................................
//  
//-------------------------------------------------------------------------
const vector<ArtsAttribute> & ArtsAsMatrixAggregator::Attributes() const
{
  return(this->_attributes);
}
