#!/usr/bin/env python

###########################################
#
#  This script is called by torque when the
# user's job is done.  It will destroy the 
# VM.
#
###########################################

#import libvirt
import smtplib
import os
import sys
import re
import ConfigParser

try:
    import sqlite3
except:
    from pysqlite2 import dbapi2 as sqlite3

#parameters.
config = ConfigParser.ConfigParser()
config.read('/etc/torque-kvm.conf')
torque_home=config.get("torque","torque_home")
dbfile=torque_home + "/net/network.db"
vmrundir = config.get("virt", "vmrundir")


# epilogue gets 9 arguments:
# 1 -- jobid
# 2 -- userid
# 3 -- grpid
# 4 -- jobname
# 5 -- session id
# 6 -- list of requested resource limits
# 7 -- list of resources used by job
# 8 -- job execution queue
# 9 -- job account
# 10 -- job exit code

jobid=sys.argv[1]
userid=sys.argv[2]
grpid=sys.argv[3]
jobname=sys.argv[4]
sessionid=sys.argv[5]
requested_resources=sys.argv[6]
used_resources=sys.argv[7]
jobqueue=sys.argv[8]
jobaccnt=sys.argv[9]
exitcode=sys.argv[10]

print '''
------------------------------------------------------------------
TORQUE EPILOGUE:
  jobid:          '''+jobid+'''
  userid:         '''+userid+'''
  groupid:        '''+grpid+'''
  job name:       '''+jobname+'''
  session id:     '''+sessionid+'''
  used resources: '''+used_resources+'''
  queue:          '''+jobqueue+'''
  exit code:      '''+exitcode


bits=jobid.split('.')
uuid='vm-'+bits[0]
target_hostfile=torque_home+"/virt/"+jobid


#destroy the vm
#conn = libvirt.open(None)
#if conn == None:
#    print 'Failed to open connection to the hypervisor'    
#    sys.exit(1)


try:
    os.system('kill $(ps ax|grep '+uuid+'|grep -v grep|cut -f1 -d " ")')
    os.system('/sbin/ifconfig '+uuid+' down')
    os.system('/usr/sbin/tunctl -d '+uuid+'>/dev/null')
except:
	# no vm for a baremetal session
	print '''------------------------------------------------------------------'''
	sys.exit(0)

#if dom.shutdown() != 0:
#    print 'Failed to shutdown domain... destroying'
#    dom.destroy()

#del dom
#del conn

print "  domain " + uuid + " destroyed"

#get the entry from the host file
host = open(target_hostfile,'r').read()

#add the entry back into the db
conn=sqlite3.connect(dbfile)
c=conn.cursor()
c.execute("update reservations set inuse = 0 where hostname=?",[host])
conn.commit()
c.close()

#delete the image file
os.remove(vmrundir+'/'+uuid)

#try to remove the scratch space, if it's there.
try:
	os.remove(vmrundir+'/'+uuid+'.scratch')
except:
	pass

#delete the job file and script:
os.remove(target_hostfile)

print '''------------------------------------------------------------------
'''
#all done!
