#!/usr/bin/env python
# encoding: utf-8
"""
supervisor.py

Created by Thomas Mangin on 2009-08-25.
Copyright (c) 2009 Exa Networks. All rights reserved.
"""

import time
import signal

from bgp.data import Notification
from bgp.protocol import Protocol,Network
from bgp.peer import Peer

class Supervisor (object):
	debug = True
	
	# [hex(ord(c)) for c in os.popen('clear').read()]
	clear = ''.join([chr(int(c,16)) for c in ['0x1b', '0x5b', '0x48', '0x1b', '0x5b', '0x32', '0x4a']])
	
	def __init__ (self,configuration):
		self.configuration = configuration
		self._peers = {}
		self._shutdown = False
		self.reload()
		
		signal.signal(signal.SIGTERM, self.sigterm)
		signal.signal(signal.SIGHUP, self.sighup)
	
	def sigterm (self,signum, frame):
		print "SIG TERM received"
		self.shutdown()

	def sighup (self,signum, frame):
		print "SIG TERM received"
		self.reload()
	
	def run (self):
		start = time.time()
		while self._peers:
			try:
				for ip in self._peers.keys():
					peer = self._peers[ip]
					peer.run()
				if self._shutdown:
					for ip in self._peers.keys():
						self._peers[ip].shutdown()
				# MUST not more than one KEEPALIVE / sec
				time.sleep(1.0)
			except KeyboardInterrupt:
				if self.debug: print "^C received"
				self.shutdown()
	
	def _add_peer (self,neighbor):
		ip = neighbor.peer_address.human()
		assert ip not in self._peers
		network = Network(ip)
		peer = Peer(Protocol(neighbor,network),self)
		self._peers[ip] = peer

	def reload (self):
		self.configuration.reload()
		for ip in self._peers.keys():
			if ip not in self.configuration.neighbor:
				self._peers[ip].shutdown()
		
		for _,neighbor in self.configuration.neighbor.iteritems():
			ip = neighbor.peer_address.human()
			if ip in self._peers:
				continue
			self._add_peer(neighbor)
		
	def shutdown (self):
		self._shutdown = True
	
	def unschedule (self,ip):
		del self._peers[ip]
@@ -595,16 +595,39 @@
 = False%0A
+%09%09self._reload = False%0A
 %09%09self.r
@@ -634,16 +634,16 @@
 eload()%0A
-
 %09%09%0A%09%09sig
@@ -850,36 +850,35 @@
 ):%0A%09%09print %22SIG 
-TERM
+HUP
  received%22%0A%09%09sel
@@ -879,24 +879,30 @@
 %0A%09%09self.
+_
 reload
-()
+ = True
 %0A%09%0A%09def 
@@ -1129,24 +1129,64 @@
 .shutdown()%0A
+%09%09%09%09if self._reload:%0A%09%09%09%09%09self.reload()%0A
 %09%09%09%09# MUST n
@@ -1541,24 +1541,47 @@
 oad (self):%0A
+%09%09self._reload = False%0A
 %09%09self.confi
@@ -1637,17 +1637,99 @@
 %0A%09%09%09
-if ip not
+print ip, %5Bn.human() for n in self.configuration.neighbor%5D%0A%09%09%09if ip not in %5Bn.human() for n
  in 
@@ -1755,16 +1755,17 @@
 neighbor
+%5D
 :%0A%09%09%09%09se

fix bugs in last commit