#!/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:

Channels,Packages,Packages_Per_Channels
"""
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('fillrhncache')
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()
max_attempt=80
db=globals.db
db_cursor=db.cursor()


buff_packages=[]
buff_latest_packages=[]

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

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

missed_stuff=[]

def pool_exception(request,exc_info):
    print "**********************************"
    try:
        print "Exception occured in request #%s: %s" % (request.requestID, exc_info[1])
        syslog.syslog(syslog.LOG_WARNING,"Exception occured in request #%s: %s" % (request.requestID, exc_info[1]))
    except:
        print "Exception trying to print exception: %s"%request.requestID
        syslog.syslog(syslog.LOG_WARNING,"Exception trying to print exception: %s"%request.requestID)

def insert_stuff(snt,params):
    #print "can we insert '%s'"%snt
    try:
        db_cursor.execute(snt,params)
    except:
        print "problem with :",snt
        print "params=",params
        syslog.syslog(syslog.LOG_DEBUG,"problem with :'%s'"%snt)
        db.rollback()
        raise



################ fill_channels ########################
def fill_channels():
    """ Fill the Channels Table"""
    print "-----------------------"
    print "Let's fill channels info"
    print "-----------------------"
    
    rhnInfo=rhnConnector.list_software_channels()
    db_cursor.execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")
    childChan=[]
    baseChan=[]
    baseChan_labels=[]
    all_rhn_chan_label=[]

    for curChan in rhnInfo:
        all_rhn_chan_label.append(curChan['channel_label'])
        if curChan['channel_parent_label']:
            childChan.append(curChan)
        else:
            baseChan.append(curChan)
            baseChan_labels.append(curChan['channel_label'])


    #Let's start by removing from the local database channels
    #that are not existing on rhn anymore.
    for clabel in globals.select_all_channels_label_in_db():
        if clabel not in all_rhn_chan_label:
            print "%s must be deleted from database"%clabel
            globals.delete_channel(clabel)

    #Now, lets fill the local database with new channel that
    #appeared on rhn.

    for chan in baseChan:
        if chan['channel_end_of_life']:
            timestamp=chan['channel_end_of_life']
        else:
            timestamp=0


        test=globals.is_channel_in_db(chan['channel_label'])
        if not test:

            if timestamp!=0:
                snt="insert into Channels (channel_label,channel_name,channel_parent_label,channel_end_of_life,channel_arch) "
                snt+="values (%(channel_label)s,%(channel_name)s,NULL,%(channel_end_of_life)s,%(channel_arch)s)"
                params={'channel_label':chan['channel_label'],\
                            'channel_name':chan['channel_name'],\
                            'channel_end_of_life':timestamp,\
                            'channel_arch':chan['channel_arch']}
            else:
                snt="insert into Channels (channel_label,channel_name,channel_parent_label,channel_end_of_life,channel_arch) "
                snt+="values (%(channel_label)s,%(channel_name)s,NULL,NULL,%(channel_arch)s)"
                params={'channel_label':chan['channel_label'],\
                            'channel_name':chan['channel_name'],\
                            'channel_arch':chan['channel_arch']}

        else:
            """channel is already in database, let s just do an update"""
            if timestamp!=0:
                snt="update Channels set channel_end_of_life=%(channel_end_of_life)s "
                snt+=" where channel_label=%(channel_label)s"
                params={'channel_end_of_life':timestamp,'channel_label':chan['channel_label']}
            else:
                snt="update Channels set channel_end_of_life=NULL "
                snt+=" where channel_label=%(channel_label)s"
                params={'channel_label':chan['channel_label']}

        insert_stuff(snt,params)

    for chan in childChan:
        if chan['channel_end_of_life']:
            timestamp=chan['channel_end_of_life']
        else:
            timestamp=0


        test=globals.is_channel_in_db(chan['channel_label'])
        if not chan['channel_parent_label'] in baseChan_labels:
            print "%s is an orphan channel ('%s' not in base channels)"%(chan['channel_label'],chan['channel_parent_label'])
            continue

        if not test:
            if timestamp!=0:
                snt="insert into Channels (channel_label,channel_name,channel_parent_label,channel_end_of_life,channel_arch)"
                snt+="values (%(channel_label)s,%(channel_name)s,%(channel_parent_label)s,%(channel_end_of_life)s,%(channel_arch)s)"
                params={'channel_label':chan['channel_label'],\
                            'channel_name':chan['channel_name'],\
                            'channel_parent_label':chan['channel_parent_label'],\
                            'channel_end_of_life':timestamp,\
                            'channel_arch':chan['channel_arch']}
            else:
                """there s no channel_end_life, so timestamp is set to 0"""
                snt="insert into Channels (channel_label,channel_name,channel_parent_label,channel_end_of_life,channel_arch)"
                snt+="values (%(channel_label)s,%(channel_name)s,%(channel_parent_label)s,NULL,%(channel_arch)s)"
                params={'channel_label':chan['channel_label'],\
                            'channel_name':chan['channel_name'],\
                            'channel_parent_label':chan['channel_parent_label'],\
                            'channel_arch':chan['channel_arch']}

        else:
            """channel is already in the database, let s update things and not insert it"""
            if timestamp!=0:
                snt="update Channels set channel_end_of_life=%(timestamp)s "
                snt+=" where channel_label=%(label)s"
                params={'timestamp':timestamp,'label':chan['channel_label']}
            else:
                snt="update Channels set channel_end_of_life=NULL "
                snt+=" where channel_label=%(label)s"
                params={'label':chan['channel_label']}

        insert_stuff(snt,params)
            
    print "COMMITING: channels"
    db.commit()

################ fill_packages ########################
def list_packages_in_channel_software(chan_label):
    #print "Let s fetch info for ",chan_label
    out={}
    out['channel_label']=chan_label
    rhn=rhnapiwrap.rhnapiwrap(rhn_login,rhn_password,rhn_server)
    rhn.login()
    out['packages']=rhn.list_packages_in_channel_software(chan_label)
    #print "fetched for",chan_label
    return out

def new_channel_content_fetched(request,result):
    #print "there is a new result for ",result['channel_label']
    buff_packages.append({'channel':result['channel_label'],'packages':result['packages']})
    #print "appends stuff in buff_packages: len(buff_packages)=%i"%len(buff_packages)

def handle_buff_packages(db_cursor):
    out=[]
    while len(buff_packages):
        #print "stuff to process in buff_packages len=%i"%len(buff_packages)
        cur=buff_packages.pop(0)
        #print "and now len=%i"%len(buff_packages)
        cur_channel=cur['channel']
        cur_content=cur['packages']
        #print " dealing with channel=",cur_channel
        for p in cur_content:
            """ package p may already be in the packages table as it appears in several channels"""
            if not globals.is_package_in_db(p['package_id']):

                if 'package_last_modified_date' not in p.keys():
                    snt="insert into Packages ("
                    snt+="package_id,package_arch_label,package_name,package_epoch,package_version,package_release,package_last_modified_date"
                    snt+=") values ("
                    snt+="%(package_id)d,%(package_arch_label)s,%(package_name)s,%(package_epoch)s,%(package_version)s,"
                    snt+="%(package_release)s,NULL"
                    snt+=")"


                    params={"package_id":int(p['package_id']),\
                                "package_arch_label":p['package_arch_label'],\
                                "package_name":p['package_name'],\
                                "package_epoch":p['package_epoch'],\
                                "package_version":p['package_version'],\
                                "package_release":p['package_release']}


                else:
                    modDate=p['package_last_modified_date']
                    snt="insert into Packages ("
                    snt+="package_id,package_arch_label,package_name,package_epoch,package_version,package_release,package_last_modified_date"
                    snt+=") values ("
                    snt+="%(package_id)d,%(package_arch_label)s,%(package_name)s,%(package_epoch)s,%(package_version)s,"
                    snt+="%(package_release)s,%(package_last_modified_date)"
                    snt+=")"


                    params={"package_id":int(p['package_id']),\
                                "package_arch_label":p['package_arch_label'],\
                                "package_name":p['package_name'],\
                                "package_epoch":p['package_epoch'],\
                                "package_version":p['package_version'],\
                                "package_release":p['package_release'],\
                                "package_last_modified_date":modDate}

                insert_stuff(snt,params)
            
            snt="insert into packages_per_channels (package_id,channel_label) "
            snt+="values ( %(package_id)s,%(cur_channel)s )"
            params={"package_id":p['package_id'],"cur_channel":cur_channel}
            insert_stuff(snt,params)


        print "Done for:%s"%cur_channel
        out.append(cur_channel)

    return out
        

def fill_packages():
    """fill the Packages Table"""
    print "-----------------------"
    print "Let's fill package info"
    print "-----------------------"
    todo=globals.select_supported_channels()
    
    #with pgdb , transaction are started automatically
    #but as we just commited one for fill_channels, let s try
    #to start a new one anyway.
    db_cursor=db.cursor()    
    db_cursor.execute("delete from packages_per_channels")

    while len(todo):
        print "todo",len(todo)
        for chanlabel in todo:
            newReq=WorkRequest(list_packages_in_channel_software,\
                               args=[chanlabel],\
                               kwds=None,\
                               requestID=str(time.time())+"-"+chanlabel,\
                               callback=new_channel_content_fetched,\
                               exc_callback=pool_exception)
            pool.putRequest(newReq)



        attempt_cnt=0
        done=[]
        while attempt_cnt<max_attempt:
            time.sleep(1)
            print "attempt_cnt=%i max_attempt=%i"%(attempt_cnt,max_attempt)
            attempt_cnt+=1
            handled=handle_buff_packages(db_cursor)
            for cur_channel in handled:
               done.append(cur_channel)
               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 len(done)==len(todo):
                    break
                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()

            
        newTodo=[]
        for t in todo:
            if t not in done:
                newTodo.append(t)
        todo=newTodo
        print "newTodo:",len(todo)

    print "fill_packages is finished"

    
################ fill_latest_packages ########################
def list_latest_packages_in_channel_software(chan_label):
    #print "Let s fetch latest info for ",chan_label
    #if chan_label==debug_arch:
    #    print "**we request**", debug_arch
    out={}
    out['channel_label']=chan_label
    rhn=rhnapiwrap.rhnapiwrap(rhn_login,rhn_password,rhn_server)
    rhn.login()
    out['packages']=rhn.list_latest_packages_in_channel_software(chan_label)
    return out

def latest_channel_content_fetched(request,result):
    #print "there is a new result for latest ",result['channel_label']
    buff_latest_packages.append({'channel':result['channel_label'],'packages':result['packages']})


def handle_buff_latest_packages():
    out=[]
    while len(buff_latest_packages):
        cur=buff_latest_packages.pop(0)
        channel=cur['channel']
                    
        for package in cur['packages']:
            
            snt="update Packages_Per_Channels set is_latest='t' where "
            snt+="package_id=%(pid)d and channel_label=%(label)s"
            params={"pid":int(package['package_id']),"label":channel}
            insert_stuff(snt,params)

        out.append(channel)
        print "Up2date packages done for",channel
    return out


def fill_latest_packages():
    """updatting Packages_Per_Channels Table"""
    print "-----------------------"
    print "Let's update Packages_Per_Channels with up2date rpms"
    print "-----------------------"
    todo=globals.select_supported_channels()    

    db_cursor=db.cursor()
    db_cursor.execute("update Packages_Per_Channels set is_latest='f'")



    while len(todo):
        for chanlabel in todo:
            newReq=WorkRequest(list_latest_packages_in_channel_software,\
                               args=[chanlabel],\
                               kwds=None,\
                               requestID=str(time.time())+"-"+chanlabel,\
                               callback=latest_channel_content_fetched,\
                               exc_callback=pool_exception)
            pool.putRequest(newReq)



        attempt_cnt=0
        done=[]
        while attempt_cnt<max_attempt:
            time.sleep(1)
            print "attempt_cnt=%i max_attempt=%i"%(attempt_cnt,max_attempt)
            attempt_cnt+=1
            handled=handle_buff_latest_packages()
            for cur_channel in handled:
                done.append(cur_channel)
                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 len(done)==len(todo):
                    break
                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()

    
        newTodo=[]
        for t in todo:
            if t not in done:
                newTodo.append(t)
        todo=newTodo
        print "newTodo;",len(todo)

    print "COMMITING: latest_packages"
    db.commit()
    db_cursor.close()
#######################################################

fill_channels()
fill_packages()
fill_latest_packages()
