# ===============================================
# (C) 2018 AO Kaspersky Lab. All Rights Reserved.
# ===============================================

import base64
import cStringIO as StringIO
import datetime
import fnmatch
import gzip
import hashlib
import json
import logging
import socket
import sys
import threading
import time

import iu_config as config
import iu_core as core
from iu_path_definer import PathStrDefiner


ScriptVersionStr = '1.105'


OptSimulateMode = False
OptMaxObjectCount = None
OptNoUpdate = False
OptTestMode = False
OptTestKsn = False
OptPortion = None
OptWriteLastDate = False
OptProcessNewRecords = False
OptProcessRescan = False


def CommonSchemaName():
  return getattr(config, 'APT_DB_SCHEMA_COMMON', None)

def ScoringSchemaName():
  return getattr(config, 'APT_DB_SCHEMA_SCORING', None)


def FormatRecord(record):
  s = []
  for field in record:
    descr = '%s=%s' % (field[0], field[1])
    if isinstance(descr, unicode):
      descr = descr.encode('utf-8')
    s.append(descr)
  return ' '.join(s)


def GetReplyTime(reply):
  t = getattr(reply, 'replyTime',None)
  if t == None:
    t = core.CurrentTimeUtc()
  return core.TimeToSql(t)



def GetDic(dic,name):
  if dic == None:
    return None
  if name in dic:
    return dic[name]
  return None


def GetListItem(lst,idx):
  if lst==None:
    return None
  if isinstance(lst,dict):
    return None
  try:
    return lst[idx]
  except Exception:
    return None


def SerStr(lst):
  if lst == None:
    return None
  return ' '.join(lst)


class RankInterval(object):
  def __init__(self):
    self.position = None
    self.popularity = None
    self.peak_position = None
    self.peak_popularity = None

  def Init(self,dic):
    self.position = GetDic(dic, 'position')
    self.popularity = GetDic(dic, 'popularity')
    self.peak_position = GetDic(dic, 'peak_position_number')
    self.peak_popularity = GetDic(dic, 'peak_count_popularity')


class Rank(object):
  def __init__(self):
    self.day = RankInterval()
    self.week = RankInterval()
    self.month = RankInterval()

def GetRank(dic):
  if not isinstance(dic, dict):
    return None

  rank = Rank()
  if '1' in dic:
    rank.day.Init(dic['1'])
  if '7' in dic:
    rank.week.Init(dic['7'])
  if '30' in dic:
    rank.month.Init(dic['30'])

  return rank


def GetRankIp(ip_reply):
  rank = None

  if GetDic(ip_reply, 'ip') is not None:
    if 'popularity' in ip_reply:
      rank = Rank()
      rank.day.popularity = ip_reply['popularity']
      rank.week.popularity = ip_reply['popularity']
      rank.month.popularity = ip_reply['popularity']
    else:
      rank = GetRank(ip_reply)

  return rank


def CheckReplyHashType(reply, expType):
  replyType = GetDic(reply.result, 'type')
  if replyType == expType:
    return True

  logging.warning('Reply hash type mismatch (key:%s type:%s, expected:%s)',
                  reply.key,
                  replyType,
                  expType)
  return False


def GetUtf8Str(name):
  if isinstance(name, unicode):
    return name.encode('utf-8')
  return str(name)


def GetNameHashStr(name):
  if not isinstance(name, unicode):
    name = name.decode('utf-8', 'ignore')
  data = name.encode('utf-16le')
  return core.Bin2Hex(hashlib.md5(data).digest())


def EncodeIDNA(url):
  if not isinstance(url, unicode):
    url = url.decode('utf-8')

  try:
    url = url.encode('idna')
  except UnicodeError:
    url = url.encode('utf-8')

  return url


totalCountStart = 0
totalCountSent = 0
totalCountRecv = 0
totalCountErrs = 0
totalCountWrite = 0

totalCountQueryStart = 0
totalCountQuerySelect = 0
totalCountQueryDone = 0

totalErrors = 0

statLock = threading.Lock()

def LogStatistics(file_name):
  if not file_name:
    return

  with open(file_name, 'w') as out_f:
    format_string = '[{time}] start={start} sent={sent} recv={recv} errs={errs} write={write}\n' \
                    'qry_start={qry_start} qry_select={qry_select} qry_done={qry_done}'

    out_f.write(format_string.format(time=core.CurrentTimeUtc(),
                                     start=totalCountStart,
                                     sent=totalCountSent,
                                     recv=totalCountRecv,
                                     errs=totalCountErrs,
                                     write=totalCountWrite,
                                     qry_start=totalCountQueryStart,
                                     qry_select=totalCountQuerySelect,
                                     qry_done=totalCountQueryDone))


def LogError(msg=None):
  global totalErrors
  global statLock
  with statLock:
    totalErrors += 1
  if msg:
    logging.error(msg)

def ClearErrors():
  global totalErrors
  totalErrors = 0


def ClearDictionaries(db_conn=None):
  query_proc_name = core.DbName(config.APT_DB_SCHEMA, 'ClearDicts')

  try:
    logging.info('Starting query: %s', query_proc_name)

    db_conn = db_conn or core.DbConnection()
    db_conn.ExecProc(query_proc_name,())

    logging.info('Finished query: %s', query_proc_name)

  except Exception as e:
    logging.exception('Error calling %s: %s', query_proc_name, e)
    raise


def GetObjectiveDates(db_conn):
  current_time = core.CurrentTimeUtc()
  objective_dates = {}

  for service_type in ServiceTypes.itervalues():
    if isinstance(service_type, ServiceTypeRescan):
      service_key_name = service_type.GetServiceKeyName()
      if service_key_name is not None:
        objective_dates[service_key_name] = current_time

  try:
    query_proc_name = core.DbName(config.APT_DB_SCHEMA, 'GetLastAggregateDates')
    logging.info('Starting query: %s', query_proc_name)

    db_conn = db_conn or core.DbConnection()
    with db_conn.QueryProc(query_proc_name, ()) as cursor:
      for r in cursor:
        service_key_name, aggregate_date = r[0], r[1]
        if service_key_name is None or aggregate_date is None:
          continue

        logging.info('LastAggregateDate(%s) : %s (delta: %s)',
                     service_key_name,
                     aggregate_date,
                     current_time - aggregate_date)

        objective_dates[service_key_name] = aggregate_date

    logging.info('Finished query: %s', query_proc_name)

  except Exception as e:
    logging.exception('Error calling %s: %s', query_proc_name, e)
    raise

  if config.APT_NEW_RECORDS_RESCAN_LAG:
    for service_type in ServiceTypes.itervalues():
      if (isinstance(service_type, ServiceTypeNew) or
          isinstance(service_type, ServiceTypeRescan)):
        service_key_name = service_type.GetServiceKeyName()
        if service_key_name in objective_dates:
          objective_dates[service_key_name] -= config.APT_NEW_RECORDS_RESCAN_LAG

  last_object_source_times = GetLastObjectSourceTimes(db_conn)

  for service_type in ServiceTypes.itervalues():
    if isinstance(service_type, ServiceTypeNew):
      service_key_name = service_type.GetServiceKeyName()
      prev_objective_date = objective_dates.get(service_key_name, datetime.datetime.min)

      object_source_time = last_object_source_times.get(service_type.object_source_query_func)
      if (object_source_time is not None and
          object_source_time - datetime.timedelta(hours=1) > prev_objective_date):

        new_objective_date = object_source_time - datetime.timedelta(hours=1)
        logging.info('No new data for %s in the DB. Skipping to %s',
                     service_key_name,
                     new_objective_date)
        objective_dates[service_key_name] = new_objective_date

  return objective_dates


def MakeServiceKey(service_key_name):
  return 'InfoUpdater.%s.%s' % (config.APT_DB_SCHEMA, service_key_name)


def GetLastObjectSourceTimes(db_conn):
  logging.info('Getting last DB object source times')

  last_object_source_times = {}
  for proc_name in ['GetLastAgentTime', 'GetLastHttpTime']:
    query_proc_name = core.DbName(ScoringSchemaName(), proc_name)

    try:
        db_conn = db_conn or core.DbConnection()
        with db_conn.QueryProc(query_proc_name, ()) as cursor:
          try:
            object_source_time = next(cursor)[0]
            last_object_source_times[proc_name] = object_source_time
            logging.info('Last object source time for %s: %s',
                         query_proc_name,
                         core.TimeToSql(object_source_time))
          except:
            pass

    except Exception as e:
      logging.exception('Error calling %s: %s', query_proc_name, e)
      raise

  return last_object_source_times


def GetProcessedDate(db_conn, service_key_name):
  query_proc_name = core.DbName(CommonSchemaName(), 'GetProcessedDate')
  processed_date = None

  try:
    logging.info('Getting ProcessedDate(%s)', service_key_name)

    service_key = MakeServiceKey(service_key_name)

    db_conn = db_conn or core.DbConnection()
    with db_conn.QueryProc(query_proc_name, (service_key,)) as cursor:
      for r in cursor:
        processed_date = r[0]

    logging.info('ProcessedDate(%s) = %s', service_key_name, core.TimeToSql(processed_date))

  except Exception as e:
    logging.exception('Error calling %s: %s', query_proc_name, e)
    raise

  return processed_date


def SetProcessedDate(db_conn, service_key_name, processed_date):
  query_proc_name = core.DbName(CommonSchemaName(), 'SetProcessedDate')

  try:
    logging.info('Setting ProcessedDate(%s) = %s',
                 service_key_name,
                 core.TimeToSql(processed_date))

    service_key = MakeServiceKey(service_key_name)

    db_conn = db_conn or core.DbConnection()
    db_conn.ExecProc(query_proc_name, (service_key, processed_date))

  except Exception as e:
    logging.exception('Error calling %s: %s', query_proc_name, e)
    raise


class ServiceType(object):
  flush_locks = {}
  object_source_query_func = None

  def __init__(self, name, serviceId):
    self.name = name
    self.serviceId = serviceId
    self.ResetStatistics()

    dict_name = self.GetDictName()
    if dict_name is not None and dict_name not in ServiceType.flush_locks:
      ServiceType.flush_locks[dict_name] = threading.RLock()

  def ResetStatistics(self):
    self.countStart   = 0
    self.countSent    = 0
    self.countRecv    = 0
    self.countErrs    = 0
    self.countWrite   = 0
    self.timeSentFirst = None
    self.timeRecvLast = None

    self.timeQueryStart = None
    self.timeQueryCursor = None
    self.timeQueryFinish = None
    self.countQuery = 0

    self.timeWriteTotal = datetime.timedelta()
    self.timeUpdateTotal = datetime.timedelta()

    self.flushTimeLast = core.CurrentTimeUtc()
    self.flushCountLast = 0

  def CreateRequest(self,key):
    return core.Request(self,key)

  def GetDictName(self):
    return None

  def GetQueryProcName(self):
    dictName = self.GetDictName()
    if dictName == None:
      return None
    return 'UpdateNeed%s' % dictName

  def GetServiceKeyName(self):
    return self.GetDictName()

  def CreateRequestsByQuery(self, row):
    if row[0] is None:
      logging.error('Invalid data in request to %s', self.GetDictName())
      return []
    return [ self.CreateRequest(row[0]) ]

  def GetCommRequestFlags(self,req):
    return core.RequestFlags.Json

  def SetCommReplyData(self, req, reply):
    req.replyJson = reply
    req.result = json.loads(reply, encoding='utf-8')

  def GetFlushLock(self):
    return GetDic(ServiceType.flush_locks, self.GetDictName())

  def WriteResults(self,replyProcessor,reply):
    logging.warning('Dropping results: %s', reply)

  def WriteEmptyResults(self, replyProcessor, reply):
    pass

  def ProcessErrorReply(self, replyProcessor, reply):
    pass

  def GetFinalizeProcName(self):
    dictName = self.GetDictName()
    if dictName == None:
      return None
    return 'Update%s' % dictName

  def GetMasterServiceType(self):
    return None

  def OnStart(self):
    global totalCountStart
    global statLock
    with statLock:
      self.countStart += 1
      totalCountStart += 1

  def OnSend(self):
    global totalCountSent
    global statLock
    with statLock:
      if self.countSent == 0:
        self.timeSentFirst = core.CurrentTimeUtc()
      self.countSent += 1
      totalCountSent += 1

  def OnRecv(self):
    global totalCountRecv
    global statLock
    with statLock:
      self.timeRecvLast = core.CurrentTimeUtc()
      self.countRecv += 1
      totalCountRecv += 1

  def OnRecvErr(self):
    global totalCountErrs
    global statLock
    with statLock:
      self.timeRecvLast = core.CurrentTimeUtc()
      self.countErrs += 1
      totalCountErrs += 1

  def OnWrite(self):
    global statLock
    with statLock:
      masterSvc = self.GetMasterServiceType()
      if masterSvc == None:
        self.countWrite += 1
      else:
        masterSvc.countWrite += 1
      global totalCountWrite
      totalCountWrite += 1


class ServiceTypeNew(object):
  def GetQueryProcName(self):
    dictName = self.GetDictName()
    if dictName is None:
      return None
    return 'UpdateNeedNew' + dictName

  def GetServiceKeyName(self):
    dictName = self.GetDictName()
    if dictName is None:
      return None
    return 'New' + dictName


class ServiceTypeRescan(object):
  def GetQueryProcName(self):
    dictName = self.GetDictName()
    if dictName is None:
      return None
    return 'UpdateNeedRescan' + dictName

  def GetServiceKeyName(self):
    dictName = self.GetDictName()
    if dictName is None:
      return None
    return 'Rescan' + dictName


class HttpDataObjectSource(object):
  object_source_query_func = 'GetLastHttpTime'


class AgentDataObjectSource(object):
  object_source_query_func = 'GetLastAgentTime'


class HostInfoService(HttpDataObjectSource, ServiceType):
  def __init__(self):
    ServiceType.__init__(self, 'HostInfo', core.ServiceId.HOST_REPUTATION)

  def GetDictName(self):
    return 'DictRemoteHostReputation'

  def GetCommRequestData(self,req):
    requestData = { 'url': EncodeIDNA(req.key) }
    return json.dumps(requestData,encoding="utf-8")

  def GetVerdictZone(self, verdict):
    if verdict=='good':
      return 1
    elif verdict=='bad':
      return 2
    else:
      return 0

  def GetEmptyHostReputation(self, reply):
    return dict([
      ('RemoteHostName', reply.key),
      ('IsBad', None),
      ('IsWl',  None),
      ('Category', None),
      ('Zone',  None),
      ('AptNames', None),
      ('Avp3Verdicts', None),
      ('UrlInfo', None),
      ('LastUpdateTime', GetReplyTime(reply))
    ])

  def WriteResults(self, replyProcessor, reply):
    verdictName = reply.result['verdict']
    categoryIds = reply.result['categories']
    categories = []
    for catId in categoryIds:
      categories.append(str(catId))
    categories = ' '.join(categories)
    zone = self.GetVerdictZone(verdictName)
    if zone == 1:
      isBad = False
      isWl = True
    elif zone == 2:
      isBad = True
      isWl = False
    else:
      isBad = None
      isWl = None

    record = self.GetEmptyHostReputation(reply)
    record['IsBad'] = core.DbBoolean(isBad)
    record['IsWl'] = core.DbBoolean(isWl)
    record['Category'] = categories
    record['Zone'] = zone

    if bool(set([64, 101, 122]) & set(categoryIds)):
      req = UrlInfoService.instance.CreateRequest(reply.key)
      req.hostInfo = record
      replyProcessor.info_updater.ProcessSubRequest(req)
    else:
      replyProcessor.WriteRecord(self, 'DictRemoteHostReputationIns', record.items())

  def WriteEmptyResults(self, replyProcessor, reply):
    record = self.GetEmptyHostReputation(reply)
    replyProcessor.WriteRecord(self, 'DictRemoteHostReputationIns', record.items())

HostInfoService.instance = HostInfoService()


class NewHostInfoService(ServiceTypeNew, HostInfoService):
  def __init__(self):
    ServiceType.__init__(self, 'NewHostInfo', core.ServiceId.HOST_REPUTATION)

NewHostInfoService.instance = NewHostInfoService()


class RescanHostInfoService(ServiceTypeRescan, HostInfoService):
  def __init__(self):
    ServiceType.__init__(self, 'RescanHostInfo', core.ServiceId.HOST_REPUTATION)

RescanHostInfoService.instance = RescanHostInfoService()


class UrlInfoService(HttpDataObjectSource, ServiceType):
  def __init__(self):
    ServiceType.__init__(self, 'UrlInfo', core.ServiceId.URL_INFO)

  def GetDictName(self):
    return None

  def GetCommRequestData(self,req):
    requestData = { 'url': EncodeIDNA(req.key) }
    return json.dumps(requestData,encoding="utf-8")

  def GetMasterServiceType(self):
    return HostInfoService.instance

  def WriteResults(self,replyProcessor,reply):
    aptNames = json.dumps(GetDic(reply.result, 'APTDomain') or [])

    threat = GetDic(reply.result, 'threat')
    avp3Verdicts = json.dumps([threat] if threat else [])

    self.DoWriteRecord(replyProcessor,reply,aptNames,avp3Verdicts)

  def WriteEmptyResults(self,replyProcessor,reply):
    self.DoWriteRecord(replyProcessor,reply,None,None)

  def ProcessErrorReply(self,replyProcessor,reply):
    self.DoWriteRecord(replyProcessor,reply,None,None)

  def DoWriteRecord(self,replyProcessor,reply,aptNames,avp3Verdicts):
    record = core.GetObjectAttribute(reply, 'hostInfo')
    if record is None:
      record = HostInfoService.instance.GetEmptyHostReputation(reply)

    record['AptNames'] = aptNames
    record['Avp3Verdicts'] = avp3Verdicts
    record['UrlInfo'] = json.dumps(reply.result)

    replyProcessor.WriteRecord(self,'DictRemoteHostReputationIns',record.items())

  def GetFlushLock(self):
    return GetDic(ServiceType.flush_locks, 'DictRemoteHostReputation')

UrlInfoService.instance = UrlInfoService()

def IpFromDb(ipb):
  if ipb[0:12] == ('\0'*12):
    return core.Bin2Ip(ipb[12:])
  else:
    return core.Bin2Ip(ipb)

def BinIpToDb(ipb):
  if len(ipb) == 4:
    ipb = ('\0'*12) + ipb
  return ipb

def IpToDb(ip):
  return BinIpToDb(core.Ip2Bin(ip))

def FindContactsRole(contacts, roleName):
  if contacts == None:
    return None
  try:
    for c in contacts:
      role = GetDic(c,"role")
      if role == roleName:
        return c
  except Exception:
    return None
  return None

class IpInfoService(HttpDataObjectSource, ServiceType):
  def __init__(self):
    ServiceType.__init__(self, 'IpInfo', core.ServiceId.HOST_INFO)

  def CreateRequest(self,key):
    core.Ip2Bin(key)
    return ServiceType.CreateRequest(self,key)

  def GetDictName(self):
    return 'DictRemoteHostIp'

  def GetCommRequestData(self,req):
    requestData = { 'type': 3, 'host': req.key }
    return json.dumps(requestData,encoding="utf-8")

  def CreateRequestsByQuery(self,row):
    if row[0] is None:
      logging.error('Invalid data in request to %s', self.GetDictName())
      return []

    if core.UseInetAddr:
      key = GetUtf8Str(row[0])
    else:
      key = IpFromDb(row[0])
    return [ self.CreateRequest(key) ]

  def WriteResults(self,replyProcessor,reply):
    updateTime = GetReplyTime(reply)

    if 'start_ip' in reply.result:
      rng = reply.result
      strIpFrom = GetDic(reply.result,'start_ip')
      strIpTo   = GetDic(reply.result,'end_ip')

      strNetName = GetDic(reply.result,'net_name')
      strOrgName = GetDic(reply.result,'owner')
      strCountryCode = GetDic(reply.result,'country_code')
      strCityName = GetDic(reply.result,'city')
      strDescr = GetDic(reply.result,'net_description')
    else:
      whois = GetDic(reply.result,'whois')
      rng = GetListItem(whois,0)
      strIpFrom = GetDic(rng,'start_ip')
      strIpTo   = GetDic(rng,'end_ip')

      rngNet = GetDic(rng,'net')
      rngCont = GetDic(rng,'contacts')
      rngOwn = FindContactsRole(rngCont,"owner")

      strNetName = GetDic(rngNet,'name')
      strOrgName = GetDic(rngOwn,'name')
      strCountryCode = GetDic(rngNet,'country')
      strCityName = GetDic(rngOwn,'city')
      strDescr = SerStr(GetDic(rngNet,'descr'))

    if isinstance(strIpFrom,dict):
      startIpB64 = strIpFrom['$binary']
      endIpB64 = strIpFrom['$binary']
      startIpBin = base64.b64decode(startIpB64)
      endIpBin = base64.b64decode(endIpB64)
      if core.UseInetAddr:
        dbIpFrom = core.Bin2Ip(startIpBin)
        dbIpTo   = core.Bin2Ip(endIpBin)
        dbIpFmt  = 0
      else:
        dbIpFrom = core.Bin2Hex(BinIpToDb(startIpBin))
        dbIpTo   = core.Bin2Hex(BinIpToDb(endIpBin))
        dbIpFmt  = core.DbOpt.StrBin
    else:
      if core.UseInetAddr:
        dbIpFrom = strIpFrom
        dbIpTo   = strIpTo
        dbIpFmt  = 0
      else:
        dbIpFrom = core.Bin2Hex(IpToDb(strIpFrom))
        dbIpTo   = core.Bin2Hex(IpToDb(strIpTo))
        dbIpFmt  = core.DbOpt.StrBin

    record = [
      ('FromIp',  dbIpFrom, dbIpFmt),
      ('ToIp',    dbIpTo,   dbIpFmt),
      ('NetName', strNetName),
      ('OrgName', strOrgName),
      ('Country', strCountryCode),
      ('City',    strCityName),
      ('Descr',   strDescr),
      ('KSNReply', reply.replyJson),
      ('LastUpdateTime', updateTime)
    ]
    replyProcessor.WriteRecord(self,'DictRemoteHostIpIns',record)

  def WriteEmptyResults(self,replyProcessor,reply):
    updateTime = GetReplyTime(reply)

    if core.UseInetAddr:
      strIp   = reply.key
      fmtMode = 0
    else:
      strIp   = core.Bin2Hex(IpToDb(reply.key))
      fmtMode = core.DbOpt.StrBin

    record = [
      ('FromIp',  strIp, fmtMode),
      ('ToIp',    strIp, fmtMode),
      ('NetName', None),
      ('OrgName', None),
      ('Country', None),
      ('City',    None),
      ('Descr',   None),
      ('KSNReply', None),
      ('LastUpdateTime', updateTime)
    ]
    replyProcessor.WriteRecord(self,'DictRemoteHostIpIns',record)

IpInfoService.instance = IpInfoService()


class NewIpInfoService(ServiceTypeNew, IpInfoService):
  def __init__(self):
    ServiceType.__init__(self, 'NewIpInfo', core.ServiceId.HOST_INFO)

NewIpInfoService.instance = NewIpInfoService()


class DomainTopService(HttpDataObjectSource, ServiceType):
  def __init__(self):
    ServiceType.__init__(self, 'DomainTop', core.ServiceId.HOST_INFO)

  def CreateRequest(self,key):
    req = ServiceType.CreateRequest(self,key)
    req.isIpAddress = core.IsIpAddress(key)
    return req

  def GetDictName(self):
    return 'DictDomainShortTop'

  def GetCommRequestData(self,req):
    if req.isIpAddress:
      requestData = { 'type': 5, 'host': req.key }
    else:
      requestData = { 'type': 2, 'host': EncodeIDNA(req.key) }
    return json.dumps(requestData,encoding="utf-8")

  def WriteResults(self,replyProcessor,reply):
    rank = GetRank(GetDic(reply.result, 'SLD'))
    if rank == None:
      rank = GetRank(GetDic(reply.result, 'TLD'))
    if rank == None and reply.isIpAddress:
      rank = GetRankIp(reply.result)
    if rank == None:
      rank = Rank()

    record = [
      ('DomainShortName', reply.key),
      ('KsnRankMonth', rank.month.position),
      ('KsnRankWeek',  rank.week.position),
      ('KsnRankDay',   rank.day.position),
      ('KsnPeakRankDay', rank.day.peak_position),
      ('KsnUsersCountMonth', rank.month.popularity),
      ('KsnUsersCountWeek',  rank.week.popularity),
      ('KsnUsersCountDay',   rank.day.popularity),
      ('KsnPeakUsersCountDay', rank.day.peak_popularity),
      ('LastUpdateTime',  GetReplyTime(reply))
    ]
    replyProcessor.WriteRecord(self,'DictDomainShortTopIns',record)

  def WriteEmptyResults(self,replyProcessor,reply):
    record = [
      ('DomainShortName', reply.key),
      ('KsnRankMonth', None),
      ('KsnRankWeek',  None),
      ('KsnRankDay',   None),
      ('KsnPeakRankDay', None),
      ('KsnUsersCountMonth', None),
      ('KsnUsersCountWeek',  None),
      ('KsnUsersCountDay',   None),
      ('KsnPeakUsersCountDay', None),
      ('LastUpdateTime',  GetReplyTime(reply))
    ]
    replyProcessor.WriteRecord(self,'DictDomainShortTopIns',record)

DomainTopService.instance = DomainTopService()


class NewDomainTopService(ServiceTypeNew, DomainTopService):
  def __init__(self):
    ServiceType.__init__(self, 'NewDomainTop', core.ServiceId.HOST_INFO)

NewDomainTopService.instance = NewDomainTopService()


class RescanDomainTopService(ServiceTypeRescan, DomainTopService):
  def __init__(self):
    ServiceType.__init__(self, 'RescanDomainTop', core.ServiceId.HOST_INFO)

RescanDomainTopService.instance = RescanDomainTopService()


class HostTopService(HttpDataObjectSource, ServiceType):
  def __init__(self):
    ServiceType.__init__(self, 'HostTop', core.ServiceId.HOST_INFO)

  def CreateRequest(self,key):
    req = ServiceType.CreateRequest(self,key)
    req.isIpAddress = core.IsIpAddress(key)
    return req

  def GetDictName(self):
    return 'DictRemoteHostTop'

  def GetCommRequestData(self,req):
    if req.isIpAddress:
      requestData = { 'type': 5, 'host': req.key }
    else:
      requestData = { 'type': 2, 'host': EncodeIDNA(req.key) }
    return json.dumps(requestData,encoding="utf-8")

  def WriteResults(self,replyProcessor,reply):
    rank = GetRank(GetDic(reply.result, 'TLD'))
    if rank == None:
      rank = GetRank(GetDic(reply.result, 'SLD'))
    if rank == None and reply.isIpAddress:
      rank = GetRankIp(reply.result)
    if rank == None:
      rank = Rank()

    record = [
      ('RemoteHostName', reply.key),
      ('KsnRankMonth', rank.month.position),
      ('KsnRankWeek',  rank.week.position),
      ('KsnRankDay',   rank.day.position),
      ('KsnPeakRankDay', rank.day.peak_position),
      ('KsnUsersCountMonth', rank.month.popularity),
      ('KsnUsersCountWeek',  rank.week.popularity),
      ('KsnUsersCountDay',   rank.day.popularity),
      ('KsnPeakUsersCountDay', rank.day.peak_popularity),
      ('LastUpdateTime',  GetReplyTime(reply))
    ]
    replyProcessor.WriteRecord(self,'DictRemoteHostTopIns',record)

  def WriteEmptyResults(self,replyProcessor,reply):
    record = [
      ('RemoteHostName', reply.key),
      ('KsnRankMonth', None),
      ('KsnRankWeek',  None),
      ('KsnRankDay',   None),
      ('KsnPeakRankDay', None),
      ('KsnUsersCountMonth', None),
      ('KsnUsersCountWeek',  None),
      ('KsnUsersCountDay',   None),
      ('KsnPeakUsersCountDay', None),
      ('LastUpdateTime',  GetReplyTime(reply))
    ]
    replyProcessor.WriteRecord(self,'DictRemoteHostTopIns',record)

HostTopService.instance = HostTopService()


class NewHostTopService(ServiceTypeNew, HostTopService):
  def __init__(self):
    ServiceType.__init__(self, 'NewHostTop', core.ServiceId.HOST_INFO)

NewHostTopService.instance = NewHostTopService()


class RescanHostTopService(ServiceTypeRescan, HostTopService):
  def __init__(self):
    ServiceType.__init__(self, 'RescanHostTop', core.ServiceId.HOST_INFO)

RescanHostTopService.instance = RescanHostTopService()


class DomainInfoService(HttpDataObjectSource, ServiceType):
  def __init__(self):
    ServiceType.__init__(self, 'DomainInfo', core.ServiceId.HOST_INFO)

  def GetDictName(self):
    return 'DictDomainShortWhois'

  def GetCommRequestData(self,req):
    requestData = { 'type': 1, 'host': EncodeIDNA(req.key) }
    return json.dumps(requestData,encoding="utf-8")

  def WriteResults(self,replyProcessor,reply):

    contacts = GetDic(reply.result,'contacts')
    ownerContacts = FindContactsRole(contacts,'registrant')
    ownerName = GetDic(ownerContacts, 'organization')
    if ownerName == None:
      ownerName = GetDic(reply.result,'registrant_organization')

    registrar = GetDic(reply.result,'registrar')
    registrarName = GetDic(registrar,'name')
    if registrarName == None:
      registrarName = GetDic(reply.result,'registrar_name')

    record = [
      ('DomainShortName',reply.key),
      ('CreationDate',   core.TimeFromKsnToSql(GetDic(reply.result,'created'))),
      ('ExpiredDate',    core.TimeFromKsnToSql(GetDic(reply.result,'expires'))),
      ('UpdatedDate',    core.TimeFromKsnToSql(GetDic(reply.result,'updated'))),
      ('RegistrarName',  registrarName),
      ('OwnerName',      ownerName),
      ('OwnerIsOrg',     core.DbBoolean(GetDic(reply.result,'owner_is_org'))),
      ('KSNReply',       reply.replyJson),
      ('LastUpdateTime', GetReplyTime(reply))
    ]
    replyProcessor.WriteRecord(self,'DictDomainShortWhoisIns',record)

  def WriteEmptyResults(self,replyProcessor,reply):
    record = [
      ('DomainShortName', reply.key),
      ('CreationDate',  None),
      ('ExpiredDate',   None),
      ('UpdatedDate',   None),
      ('RegistrarName', None),
      ('OwnerName',     None),
      ('OwnerIsOrg',    None),
      ('KSNReply',      None),
      ('LastUpdateTime',  GetReplyTime(reply))
    ]
    replyProcessor.WriteRecord(self,'DictDomainShortWhoisIns',record)

DomainInfoService.instance = DomainInfoService()


class NewDomainInfoService(ServiceTypeNew, DomainInfoService):
  def __init__(self):
    ServiceType.__init__(self, 'NewDomainInfo', core.ServiceId.HOST_INFO)

NewDomainInfoService.instance = NewDomainInfoService()


class FileNameService(AgentDataObjectSource, ServiceType):
  HASH_TYPE = 'nn'

  def __init__(self):
    ServiceType.__init__(self, 'FileName', core.ServiceId.HASH_INFO)

  def CreateRequest(self, key):
    normalized_key = self.HASH_TYPE + '\0' + PathStrDefiner.derandomize_path(key)
    req = core.Request(self, normalized_key)
    req.file_name = key
    return req

  def GetDictName(self):
    return 'DictFileName'

  def GetCommRequestData(self, req):
    md5 = GetNameHashStr(req.key)
    request_data = {'md5': md5, 'metadata': req.key}
    return json.dumps(request_data, encoding='utf-8')

  def WriteResults(self, replyProcessor, reply):
    popularity = None
    if CheckReplyHashType(reply, self.HASH_TYPE):
      popularity = reply.result['popularity']

    record = [
      ('FileName', reply.file_name),
      ('UsersCount', popularity),
      ('LastUpdateTime', GetReplyTime(reply))
    ]
    replyProcessor.WriteRecord(self, 'DictFileNameIns', record)

  def WriteEmptyResults(self, replyProcessor, reply):
    reply.result = {'type': self.HASH_TYPE, 'popularity': None}
    self.WriteResults(replyProcessor, reply)

FileNameService.instance = FileNameService()


class NewFileNameService(ServiceTypeNew, FileNameService):
  def __init__(self):
    ServiceType.__init__(self, 'NewFileName', core.ServiceId.HASH_INFO)

NewFileNameService.instance = NewFileNameService()


class FilePathAssociationsService(ServiceType):
  HASH_TYPE = 'np2'

  def __init__(self):
    ServiceType.__init__(self, 'FilePathAssociations', core.ServiceId.HASH_INFO)

  def CreateRequest(self, key):
    normalized_key = self.HASH_TYPE + '\0' + PathStrDefiner.derandomize_path(key)
    req = core.Request(self, normalized_key)
    req.file_path = key
    return req

  def GetDictName(self):
    return None

  def GetCommRequestData(self, req):
    md5 = GetNameHashStr(req.key)
    request_data = {'md5': md5, 'metadata': req.key}
    return json.dumps(request_data, encoding='utf-8')

  def GetMasterServiceType(self):
    return FilePathService.instance

  def WriteResults(self, replyProcessor, reply):
    file_path_associations = None
    if CheckReplyHashType(reply, self.HASH_TYPE):
      file_path_associations = reply.result
    self.DoWriteRecord(replyProcessor, reply, file_path_associations)

  def WriteEmptyResults(self, reply_processor, reply):
    self.DoWriteRecord(reply_processor, reply, None)

  def DoWriteRecord(self, reply_processor, reply, file_path_associations):
    users_count = getattr(reply, 'users_count', None)

    if GetDic(file_path_associations, 'compressed'):
      try:
        domains_array_base64 = GetDic(file_path_associations, 'domains_array') or ''
        domains_array_raw = base64.b64decode(domains_array_base64)

        with gzip.GzipFile(fileobj=StringIO.StringIO(domains_array_raw)) as in_gzip:
          domains_array_string = '{' + in_gzip.read().decode('utf-16le') + '}'
      except:
        logging.warning('FilePathAssociationsService: Unable to decode domains_array')
        domains_array_string = None
    else:
      domains_array = GetDic(file_path_associations, 'domains_array') or {}
      domains_array_string = json.dumps(domains_array)

    record = [
      ('FilePathNorm', reply.file_path),
      ('UsersCount', users_count),
      ('KSNReply', reply.replyJson),
      ('LastUpdateTime', GetReplyTime(reply)),
      ('PathUserCount', GetDic(file_path_associations, 'path_user_count')),
      ('SCUserCount', GetDic(file_path_associations, 'SC_user_count')),
      ('SCNotLocalUserCount', GetDic(file_path_associations, 'SC_not_local_user_count')),
      ('DomainCnt', GetDic(file_path_associations, 'domain_cnt')),
      ('DomainCntPop', GetDic(file_path_associations, 'domain_cnt_pop')),
      ('mindomainusers', GetDic(file_path_associations, 'mindomainusers')),
      ('maxdomainusers', GetDic(file_path_associations, 'maxdomainusers')),
      ('PublishedDomains', GetDic(file_path_associations, 'published_domains')),
      ('DomainArray', domains_array_string)
    ]
    reply_processor.WriteRecord(self, 'DictFilePathNormIns', record)

  def GetFlushLock(self):
    return GetDic(ServiceType.flush_locks, 'DictFilePathNorm')

FilePathAssociationsService.instance = FilePathAssociationsService()


class FilePathService(AgentDataObjectSource, ServiceType):
  HASH_TYPE = 'np'

  def __init__(self):
    ServiceType.__init__(self, 'FilePath', core.ServiceId.HASH_INFO)

  def CreateRequest(self, key):
    normalized_key = self.HASH_TYPE + '\0' + PathStrDefiner.derandomize_path(key)
    req = core.Request(self, normalized_key)
    req.file_path = key
    return req

  def GetDictName(self):
    return 'DictFilePathNorm'

  def GetCommRequestData(self, req):
    md5 = GetNameHashStr(req.key)
    request_data = {'md5': md5, 'metadata': req.key}
    return json.dumps(request_data, encoding='utf-8')

  def WriteResults(self, reply_processor, reply):
    popularity = None
    if CheckReplyHashType(reply, self.HASH_TYPE):
      popularity = reply.result['popularity']

    req = FilePathAssociationsService.instance.CreateRequest(reply.file_path)
    req.users_count = popularity
    reply_processor.info_updater.ProcessSubRequest(req)

  def WriteEmptyResults(self, reply_processor, reply):
    req = FilePathAssociationsService.instance.CreateRequest(reply.file_path)
    req.users_count = None
    reply_processor.info_updater.ProcessSubRequest(req)

FilePathService.instance = FilePathService()


class NewFilePathService(ServiceTypeNew, FilePathService):
  def __init__(self):
    ServiceType.__init__(self, 'NewFilePath', core.ServiceId.HASH_INFO)

NewFilePathService.instance = NewFilePathService()


class FilePathShortService(AgentDataObjectSource, ServiceType):
  HASH_TYPE = 'sp'

  def __init__(self):
    ServiceType.__init__(self, 'FilePathShort', core.ServiceId.HASH_INFO)

  def CreateRequest(self, key):
    normalized_key = self.HASH_TYPE + '\0' + PathStrDefiner.derandomize_path(key)
    req = core.Request(self, normalized_key)
    req.file_path_short = key[:-1] if key.endswith('\\') else key
    return req

  def GetDictName(self):
    return 'DictFilePathShortNorm'

  def GetCommRequestData(self, req):
    md5 = GetNameHashStr(req.key)
    request_data = {'md5': md5, 'metadata': req.key}
    return json.dumps(request_data, encoding='utf-8')

  def WriteResults(self, replyProcessor, reply):
    popularity = None
    if CheckReplyHashType(reply, self.HASH_TYPE):
      popularity = reply.result['popularity']

    record = [
      ('FilePathShortNorm', reply.file_path_short),
      ('UsersCount', popularity),
      ('LastUpdateTime', GetReplyTime(reply))
    ]
    replyProcessor.WriteRecord(self,'DictFilePathShortNormIns',record)

  def WriteEmptyResults(self,replyProcessor,reply):
    reply.result = {'type' : self.HASH_TYPE, 'popularity' : None}
    self.WriteResults(replyProcessor, reply)

FilePathShortService.instance = FilePathShortService()


class NewFilePathShortService(ServiceTypeNew, FilePathShortService):
  def __init__(self):
    ServiceType.__init__(self, 'NewFilePathShort', core.ServiceId.HASH_INFO)

NewFilePathShortService.instance = NewFilePathShortService()


class FilePathMd5Service(AgentDataObjectSource, ServiceType):
  HASH_TYPE = 'nph'

  def __init__(self):
    ServiceType.__init__(self, 'FilePathMd5', core.ServiceId.HASH_INFO)

  def GetDictName(self):
    return 'DictFileAndPathNorm'

  def CreateRequest(self, key):
    sep_idx = key.rindex('\\')

    file_path = key[:sep_idx]
    file_md5 = key[sep_idx+1:]

    normalized_key = '%s\\%s' % (PathStrDefiner.derandomize_path(file_path), file_md5)
    normalized_key = self.HASH_TYPE + '\0' + normalized_key

    req = core.Request(self, normalized_key)
    req.file_path = file_path
    req.file_md5 = file_md5

    return req

  def CreateRequestsByQuery(self, row):
    if (row[0] is None) or (row[1] is None):
      logging.error('Invalid data in request to %s', self.GetDictName())
      return []

    key = '%s\\%s' % (row[0], core.HashFromDb(row[1]))
    return [ self.CreateRequest(key) ]

  def GetCommRequestData(self, req):
    md5 = GetNameHashStr(req.key)
    requestData = { 'md5': md5, 'metadata': req.key }
    return json.dumps(requestData,encoding="utf-8")

  def WriteResults(self, replyProcessor, reply):
    popularity = None
    if CheckReplyHashType(reply, self.HASH_TYPE):
      popularity = reply.result['popularity']

    record = [
      ('FilePathNorm', reply.file_path),
      ('FileMd5',      reply.file_md5, core.DbOpt.HashBin),
      ('UsersCount',   popularity),
      ('LastUpdateTime', GetReplyTime(reply))
    ]
    replyProcessor.WriteRecord(self, 'DictFileAndPathNormIns', record)

  def WriteEmptyResults(self, replyProcessor, reply):
    reply.result = {'type': self.HASH_TYPE, 'popularity': None}
    self.WriteResults(replyProcessor, reply)

FilePathMd5Service.instance = FilePathMd5Service()


class NewFilePathMd5Service(ServiceTypeNew, FilePathMd5Service):
  def __init__(self):
    ServiceType.__init__(self, 'NewFilePathMd5', core.ServiceId.HASH_INFO)

NewFilePathMd5Service.instance = NewFilePathMd5Service()


class FileNameMd5Service(AgentDataObjectSource, ServiceType):
  HASH_TYPE = 'nfn'

  def __init__(self):
    ServiceType.__init__(self, 'FileNameMd5', core.ServiceId.HASH_INFO)

  def GetDictName(self):
    return 'DictFileAndNameNorm'

  def CreateRequest(self, key):
    sep_idx = key.rindex('\\')

    file_name = key[:sep_idx]
    file_md5 = key[sep_idx+1:]

    normalized_key = '%s\\%s' % (PathStrDefiner.derandomize_path(file_name), file_md5)
    normalized_key = self.HASH_TYPE + '\0' + normalized_key

    req = core.Request(self, normalized_key)
    req.file_name = file_name
    req.file_md5 = file_md5

    return req

  def CreateRequestsByQuery(self, row):
    if (row[0] is None) or (row[1] is None):
      logging.error('Invalid data in request to %s', self.GetDictName())
      return []

    key = '%s\\%s' % (row[0], core.HashFromDb(row[1]))
    return [ self.CreateRequest(key) ]

  def GetCommRequestData(self, req):
    md5 = GetNameHashStr(req.key)
    requestData = { 'md5': md5, 'metadata': req.key }
    return json.dumps(requestData,encoding="utf-8")

  def WriteResults(self, replyProcessor, reply):
    popularity = None
    if CheckReplyHashType(reply, self.HASH_TYPE):
      popularity = reply.result['popularity']

    record = [
      ('FileName',   reply.file_name),
      ('FileMd5',      reply.file_md5, core.DbOpt.HashBin),
      ('UsersCount',   popularity),
      ('LastUpdateTime', GetReplyTime(reply))
    ]
    replyProcessor.WriteRecord(self, 'DictFileAndNameNormIns', record)

  def WriteEmptyResults(self, replyProcessor, reply):
    reply.result = {'type': self.HASH_TYPE, 'popularity': None}
    self.WriteResults(replyProcessor, reply)

FileNameMd5Service.instance = FileNameMd5Service()


class NewFileNameMd5Service(ServiceTypeNew, FileNameMd5Service):
  def __init__(self):
    ServiceType.__init__(self, 'NewFileNameMd5', core.ServiceId.HASH_INFO)

NewFileNameMd5Service.instance = NewFileNameMd5Service()


class VhsVerdictService(ServiceType):
  HASH_TYPE = 'vh'

  def __init__(self):
    ServiceType.__init__(self, 'VhsVerdict', core.ServiceId.HASH_INFO)

  def GetDictName(self):
    return None

  def CreateRequest(self, key):
    req = core.Request(self, self.HASH_TYPE + '\0' + key.upper())
    req.file_vhs = key
    return req

  def GetCommRequestData(self, req):
    md5 = GetNameHashStr(req.key)
    requestData = {'md5': md5, 'metadata': req.key}
    return json.dumps(requestData, encoding='utf-8')

  def GetMasterServiceType(self):
    return FileVhsService.instance

  def WriteResults(self, replyProcessor, reply):
    hack_tool_verdicts = None
    if CheckReplyHashType(reply, self.HASH_TYPE):
      hack_tool_verdicts = json.dumps(GetDic(reply.result, 'records'))

    self.DoWriteRecord(replyProcessor, reply, hack_tool_verdicts)

  def WriteEmptyResults(self, replyProcessor, reply):
    self.DoWriteRecord(replyProcessor, reply, None)

  def DoWriteRecord(self, replyProcessor, reply, hack_tool_verdicts):
    record = core.GetObjectAttribute(reply, 'vhs_info')
    if not record:
      record = FileVhsService.instance.GetEmptyVhsInfo(reply)
      record['FileVHS'] = (reply.file_vhs, core.DbOpt.HashBin)

    record['HackToolVerdictes'] = hack_tool_verdicts

    items = [sum((p if type(p) is tuple else (p,) for p in r), ()) for r in record.items()]
    replyProcessor.WriteRecord(self, 'DictVhsIns', items)

  def GetFlushLock(self):
    return GetDic(ServiceType.flush_locks, 'DictVhs')

VhsVerdictService.instance = VhsVerdictService()


class FileVhsService(AgentDataObjectSource, ServiceType):
  def __init__(self):
    ServiceType.__init__(self, 'FileVhs', core.ServiceId.HASH_INFO)

  def GetDictName(self):
    return 'DictVhs'

  def CreateRequestsByQuery(self,row):
    if row[0] is None:
      logging.error('Invalid data in request to %s', self.GetDictName())
      return []

    hashes = core.HashFromDb(row[0])
    requests = []
    while len(hashes) > 0:
      h = hashes[0:32]
      requests.append(self.CreateRequest(h))
      hashes = hashes[32:]
    return requests

  def GetCommRequestData(self,req):
    requestData = { 'md5': req.key, 'metadata': req.key }
    return json.dumps(requestData,encoding="utf-8")

  def GetEmptyVhsInfo(self, reply):
    return dict([
      ('FileVHS', (reply.key, core.DbOpt.HashBin)),
      ('FirstTime',  None),
      ('LastTime',   None),
      ('UsersCount', None),
      ('FilesCount', None),
      ('GoodFilesCount', None),
      ('BadFilesCount',  None),
      ('KSNReply', None),
      ('HackToolVerdictes', None),
      ('LastUpdateTime', GetReplyTime(reply))
    ])

  def WriteResults(self, replyProcessor, reply):
    if CheckReplyHashType(reply, '12'):
      req = VhsVerdictService.instance.CreateRequest(reply.key)

      req.vhs_info = self.GetEmptyVhsInfo(reply)
      req.vhs_info['FirstTime'] = core.TimeFromKsnToSql(GetDic(reply.result, 'first_date'))
      req.vhs_info['LastTime'] = core.TimeFromKsnToSql(GetDic(reply.result, 'last_date'))
      req.vhs_info['UsersCount'] = GetDic(reply.result, 'max_daily_users_count')
      req.vhs_info['FilesCount'] = GetDic(reply.result, 'files_count')
      req.vhs_info['GoodFilesCount'] = GetDic(reply.result, 'goodFilesCount')
      req.vhs_info['BadFilesCount'] = GetDic(reply.result, 'badFilesCount')
      req.vhs_info['KSNReply'] = reply.replyJson

      replyProcessor.info_updater.ProcessSubRequest(req)
    else:
      self.WriteEmptyResults(replyProcessor, reply)

  def WriteEmptyResults(self, replyProcessor, reply):
    req = VhsVerdictService.instance.CreateRequest(reply.key)
    replyProcessor.info_updater.ProcessSubRequest(req)

FileVhsService.instance = FileVhsService()


class NewFileVhsService(ServiceTypeNew, FileVhsService):
  def __init__(self):
    ServiceType.__init__(self, 'NewFileVhs', core.ServiceId.HASH_INFO)

NewFileVhsService.instance = NewFileVhsService()


class HipsFileInfo(object):
  def __init__(self,result):
    self.wocFirstTime = None
    self.wocLastTime = None
    self.wocUsersCount = None
    self.mixUsersCount = None
    self.hipsFileGroup = None
    self.hipsProductName = None
    self.hipsVendorName = None

    if result != None:
      hipsInfo = result['HipsPolicy']
      hipsInfoEx = result['HipsPolicyEx']
      wocData = result['WocData']
      fileDesc = hipsInfoEx['FileDescription']
      self.wocFirstTime = core.TimeFromKsnToSql(wocData['FirstRequestTime'])
      self.wocUsersCount = wocData['UsersCount']
      self.hipsFileGroup = hipsInfo['HipsGroup']
      self.hipsProductName = fileDesc['ProductName'].strip()
      self.hipsVendorName = fileDesc['VendorName'].strip()


class FileAssociationsService(ServiceType):
  HASH_TYPE = 'f2'

  def __init__(self):
    ServiceType.__init__(self, 'FileAssociations', core.ServiceId.HASH_INFO)

  def GetDictName(self):
    return None

  def CreateRequest(self, key):
    req = core.Request(self, self.HASH_TYPE + '\0' + key.upper())
    req.file_md5 = key
    return req

  def GetCommRequestData(self, req):
    md5 = GetNameHashStr(req.key)
    requestData = {'md5': md5, 'metadata': req.key}
    return json.dumps(requestData, encoding='utf-8')

  def GetMasterServiceType(self):
    return FileInfoService.instance

  def WriteResults(self, replyProcessor, reply):
    file_associations = None
    if CheckReplyHashType(reply, self.HASH_TYPE):
      file_associations = reply.result
    self.DoWriteRecord(replyProcessor, reply, file_associations)

  def WriteEmptyResults(self, reply_processor, reply):
    self.DoWriteRecord(reply_processor, reply, None)

  def DoWriteRecord(self, reply_processor, reply, file_associations):
    hips_info = getattr(reply, 'hipsResult', None)
    if hips_info is None:
      hips_info = HipsFileInfo(None)

    mix_users_count = getattr(reply, 'mixUsersCount', None)

    if GetDic(file_associations, 'compressed'):
      try:
        domains_array_base64 = GetDic(file_associations, 'domains_array') or ''
        domains_array_raw = base64.b64decode(domains_array_base64)

        with gzip.GzipFile(fileobj=StringIO.StringIO(domains_array_raw)) as in_gzip:
          domains_array_string = '{' + in_gzip.read().decode('utf-16le') + '}'
      except:
        logging.warning('FileAssociationsService: Unable to decode domains_array')
        domains_array_string = None
    else:
      domains_array = GetDic(file_associations, 'domains_array') or {}
      domains_array_string = json.dumps(domains_array)

    record = [
      ('FileMd5', reply.file_md5, core.DbOpt.HashBin),
      ('WocFirstTime', hips_info.wocFirstTime),
      ('WocLastTime', hips_info.wocLastTime),
      ('WocUsersCount', hips_info.wocUsersCount),
      ('MixUsersCount', mix_users_count),
      ('HipsFileGroup', hips_info.hipsFileGroup),
      ('HipsProductName', hips_info.hipsProductName),
      ('HipsVendorName', hips_info.hipsVendorName),
      ('KSNReply', reply.replyJson),
      ('LastUpdateTime', GetReplyTime(reply)),
      ('FileUserCount', GetDic(file_associations, 'file_user_count')),
      ('FilePathNorm', GetDic(file_associations, 'norm_path')),
      ('PathUserCount', GetDic(file_associations, 'path_user_count')),
      ('SCUserCount', GetDic(file_associations, 'SC_user_count')),
      ('SCNotLocalUserCount', GetDic(file_associations, 'SC_not_local_user_count')),
      ('DomainCnt', GetDic(file_associations, 'domain_cnt')),
      ('DomainCntPop', GetDic(file_associations, 'domain_cnt_pop')),
      ('mindomainusers', GetDic(file_associations, 'mindomainusers')),
      ('maxdomainusers', GetDic(file_associations, 'maxdomainusers')),
      ('PublishedDomains', GetDic(file_associations, 'published_domains')),
      ('DomainArray', domains_array_string)
    ]
    reply_processor.WriteRecord(self, 'DictFileIns', record)

  def GetFlushLock(self):
    return GetDic(ServiceType.flush_locks, 'DictFile')

FileAssociationsService.instance = FileAssociationsService()


class FileContentService(ServiceType):
  HASH_TYPE = 'f'

  def __init__(self):
    ServiceType.__init__(self, 'FileContent', core.ServiceId.HASH_INFO)

  def GetDictName(self):
    return None

  def GetCommRequestData(self, req):
    request_data = {'md5': req.key, 'metadata': req.key}
    return json.dumps(request_data, encoding='utf-8')

  def GetMasterServiceType(self):
    return FileInfoService.instance

  def WriteResults(self, reply_processor, reply):
    popularity = None
    if CheckReplyHashType(reply, self.HASH_TYPE):
      popularity = reply.result['popularity']

    req = FileAssociationsService.instance.CreateRequest(reply.key)
    req.hipsResult = reply.hipsResult
    req.mixUsersCount = popularity
    reply_processor.info_updater.ProcessSubRequest(req)

  def WriteEmptyResults(self, reply_processor, reply):
    req = FileAssociationsService.instance.CreateRequest(reply.key)
    req.hipsResult = reply.hipsResult
    req.mixUsersCount = None
    reply_processor.info_updater.ProcessSubRequest(req)

FileContentService.instance = FileContentService()


class FileInfoService(AgentDataObjectSource, ServiceType):
  def __init__(self):
    ServiceType.__init__(self, 'FileInfo', core.ServiceId.FILE_REPUTATION)

  def GetDictName(self):
    return 'DictFile'

  def GetCommRequestData(self,req):
    requestData = { 'md5': req.key }
    return json.dumps(requestData,encoding="utf-8")

  def CreateRequestsByQuery(self,row):
    if row[0] is None:
      logging.error('Invalid data in request to %s', self.GetDictName())
      return []
    return [ self.CreateRequest(core.HashFromDb(row[0])) ]

  def WriteResults(self,replyProcessor,reply):
    req = FileContentService.instance.CreateRequest(reply.key)
    req.hipsResult = HipsFileInfo(reply.result)
    replyProcessor.info_updater.ProcessSubRequest(req)

  def WriteEmptyResults(self,replyProcessor,reply):
    req = FileContentService.instance.CreateRequest(reply.key)
    req.hipsResult = None
    replyProcessor.info_updater.ProcessSubRequest(req)

FileInfoService.instance = FileInfoService()


class NewFileInfoService(ServiceTypeNew, FileInfoService):
  def __init__(self):
    ServiceType.__init__(self, 'NewFileInfo', core.ServiceId.FILE_REPUTATION)

NewFileInfoService.instance = NewFileInfoService()


class RulesStateService(ServiceType):
  def __init__(self):
    ServiceType.__init__(self, 'RulesState', core.ServiceId.HASH_INFO)

  def GetDictName(self):
    return 'DictRuleState'

  def CreateRequest(self, key):
    if key:
      req = core.Request(self, key + '\0' + 'RuleKey')
    else:
      req = core.Request(self, 'RuleKey')
    req.installation_id = key
    return req

  def GetCommRequestData(self, req):
    md5 = core.Bin2Hex(hashlib.md5(req.key).digest())
    requestData = {'md5': md5, 'metadata': req.key}
    return json.dumps(requestData, encoding='utf-8')

  def WriteResults(self, reply_processor, reply):
    for rule_name, rule_states in reply.result.iteritems():
      for rule_version, rule_state in rule_states.iteritems():
        record = [('RuleName', rule_name),
                  ('RuleVersion', rule_version),
                  ('State', rule_state),
                  ('LastUpdateTime', GetReplyTime(reply))]
        reply_processor.WriteRecord(self, 'DictRuleStateIns', record)

  def WriteEmptyResults(self, reply_processor, reply):
    if reply.installation_id:
      logging.info('No detector rules for user ID=%s', reply.installation_id)
      req = RulesStateService.instance.CreateRequest('')
      reply_processor.info_updater.ProcessSubRequest(req)
    else:
      logging.warning('No detector rules in KSN hash service')

RulesStateService.instance = RulesStateService()


ServiceTypes = {}
ServiceTypeNames = {}

def RegisterServiceType(alias,service):
  svc = service.instance
  ServiceTypes[svc.name] = svc
  ServiceTypeNames[svc.name] = svc
  if alias != None:
    ServiceTypeNames[alias] = svc


RegisterServiceType('file_info',               FileInfoService)
RegisterServiceType('domain_info',             DomainInfoService)
RegisterServiceType('domain_top',              DomainTopService)
RegisterServiceType('host_info',               HostInfoService)
RegisterServiceType('url_info',                UrlInfoService)
RegisterServiceType('host_top',                HostTopService)
RegisterServiceType('ip_info',                 IpInfoService)
RegisterServiceType('file_name',               FileNameService)
RegisterServiceType('file_path',               FilePathService)
RegisterServiceType('file_path_short',         FilePathShortService)
RegisterServiceType('file_path_associations',  FilePathAssociationsService)
RegisterServiceType('file_pathmd5',            FilePathMd5Service)
RegisterServiceType('file_namemd5',            FileNameMd5Service)
RegisterServiceType('file_content',            FileContentService)
RegisterServiceType('file_associations',       FileAssociationsService)
RegisterServiceType('file_vhs',                FileVhsService)
RegisterServiceType('vhs_verdict',             VhsVerdictService)
RegisterServiceType('rules_state',             RulesStateService)

RegisterServiceType('new_file_info',       NewFileInfoService)
RegisterServiceType('new_domain_info',     NewDomainInfoService)
RegisterServiceType('new_domain_top',      NewDomainTopService)
RegisterServiceType('new_host_info',       NewHostInfoService)
RegisterServiceType('new_host_top',        NewHostTopService)
RegisterServiceType('new_ip_info',         NewIpInfoService)
RegisterServiceType('new_file_name',       NewFileNameService)
RegisterServiceType('new_file_path',       NewFilePathService)
RegisterServiceType('new_file_path_short', NewFilePathShortService)
RegisterServiceType('new_file_pathmd5',    NewFilePathMd5Service)
RegisterServiceType('new_file_namemd5',    NewFileNameMd5Service)
RegisterServiceType('new_file_vhs',        NewFileVhsService)

RegisterServiceType('rescan_domain_top', RescanDomainTopService)
RegisterServiceType('rescan_host_info',  RescanHostInfoService)
RegisterServiceType('rescan_host_top',   RescanHostTopService)


def GetServiceType(name):
  return ServiceTypeNames[name]


class ReplyProcessor(object):
  def __init__(self,info_updater,name,reply_queue):
    self.info_updater = info_updater
    self.name = name
    self._dbConnection = None
    self.reply_queue = reply_queue
    self._thread = None

  def Start(self):
    self._thread = threading.Thread(name='ReplyProcessor:%s' % (self.name,), target=self.ProcessReplies)
    self._thread.daemon = True
    self._thread.start()

  def Stop(self):
    if (self._thread != None):
      self._thread.join()
      self._thread = None

  def ProcessReplies(self):
    try:
      logging.info('ReplyProcessor (%s): thread started', self.name)

      core.UpdateActivity()

      while 1:
        try:
          core.UpdateActivity()
          reply = self.reply_queue.Get()
          core.UpdateActivity()
        except EOFError:
          logging.info('ReplyProcessor (%s): no more replies, finishing...', self.name)
          break
        except Exception as e:
          LogError('ReplyProcessor (%s): error getting reply: %s' % (self.name, e))
          break

        startWriteTime = core.CurrentTimeUtc()

        try:
          if reply.Success():
            if reply.NoData():
              reply.service_type.WriteEmptyResults(self, reply)
            else:
              reply.service_type.WriteResults(self, reply)
          else:
            logging.debug('ReplyProcessor: failed reply (%s, status:%s)', reply, reply.replyStatus)
            reply.service_type.ProcessErrorReply(self, reply)
        except Exception as e:
          LogError('ReplyProcessor (%s): error processing reply (%s): %s' % (self.name, reply, e))
          LogError('ReplyProcessor (%s): failed reply data: %s' % (self.name, reply.result))

        reply.service_type.timeWriteTotal += core.CurrentTimeUtc() - startWriteTime

    except Exception as e:
      LogError('ReplyProcessor (%s): exception: %s' % (self.name, e))
    finally:
      logging.info('ReplyProcessor (%s): thread stopped', self.name)

  def GetDbConnection(self):
    if self._dbConnection == None:
      self._dbConnection = core.DbConnection()
    return self._dbConnection

  def CloseDbConnection(self):
    if self._dbConnection:
      self._dbConnection.Close()

  def WriteRecord(self, service_type, tableName, record):
    with service_type.GetFlushLock():
      tableDbName = core.DbName(config.APT_DB_SCHEMA,tableName)
      msg = 'Writing %s: %s' % (tableDbName, FormatRecord(record))
      logging.info(msg)
      if OptSimulateMode:
        print(msg)
      else:
        self.GetDbConnection().InsertRecord(tableDbName,record)
      service_type.OnWrite()


class ObjectSelector(object):
  def __init__(self,info_updater,name,requestTypeQueue):
    self.info_updater = info_updater
    self.name = name
    self._dbConnection = None
    self.requestTypeQueue = requestTypeQueue
    self._thread = None

  def Start(self):
    self._thread = threading.Thread(name='ObjectSelector:%s' % (self.name,), target=self.ProcessRequests)
    self._thread.daemon = True
    self._thread.start()

  def Stop(self):
    if (self._thread != None):
      self._thread.join()
      self._thread = None

  def ProcessRequests(self):
    try:
      logging.info('ObjectSelector: thread started')

      core.UpdateActivity()

      while 1:
        try:
          core.UpdateActivity()
          requestSpec = self.requestTypeQueue.Get()
          requestType = requestSpec[0]
          time_interval = requestSpec[1]
          object_name_mask = requestSpec[2]
          core.UpdateActivity()
        except EOFError:
          logging.info('ObjectSelector: finishing...')
          break
        except Exception as e:
          LogError('ObjectSelector: error getting workitem: %s' % (e,))
          break

        try:
            self.ProcessServiceType(requestType, time_interval, object_name_mask)
        except Exception as e:
          LogError('ObjectSelector: error processing %s: %s' % (requestType.name,e))

    except Exception as e:
      LogError('ObjectSelector: exception: %s' % (e,))
    finally:
      logging.info('ObjectSelector: thread stopped')

  def ProcessServiceType(self, service_type, time_interval, object_name_mask):
    global totalCountQueryStart, totalCountQuerySelect, totalCountQueryDone
    query_proc_name = service_type.GetQueryProcName()
    if query_proc_name == None:
      logging.debug('ObjectSelector: no query defined for %s', service_type.name)
      return
    logging.info('ObjectSelector: processing %s', service_type.name)

    if time_interval == None:
      time_interval = (None, None)

    timeFrom = time_interval[0]
    timeTo = time_interval[1]
    timeFromStr = None
    if timeFrom != None:
      timeFromStr = core.TimeToSql(timeFrom)
    timeToStr = None
    if timeTo != None:
      timeToStr = core.TimeToSql(timeTo)

    queryProcDbName = core.DbName(config.APT_DB_SCHEMA, query_proc_name)

    logging.info('Starting query: %s [%s - %s]', queryProcDbName, timeFromStr, timeToStr)
    self.info_updater.LogOperation('QueryStart (%s)' % (query_proc_name,), None, 0)

    global statLock
    with statLock:
      totalCountQueryStart += 1

    try:
      startTime = core.CurrentTimeUtc()
      try:
        cursor = self.GetDbConnection().QueryProc(queryProcDbName,(timeFrom,timeTo))
      finally:
        with statLock:
          totalCountQuerySelect += 1

      duration = core.CurrentTimeUtc() - startTime
      self.info_updater.LogOperation('QuerySelect (%s)' % query_proc_name, duration, 0)

      objectCount = 0
      try:
        logging.info('Processing query results: %s', queryProcDbName)

        for r in cursor:
          try:
            reqs = service_type.CreateRequestsByQuery(r)

            for req in reqs:

              if object_name_mask != None:
                if not fnmatch.fnmatch(req.key,object_name_mask):
                  logging.debug('ObjectSelector: skipping not matched object: %s (mask:%s)',
                                req.key,
                                object_name_mask)
                  continue

              self.info_updater.ProcessRequest(req)
              objectCount += 1

            if OptMaxObjectCount != None and objectCount >= OptMaxObjectCount:
              logging.info('ObjectSelector: max object count reached')
              break
          except socket.error:
            LogError()
          except Exception as e:
            LogError('ObjectSelector: error creating request from row: %s (%s)' % (r, e))
      finally:
        try:
          cursor.close()
        except Exception:
          pass
        del cursor

      duration = core.CurrentTimeUtc() - startTime
      self.info_updater.LogOperation('QueryDone (%s)' % query_proc_name, duration, objectCount)

      logging.info('ObjectSelector: done processing %s' % (service_type.name))
    finally:
      with statLock:
        totalCountQueryDone += 1

  def GetDbConnection(self):
    if self._dbConnection == None:
      self._dbConnection = core.DbConnection()
    return self._dbConnection

  def CloseDbConnection(self):
    if self._dbConnection:
      self._dbConnection.Close()


TestService_FileReputation = {'id': core.ServiceId.FILE_REPUTATION, 'request_key': 'md5'}
TestService_HostReputation = {'id': core.ServiceId.HOST_REPUTATION, 'request_key': 'url'}
TestService_HostInfo = {'id': core.ServiceId.HOST_INFO, 'selector': 'type', 'request_key': 'host'}
TestService_HashInfo = {'id': core.ServiceId.HASH_INFO, 'request_key': 'md5'}
TestService_UrlInfo = {'id': core.ServiceId.URL_INFO, 'request_key': 'url'}

TestRequestTypes = {
  'domain_info' : {'service': TestService_HostInfo, 'selector_value': 1},
  'domain_top'  : {'service': TestService_HostInfo, 'selector_value': 2},
  'file_info'   : {'service': TestService_FileReputation},
  'host_info'   : {'service': TestService_HostReputation},
  'host_top'    : {'service': TestService_HostInfo, 'selector_value': 2},
  'ip_info'     : {'service': TestService_HostInfo, 'selector_value': 3},
  'ip_top'      : {'service': TestService_HostInfo, 'selector_value': 5},
  'file_name'   : {'service': TestService_HashInfo},
  'file_path'   : {'service': TestService_HashInfo},
  'file_pathmd5': {'service': TestService_HashInfo},
  'file_content': {'service': TestService_HashInfo},
  'url'         : {'service': TestService_UrlInfo},
  'vhs'         : {'service': TestService_HashInfo},
  'hash'        : {'service': TestService_HashInfo}
}

class TestKsnServer:
  def __init__(self):
    self.testSelectors = {}
    self.testReplyData = {}
    self.commServer = core.TestCommServer()

    for requestType in TestRequestTypes.itervalues():
      testService = requestType['service']

      serviceId = testService['id']
      selector = testService.get('selector')
      requestKeyName = testService['request_key']

      if not serviceId in self.testSelectors:
        self.testSelectors[serviceId] = (selector, requestKeyName)
      if not serviceId in self.testReplyData:
        self.testReplyData[serviceId] = {}

      selectorValue = requestType.get('selector_value')

      self.testReplyData[serviceId][selectorValue] = {}

  def Load(self, testFileName):
    try:
      logging.info('TestKsnServer: loading data from %s', testFileName)
      with open(testFileName, 'r') as fd:
        for line in fd:
          if not line.startswith('#') and len(line.strip()) != 0:
            self.LoadLine(line)
    except Exception as e:
      LogError('Error loading test data from %s: %s' % (testFileName, e))
      raise

  def LoadLine(self,testDataLine):
    try:
      requestTypeName, requestKey, replyData = testDataLine.split('\t')
      replyData = (replyData or '\n').splitlines()[0]

      requestType = TestRequestTypes[requestTypeName]
      serviceId = requestType['service']['id']
      selectorValue = requestType.get('selector_value')

      self.testReplyData[serviceId][selectorValue][requestKey] = replyData
    except Exception as e:
      LogError('Error in test data line: %s : %s' % (testDataLine, e))
      raise

  def Start(self, port, testDataFile):
    self.Load(testDataFile)
    self.commServer.Start(port, self.ProcessRequest)

  def Stop(self):
    self.commServer.Stop()

  def ProcessRequest(self, serviceId, requestData):
    try:
      request = json.loads(requestData, encoding='utf-8')
      selector, requestKeyName = self.testSelectors[serviceId]

      selectorValue = request.get(selector)
      repliesDict = self.testReplyData[serviceId][selectorValue]
      requestKey = request[requestKeyName]

      if requestKey in repliesDict:
        replyStatus = core.ReplyStatus.Success
        replyData = repliesDict[requestKey]
      else:
        replyStatus = core.ReplyStatus.NoData
        replyData = ''
    except Exception as e:
      LogError('TestKsnServer: error processing request: %s' % (e,))
      replyStatus = core.ReplyStatus.PermError
      replyData = ''

    return replyStatus, replyData

TestServer = TestKsnServer()


class InfoUpdater(object):
  def __init__(self):
    self.reply_queue = core.Queue(config.APT_REPLY_QUEUE_SIZE)
    self.selector_queue = core.Queue()
    self.replyProcessors = []
    self.objectSelectors = []
    self.logDbConnection = core.DbConnection()
    self.startTime = None

    self.info_provider = core.InfoProvider()
    self.watchdogThread = None
    self.watchdog_stopped = False

    self.logOperationLock = threading.Lock()

    replyWorkerCount = config.APT_REPLY_WORKERS
    i = 0
    while i < replyWorkerCount:
      worker = ReplyProcessor(self, ('%s' % (i+1,)), self.reply_queue)
      self.replyProcessors.append(worker)
      i += 1

    selectorCount = config.APT_REQUEST_WORKERS
    i = 0
    while i < selectorCount:
      worker = ObjectSelector(self, ('%s' % (i+1,)), self.selector_queue)
      self.objectSelectors.append(worker)
      i += 1

  def Start(self):
    logging.info('InfoUpdater: starting')
    self.startTime = core.CurrentTimeUtc()
    self.LogOperation('Starting',None,0)

    if OptTestKsn:
      TestServer.Start(config.APT_TEST_PORT, config.APT_TEST_DATA_FILE)

    if config.APT_WATCHDOG_PERIODICITY:
      self.watchdogThread = threading.Thread(name='Watchdog', target=self.WatchdogThread)
      self.watchdogThread.daemon = True
      self.watchdogThread.start()

    self.info_provider.Start()
    for w in self.replyProcessors:
      w.Start()
    for w in self.objectSelectors:
      w.Start()

    logging.info('InfoUpdater: started')

  def ProcessRequest(self, req):
    service_type = req.service_type
    req.service_type.OnStart()
    self.info_provider.SendRequest(req, self.reply_queue)

  def ProcessSubRequest(self,req):
    service_type = req.service_type
    self.info_provider.SendRequest(req, self.reply_queue)

  def ProcessService(self, service_name, time_interval=None, object_name_mask=None):
    service_type = GetServiceType(service_name)
    self.selector_queue.Put((service_type, time_interval, object_name_mask))

  def Finish(self):
    self.selector_queue.Close()
    for w in self.objectSelectors:
      w.Stop()

    logging.info('InfoUpdater: processing replies...')
    if any(s.countSent > 0 for s in ServiceTypes.itervalues()):
      core.WaitForIdle(core.TimeDeltaToSeconds(config.APT_KSN_TIMEOUT))

  def Stop(self):
    logging.info('InfoUpdater: stopping...')
    self.info_provider.Stop()
    self.reply_queue.Close()

    for w in self.objectSelectors:
      w.CloseDbConnection()

    for w in self.replyProcessors:
      w.Stop()
      w.CloseDbConnection()

    if self.watchdogThread != None:
      logging.info('InfoUpdater: stopping watchdog')
      self.watchdog_stopped = True
      self.watchdogThread.join()
      self.watchdogThread = None

    self.Finalize()
    self.ReportStatistics()

    if OptTestKsn:
      TestServer.Stop()

    if self.startTime is None:
      self.startTime = core.CurrentTimeUtc()
    duration = core.CurrentTimeUtc() - self.startTime
    self.LogOperation('Stopped', duration, totalCountWrite)

    with self.logOperationLock:
      self.logDbConnection.Close()
    logging.info('InfoUpdater: stopped')

  def FlushService(self,service_type):
    with service_type.GetFlushLock():
      procName = service_type.GetFinalizeProcName()
      if procName is not None:
        try:
          procDbName = core.DbName(config.APT_DB_SCHEMA,procName)
          logging.info('Updating %s: calling %s...' % (service_type.name,procDbName))
          startTime = core.CurrentTimeUtc()
          if not OptSimulateMode and not OptNoUpdate:
            with core.DbConnection() as db_conn:
              db_conn.ExecProc(procDbName,())
          endTime = core.CurrentTimeUtc()
          self.LogOperation('%s' % (procName,), endTime-startTime, service_type.countWrite)
        except Exception as e:
          LogError('Error updating %s: %s' % (service_type.name,e))
      service_type.flushTimeLast = core.CurrentTimeUtc()
      service_type.flushCountLast = service_type.countWrite

  def Finalize(self):
    logging.info('Updating database')
    for service_type in ServiceTypes.itervalues():
      if service_type.countWrite != 0:
        self.FlushService(service_type)
    logging.info('Done updating database')

  def LogOperation(self, info, duration, object_count):
    with self.logOperationLock:
      try:
        seconds = 0
        if duration is not None:
          seconds = int(core.TimeDeltaToSeconds(duration) + 0.5)

        logging.info('LogOperation: %s, duration: %s (%s sec), objcount: %s',
                     info,
                     duration,
                     seconds,
                     object_count)

        if OptSimulateMode:
          return
        self.logDbConnection.ExecProc(core.DbName(CommonSchemaName(), 'log_operation_dur'),
                                      (seconds, config.APT_EXECUTION_LOG_KEY, info, object_count))
      except Exception as e:
        LogError('LogOperation error: %s' % (e,))

  def ReportStatistics(self):
    self.LogOperation('ReqSent (total)', None, totalCountSent)
    self.LogOperation('ReqRecv (total)', None, totalCountRecv)
    self.LogOperation('ReqErrs (total)', None, totalCountErrs)
    self.LogOperation('Written (total)', None, totalCountWrite)

    for service_name, service_type in ServiceTypes.iteritems():
      self.LogOperation('ReqSent (%s)' % service_name, None, service_type.countSent)

      if service_type.countSent != 0:
        duration = None
        if service_type.timeSentFirst is not None:
          timeRecvLast = service_type.timeRecvLast or core.CurrentTimeUtc()
          duration = timeRecvLast - service_type.timeSentFirst
        self.LogOperation('ReqRecv (%s)' % service_name, duration, service_type.countRecv)

      if service_type.countErrs != 0:
        self.LogOperation('ReqErrs (%s)' % service_name, None, service_type.countErrs)

      if service_type.countSent != 0 or service_type.countWrite != 0:
        self.LogOperation('Written (%s)' % service_name,
                          service_type.timeWriteTotal,
                          service_type.countWrite)

  def WatchdogThread(self):
    logging.info('Watchdog started')
    try:
      self.WatchdogProc()
      last_time = core.CurrentTimeUtc()

      while not self.watchdog_stopped:
        current_time = core.CurrentTimeUtc()
        if (current_time - last_time) >= config.APT_WATCHDOG_PERIODICITY:
          self.WatchdogProc()
          last_time = current_time
        time.sleep(1)

      self.WatchdogProc()
    except Exception as e:
      LogError('Watchdog exception: %s' % (e,))
    finally:
      logging.info('Watchdog stopped')

  def WatchdogProc(self):
    try:
      LogStatistics(config.APT_WATCHDOG_FILE)
      self.CheckFlush()
    except Exception:
      pass

  def CheckFlush(self):
    try:
      for service_type in ServiceTypes.itervalues():
        need_flush = False

        if (service_type.GetFinalizeProcName() is not None and
            service_type.countWrite > service_type.flushCountLast):

          if config.APT_FLUSH_PERIODICITY:
            if (core.CurrentTimeUtc() - service_type.flushTimeLast) >= config.APT_FLUSH_PERIODICITY:
              need_flush = True

          if config.APT_FLUSH_RECORDS:
            if (service_type.countWrite - service_type.flushCountLast) >= config.APT_FLUSH_RECORDS:
              need_flush = True

        if need_flush:
          self.FlushService(service_type)
    except Exception:
      pass

  def CheckSuccess(self):
    global totalErrors
    ok = True
    if totalErrors != 0:
      logging.error('InfoUpdater: error count is nonzero')
      ok = False
    if not self.reply_queue.IsEmpty():
      logging.error('InfoUpdater: reply queue not empty')
      ok = False
    if not self.selector_queue.IsEmpty():
      logging.error('InfoUpdater: selector queue not empty')
      ok = False
    if self.info_provider.HasUnprocessedRequests():
      logging.error('InfoUpdater: has unprocessed requests')
      ok = False
    return ok


def ResetServiceStatistics():
  for service_type in ServiceTypes.itervalues():
    service_type.ResetStatistics()


class InfoUpdaterRunner(object):
  def __init__(self):
    logging.info('InfoUpdater v %s', ScriptVersionStr)

    self.allow_write_processed_date = False
    self.info_updater = None
    self.processed_dates = {}
    self.objective_dates = {}
    self.work_intervals = None
    self.is_success = None

  def Init(self, portion_size, allow_write_processed_date, service_names=None):
    with core.DbConnection() as db_conn:
      self.objective_dates = GetObjectiveDates(db_conn)
      self.processed_dates = {}

      service_names = service_names or set()
      for service_name, service_type in ServiceTypes.iteritems():
        if service_name not in service_names:
          continue

        service_key_name = service_type.GetServiceKeyName()
        if service_key_name is not None:
          processed_date = GetProcessedDate(db_conn, service_key_name)
          self.processed_dates[service_key_name] = processed_date

    self.portion_size = portion_size
    self.allow_write_processed_date = allow_write_processed_date
    logging.info('PortionSize: %s', self.portion_size)

  def GetProcessor(self):
    return self.info_updater

  def BeginPortion(self):
    ResetServiceStatistics()
    ClearErrors()
    self.is_success = None

    self.info_updater = InfoUpdater()
    self.info_updater.Start()

    self.work_intervals = {}
    for service_key_name, processed_date in self.processed_dates.iteritems():
      objective_date = GetDic(self.objective_dates, service_key_name)
      if objective_date is None:
        logging.debug('Skipping %s: no objective date', service_key_name)
        continue

      min_date_from = objective_date - config.APT_MAX_DATA_AGE
      if processed_date is None or processed_date < min_date_from:
        processed_date = min_date_from

      if processed_date >= objective_date:
        logging.debug('Skipping %s: objective date %s reached',
                      service_key_name,
                      core.TimeToSql(objective_date))
        continue

      if self.portion_size is not None:
        work_date = processed_date + self.portion_size
      else:
        work_date = core.CurrentTimeUtc()

      logging.info('WorkPortion %s: [%s - %s]',
                   service_key_name,
                   core.TimeToSql(processed_date),
                   core.TimeToSql(work_date))

      self.work_intervals[service_key_name] = (processed_date, work_date)

  def ProcessResponses(self):
    self.info_updater.Finish()

  def CheckSuccess(self):
    return bool(self.is_success)

  def HasMoreWork(self, service_name):
    service_key_name = GetServiceType(service_name).GetServiceKeyName()

    processed_date = GetDic(self.processed_dates, service_key_name)
    objective_date = GetDic(self.objective_dates, service_key_name)

    if (not processed_date) or (not objective_date):
      return False

    return processed_date < objective_date

  def ProcessService(self, service_name, object_name_mask=None):
    service_key_name = GetServiceType(service_name).GetServiceKeyName()

    if service_key_name in self.work_intervals:
      work_interval = self.work_intervals[service_key_name]

      logging.info('Processing %s [%s - %s]',
                   service_name,
                   core.TimeToSql(work_interval[0]),
                   core.TimeToSql(work_interval[1]))

      self.info_updater.ProcessService(service_name, work_interval, object_name_mask)

  def ProcessAllServices(self):
    for service_name, service_type in ServiceTypes.iteritems():
      if service_type.GetServiceKeyName() is not None:
        self.ProcessService(service_name)

  def EndPortion(self):
    try:
      self.info_updater.Stop()
      self.is_success = self.info_updater.CheckSuccess()

      if not self.is_success:
        logging.error('InfoUpdater finished with errors')
      else:
        for service_key_name, work_interval in self.work_intervals.iteritems():
          objective_date = self.objective_dates[service_key_name]
          processed_date = min(work_interval[1], objective_date)

          if self.allow_write_processed_date:
            with core.DbConnection() as db_conn:
              SetProcessedDate(db_conn, service_key_name, processed_date)

          self.processed_dates[service_key_name] = processed_date
    finally:
      self.info_updater = None

  def Cleanup(self):
    if self.info_updater != None:
      self.info_updater.Stop()
      self.info_updater = None


def update_detector_rules_state(info_updater):
  logging.info('Loading detector rules state...')

  installation_id = ''
  try:
    with open('/var/opt/kaspersky/apt/installer.dat', 'r') as in_f:
      installation_id = in_f.read().strip().split('=')[1]
    logging.debug('Installation ID=%s', installation_id)
  except Exception as e:
    LogError('Unable to get installation ID: %s' % (e,))

  try:
    req = RulesStateService.instance.CreateRequest(installation_id)
    info_updater.GetProcessor().ProcessRequest(req)
  except Exception as e:
    LogError('Error processing RulesStateService request: %s' % (e,))


def Run(cfg, process_new_records=False, process_rescan=False):
  config.APT_HOST = cfg['comm']['host']
  config.APT_PORT = cfg['comm']['port']
  config.APT_DB_SERVER = cfg['db']['server']
  config.APT_DB_PORT = cfg['db']['port']
  config.APT_DB_NAME = cfg['db']['name']
  config.APT_DB_USER = cfg['db']['user']
  config.APT_DB_PASSWORD = cfg['db']['password']

  info_updater = InfoUpdaterRunner()
  try:
    service_names = set()
    for service_name, service_type in ServiceTypes.iteritems():
      is_new_records_service = isinstance(service_type, ServiceTypeNew)
      is_rescan_service = isinstance(service_type, ServiceTypeRescan)

      if (is_new_records_service == process_new_records and
          is_rescan_service == process_rescan):
        service_names.add(service_name)

    info_updater.Init(config.APT_WORK_PORTION, True, service_names)

    cycle_num, retry_count = 0, 0
    while True:
      cycle_num += 1
      logging.info('Cycle %s: begin' % (cycle_num,))

      try:
        info_updater.BeginPortion()

        if cycle_num == 1 and process_rescan:
          update_detector_rules_state(info_updater)

        info_updater.ProcessAllServices()
        info_updater.ProcessResponses()
        info_updater.EndPortion()
      except Exception as e:
        LogError('InfoUpdater failed: %s' % (e,))
      finally:
        info_updater.Cleanup()

      logging.info('Cycle %s: end', cycle_num)

      if info_updater.CheckSuccess():
        retry_count = 0
        has_work = any(info_updater.HasMoreWork(s) for s in ServiceTypes.iterkeys())
        if not has_work:
          logging.info('No more work, exiting')
          break
      else:
        logging.error('InfoUpdater finished with errors')
        retry_count += 1
        max_retry_count = config.APT_RETRY_COUNT or 0
        if retry_count > max_retry_count:
          logging.info('Retry limit (%s) exceeded, exiting', max_retry_count)
          sys.exit(1)

        logging.info('Retry attempt #%s (limit: %s)', retry_count, max_retry_count)
        if config.APT_RETRY_DELAY:
          delay_seconds = core.TimeDeltaToSeconds(config.APT_RETRY_DELAY)
          logging.info('Pausing for %s seconds before retry', delay_seconds)
          time.sleep(delay_seconds)

  finally:
    info_updater.Cleanup()
    LogStatistics(config.APT_WATCHDOG_FILE)

if __name__ == "__main__":
  import codecs

  def IsMask(s):
    if s.find('*')>=0 or s.find('?')>=0:
      return True
    else:
      return False

  codec = None
  try:
    if codecs.lookup('mbcs') != None:
      codec = 'mbcs'
  except Exception:
    pass

  objectsToQuery = []

  has_object_names = False

  a = 1
  while a < len(sys.argv):
    arg = sys.argv[a]
    if len(arg)!=0 and (arg[0]=='-' or arg[0]=='/'):
      isOption = True
      argNorm = arg[1:]
    else:
      isOption = False
      argNorm = arg

    try:
      idx = argNorm.index(':')
      argName = argNorm[:idx]
      argParm = argNorm[idx+1:].lower()
    except ValueError:
      argName = argNorm
      argParm = None

    if isOption:
      argName = argName.lower()
      if argName == 'simulate':
        OptSimulateMode = True
      elif argName == 'maxcount':
        OptMaxObjectCount = int(argParm)
      elif argName == 'noupdate':
        OptNoUpdate = True
      elif argName == 'test':
        OptTestMode = True
      elif argName == 'testksn':
        OptTestKsn = True
      elif argName == 'portion':
        OptPortion = datetime.timedelta(hours=float(argParm))
      elif argName == 'writelastdate':
        OptWriteLastDate = True
      elif argName == 'newrecords':
        OptProcessNewRecords = True
        config.APT_WORK_PORTION = config.APT_NEW_RECORDS_WORK_PORTION
        config.APT_WATCHDOG_FILE = config.APT_NEW_RECORDS_WATCHDOG_FILE
        config.APT_EXECUTION_LOG_KEY = config.APT_NEW_RECORDS_EXECUTION_LOG_KEY
      elif argName == 'rescan':
        OptProcessRescan = True
        config.APT_WORK_PORTION = config.APT_RESCAN_WORK_PORTION
        config.APT_WATCHDOG_FILE = config.APT_RESCAN_WATCHDOG_FILE
        config.APT_EXECUTION_LOG_KEY = config.APT_RESCAN_EXECUTION_LOG_KEY
      else:
        print('Invalid option: %s' % (arg,))
        sys.exit(1)
    else:
      if not argName in ServiceTypeNames:
        print('Unknown service: %s' % (argName,))
      objectsToQuery.append((argName,argParm))
      if argParm != None:
        has_object_names = True

    a += 1

  if OptTestMode:
    OptTestKsn = True
    logFormat = '%(asctime)s %(levelname)s %(message)s'
    logging.basicConfig(level=logging.DEBUG, format=logFormat)
    config.APT_DB_NAME = config.APT_TEST_DB_NAME
    config.APT_DB_SCHEMA = config.APT_TEST_DB_SCHEMA
    config.APT_MAX_DATA_AGE = datetime.timedelta(days=20000)
    config.APT_KSN_REQUEST_INTERVAL = 0.0
  else:
    logFormat = '%(asctime)s %(levelname)s [%(threadName)s:%(funcName)s] %(message)s'
    logging.basicConfig(filename='info_updater.log', level=logging.DEBUG, format=logFormat, filemode='w')

  if OptTestKsn:
    config.APT_HOST = '127.0.0.1'
    config.APT_PORT = config.APT_TEST_PORT

  if OptTestMode:
    print('Timeout: %s' % (config.APT_TEST_TIMEOUT,))
    ClearDictionaries()

  allow_write_processed_date = True
  if (OptSimulateMode or OptNoUpdate) and not OptWriteLastDate:
    allow_write_processed_date = False
  if OptTestMode or OptTestKsn:
    allow_write_processed_date = False
  if OptMaxObjectCount != None:
    allow_write_processed_date = False
  if has_object_names:
    allow_write_processed_date = False

  info_updater = InfoUpdaterRunner()

  try:
    if OptPortion is None and not OptTestMode:
      OptPortion = config.APT_WORK_PORTION

    service_names = set()
    for service_name, service_type in ServiceTypes.iteritems():
      is_new_records_service = isinstance(service_type, ServiceTypeNew)
      is_rescan_service = isinstance(service_type, ServiceTypeRescan)

      if (is_new_records_service == OptProcessNewRecords and
          is_rescan_service == OptProcessRescan):
        service_names.add(service_name)

    info_updater.Init(OptPortion, allow_write_processed_date, service_names)

    cycle_num = 0
    while True:
      cycle_num += 1

      print('Cycle %s: begin' % (cycle_num,))
      logging.info('Cycle %s: begin', cycle_num)

      print('Starting InfoUpdater...')

      info_updater.BeginPortion()
      repeat_cycle = True

      if len(objectsToQuery) == 0:
        info_updater.ProcessAllServices()
      else:
        repeat_cycle = False
        for obj in objectsToQuery:
          service_name, object_name = obj[0], obj[1]

          if object_name == None or IsMask(object_name):
            print('Processing service: %s (mask:%s)' % (service_name, object_name))
            if codec != None and object_name != None:
              object_name = object_name.decode(codec).encode('utf-8')
            info_updater.ProcessService(service_name,object_name)
            if object_name == None and info_updater.HasMoreWork(service_name):
              repeat_cycle = True
          else:
            print('Processing object: %s:%s' % (service_name, object_name))
            service_type = GetServiceType(service_name)
            if codec != None:
              object_name = object_name.decode(codec).encode('utf-8')
            else:
              object_name = object_name.decode(sys.stdin.encoding).encode('utf-8')
            req = service_type.CreateRequest(object_name)
            info_updater.GetProcessor().ProcessRequest(req)

      print('Processing objects...')
      info_updater.ProcessResponses()

      print('Done processing objects')
      info_updater.EndPortion()

      print('Cycle %s: end' % (cycle_num,))
      logging.info('Cycle %s: end', cycle_num)

      if not info_updater.CheckSuccess():
        print('InfoUpdater finished with errors, exiting')
        sys.exit(1)

      has_work = any(info_updater.HasMoreWork(s) for s in ServiceTypes.iterkeys())
      if not (repeat_cycle and has_work):
        print('No more work to do, exiting')
        break

  except Exception as e:
    print('Processing error: %s' % (e,))
    totalErrors += 1
  finally:
    info_updater.Cleanup()
    LogStatistics(config.APT_WATCHDOG_FILE)
    print('Done')

  if OptTestMode:
    print('Test summary: Started: %s, Written: %s, Errors: %s' % (totalCountStart,
                                                                  totalCountWrite,
                                                                  totalErrors))

    if totalCountStart != 0 and totalCountWrite == totalCountStart and totalErrors == 0:
      print('Test success')
      sys.exit(0)
    else:
      print('Test failure')
      sys.exit(1)
