#!/usr/bin/python
# checksysreport, a tool to spot unsupported issues.
# Copyright 2005 Pierre Amadio 
# pamadio@redhat.com
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation version 2.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
"""
This script fills the following tables:

Erratas,Advisory_Per_Packages,Bugzillas,Bz_Per_Advisory,
"""
import sys
import time
sys.path.append('/usr/share/checksysreport')
import pgdb
import rhnapiwrap
import string
import Queue
#http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/435883
#http://chrisarndt.de/en/software/python/threadpool.html
from threadpool import *
import globals
#http://www.devpicayune.com/entry/200609191448
import socket
socket.setdefaulttimeout(300) 

import signal
import syslog
poolSize=10
syslog.openlog('fill-cache-advisory')

rhn_login=globals.config['rhn_login']
rhn_password=globals.config['rhn_password']
rhn_server=globals.config['rhn_server']
rhnConnector=rhnapiwrap.rhnapiwrap(rhn_login,rhn_password,rhn_server)
rhnConnector.login()
#all_packages=Queue.Queue()
buff_packages=[]
#latest_packages=Queue.Queue()
buff_latest_packages=[]
buff_adv=[]
max_attempt=30
db=globals.db

def sig_handler(sig,frame):
    print "signal received",sig
    syslog.syslog(syslog.LOG_WARNING,'Recieved a signal:%s',sig)
    db.abord()
    sys.exit()
    raise

signal.signal(signal.SIGTERM, sig_handler)
pool=ThreadPool(poolSize)

################ fill_advisory ########################

def get_advinfos_for_channel(channel):
    print "lets get info for ",channel
    out=[channel]
    try:
        db_thread=pgdb.connect(database=globals.config["sql_database"])
        db_thread_cursor=db_thread.cursor()
    except pgdb.DatabaseError,error:
        syslog.syslog(syslog.LOG_WARNING,"Exception occured in request for channel %s:'%s'"%(channel,error))
        globals.die("We have a problem with the database:%s"%error)

    try:
        rhn=rhnapiwrap.rhnapiwrap(rhn_login,rhn_password)
        rhn.login()
    except:
        syslog.syslog(syslog.LOG_WARNING,"Problem connecting to rhn:'%s'"%sys.exc_info()[0])
        print "Exception occured wile connecting to rhn '%s'"%sys.exc_info()[0]
        print "Problem connecting to rhn: '%s'"%sys.exc_info()[1]
        db_thread.close()
        time.sleep(5)
        return get_advinfos_for_channel(channel)
                                             

        
    new_adv=[]

    
    try:

        
        for cur_adv in rhn.listErrata(channel):
            #db_thread.query("BEGIN TRANSACTION")
            db_thread_cursor.execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")
            #print "adv",cur_adv['errata_advisory']
            qsnt="select count(*) as cnt from Erratas where advisory='"+str(cur_adv['errata_advisory'])+"'"
            
            db_thread_cursor.execute(qsnt)
            testExist=db_thread_cursor.fetchone()[0]
            
            if testExist:
                #print "already in db:%s"%cur_adv['errata_advisory']
                db_thread.commit()
                continue

            print "new advisory to treat: %s"%cur_adv['errata_advisory']
            curDic={}
            #snt=sql_erratas_snt(cur_adv).encode('utf8')
            
            snt="insert into Erratas (advisory,update_date,advisory_type,synopsis,last_modified_date,issue_date) "
            snt+="values (%(errata_advisory)s,%(errata_update_date)s,%(errata_advisory_type)s,%(errata_synopsis)s,"
            snt+="%(errata_last_modified_date)s,%(errata_issue_date)s)"
            
            new_adv.append(cur_adv['errata_advisory'])

            try:
                db_thread_cursor.execute(snt,{'errata_advisory':cur_adv['errata_advisory'],\
                                                  'errata_update_date':cur_adv['errata_update_date'],\
                                                  'errata_advisory_type':cur_adv['errata_advisory_type'],\
                                                  'errata_synopsis':cur_adv['errata_synopsis'],\
                                                  'errata_last_modified_date':cur_adv['errata_last_modified_date'],\
                                                  'errata_issue_date':cur_adv['errata_issue_date'],\
                                                  })

            except pgdb.Error,error:
                db_thread.rollback()
                print "probelmatic advisory",cur_adv
                syslog.syslog(syslog.LOG_WARNING,"Exception occured in'%s':'%s'"%(snt,error))
                globals.die("We have a problem with the database:'%s'  :   '%s'"%(snt,error))

                
            for p in rhn.errata_list_packages(cur_adv['errata_advisory']):
                snt="insert into Advisory_Per_Packages values (%(errata_advisory)s,%(package_id)d)"
                try:
                    db_thread_cursor.execute(snt,{'errata_advisory':cur_adv['errata_advisory'],\
                                                      'package_id':int(p['package_id'])})

                except pgdb.Error,error:
                    db_thread.rollback()
                    print "cur_adv['errata_advisory']",cur_adv['errata_advisory']
                    print "package_id",int(p['package_id'])
                    print snt
                    print ___
                    syslog.syslog(syslog.LOG_WARNING,"Exception occured in'%s':'%s'"%(snt,error))
                    globals.die("We have a problem with the database:'%s'  :   '%s'"%(snt,error))
                

            bugs=rhn.get_bugs_for_errata(cur_adv['errata_advisory'])
            for id in bugs:
                #print id,bugs[id]
                qsnt="select count(*) as cnt from Bugzillas where bz_id="+str(id)
                #print "qsnt=%s"%qsnt
                db_thread_cursor.execute(qsnt)
                testExist=db_thread_cursor.fetchone()[0]
                
                if not testExist:
                    label=bugs[id]
                    snt="insert into Bugzillas values (%(id)d,%(label)s)"
                    try:
                        db_thread_cursor.execute(snt,{'id':int(id),'label':label.encode('utf8')})
                    except pgdb.Error,error:
                        db_thread.rollback()
                        syslog.syslog(syslog.LOG_WARNING,"Exception occured in'%s':'%s'"%(snt,error))
                        globals.die("We have a problem with the database:'%s'  :   '%s'"%(snt,error))

                snt="insert into Bz_Per_Advisory values (%(errata_advisory)s,%(id)d)"
                try:
                    db_thread_cursor.execute(snt,{'errata_advisory':cur_adv['errata_advisory'],\
                                                      'id':int(id)})

                except pgdb.Error,error:
                    db_thread.rollback()
                    syslog.syslog(syslog.LOG_WARNING,"Exception occured in'%s':'%s'"%(snt,error))
                    globals.die("We have a problem with the database:'%s'  :   '%s'"%(snt,error))


            print "done for advisory %s"%cur_adv['errata_advisory']
            db_thread.commit()

    except :
        """
         There was a problem... Let s re start from scratch.
        """
        print "Exception occured in request #%s"%channel
        print sys.exc_info()[0]
        print sys.exc_info()[1]
        #print sys.exc_info()[2]
        syslog.syslog(syslog.LOG_WARNING,"Exception occured in request for channel %s"%channel)
        #should not be necessary to rollback, but...just in case.
        db_thread.rollback()
        db_thread.close()

        if len(new_adv)>1:
            print "Some new advisory for channels %s were treaded anyway:"%channel
            for a in new_adv[:-1]:
                print "  %s"%a
        
        print "Let's do it again for channel '%s'"%channel
        return get_advinfos_for_channel(channel)

    db_thread.close()

    if len(new_adv):
        print "New advisory for channels %s"%channel
        for a in new_adv:
            print "  %s"%a
        
    return out

def advisory_infos_fetched(request,result):
    #print "fetched req=",request.requestID
    buff_adv.append(result)
    #print "result=",result

def handle_advisory():
    out=[]
    #print "handling %i data"%len(buff_adv)
    
    while len(buff_adv):
        cur=buff_adv.pop(0)
        #print "cur=",cur[0]
        #print "CUR=",cur
        #for k in cur:
        #    print "Cur key",k
        #out.append(cur['advisory_id'])
        out.append(cur[0])
    return out
    
def fill_advisory():
    print "Let's fetch erratas informations"
    fresh_adv=[]
        


    channels=globals.select_supported_channels()
    nbr_all=len(channels)
    nbr_waiting=nbr_all
    waiting={}
    for channel_label in channels:
        newReq=WorkRequest(get_advinfos_for_channel,\
                           args=[channel_label],\
                           kwds=None,\
                           requestID=channel_label,\
                           callback=advisory_infos_fetched)
        pool.putRequest(newReq)
        waiting[channel_label]=True


    attempt_cnt=0
    
    while 1:
        time.sleep(1)
        nbr_done=nbr_all-nbr_waiting
        print "nbr_done=%i nbr_waiting=%i"%(nbr_done,nbr_waiting)

        if attempt_cnt>max_attempt:
            syslog.syslog(syslog.LOG_WARNING,'Max attempt reached')
            print "Max attempt reached"
            db.commit()
            sys.exit()

        handled=handle_advisory()
        for cur_adv in handled:
            #print "has been handled ",cur_adv
            waiting[cur_adv]=False
            nbr_waiting=nbr_waiting-1
            attempt_cnt=0
            
        try:
            pool.poll()
            
        except KeyboardInterrupt:
            print "Interrupted!"
            syslog.syslog(syslog.LOG_WARNING,'Received a keyboard interrupt')
            db.rollback()
            sys.exit()
        except NoResultsPending:
            print "No Results Pending."
            if nbr_waiting==0:
                break
            
            print "nbr_waiting=",nbr_waiting
            attempt_cnt+=1
            print "%s out of %s attempt"%(attempt_cnt,max_attempt)
            continue
        except:
            print "Karamba ke passa ?"
            print "Yet another unexpected error:", sys.exc_info()[0]
            syslog.syslog(syslog.LOG_WARNING,'Karamba ke passa: fill_packages ?')
            db.rollback()
            raise
            sys.exit()
            

    print "updating advisory packages is done."
    sys.exit()




fill_advisory()


