root slice needs to come first. Also, emtpy conf file now handled correctly.
[nodemanager.git] / codemux.py
1 # $Id$
2 # $URL$
3
4 """Codemux configurator.  Monitors slice attributes and configures CoDemux to mux port 80 based on HOST field in HTTP request.  Forwards to localhost port belonging to configured slice."""
5
6 import logger
7 import os
8 import vserver
9 from sets import Set
10
11 CODEMUXCONF="/etc/codemux/codemux.conf"
12
13 def start(options, config):
14     pass
15
16
17 def GetSlivers(data):
18     """For each sliver with the codemux attribute, parse out "host,port" and make entry in conf.  Restart service after."""
19     logger.log("codemux:  Starting.", 2)
20     # slices already in conf
21     slicesinconf = parseConf()
22     # slices that need to be written to the conf
23     codemuxslices = {}
24     
25     # XXX Hack for planetflow
26     if slicesinconf.has_key("root"): _writeconf = False
27     else: _writeconf = True
28
29     # Parse attributes and update dict of scripts
30     for sliver in data['slivers']:
31         for attribute in sliver['attributes']:
32             if attribute['name'] == 'codemux':
33                 # add to conf.  Attribute is [host, port]
34                 [host, port] = attribute['value'].split(",")
35                 try:
36                     # Check to see if sliver is running.  If not, continue
37                     if vserver.VServer(sliver['name']).is_running():
38                         # Add to dict of codemuxslices 
39                         codemuxslices[sliver['name']] = {'host': host, 'port': port}
40                         # Check if new
41                         if sliver['name'] not in slicesinconf.keys():
42                             logger.log("codemux:  New slice %s using %s" % \
43                                 (sliver['name'], host))
44                             #  Toggle write.
45                             _writeconf = True
46                         # Check old slivers for changes
47                         else:
48                             # Get info about slice in conf
49                             sliverinconf = slicesinconf[sliver['name']]
50                             # Check values for changes.
51                             if (sliverinconf['host'] != host) or \
52                                 (sliverinconf['port'] != port):
53                                 logger.log("codemux:  Updating slice %s" % sliver['name'])
54                                 # use updated values
55                                 codemuxslices[sliver['name']] = {'host': host, 'port': port}
56                                 #  Toggle write.
57                                 _writeconf = True
58                 except:
59                     logger.log("codemux:  sliver %s not running yet.  Deferring."\
60                                 % sliver['name'])
61
62                     logger.log_exc(name = "codemux")
63                     pass
64
65     # Remove slices from conf that no longer have the attribute
66     for deadslice in Set(slicesinconf.keys()) - Set(codemuxslices.keys()):
67         # XXX Hack for root slice
68         if deadslice != "root": 
69             logger.log("codemux:  Removing %s" % deadslice)
70             _writeconf = True 
71
72     if _writeconf:  writeConf(codemuxslices)
73
74 def writeConf(slivers, conf = CODEMUXCONF):
75     '''Write conf with default entry up top. Restart service.'''
76     f = open(conf, "w")
77     # This needs to be the first entry...
78     f.write("* root 1080\n")
79     for (slice, params) in slivers.iteritems():
80         if slice == "root":  continue
81         f.write("%s %s %s\n" % (params['host'], slice, params['port']))
82     f.truncate()
83     f.close()
84     try:  restartService()
85     except:  logger.log_exc()
86
87 def parseConf(conf = CODEMUXCONF):
88     '''Parse the CODEMUXCONF and return dict of slices in conf. {slice: (host,port)}'''
89     slicesinconf = {} # default
90     try: 
91         f = open(conf)
92         for line in f.readlines():
93             if line.startswith("#") or (len(line.split()) != 3):
94                 continue
95             (host, slice, port) = line.split()[:3]
96             logger.log("codemux:  found %s in conf" % slice, 2)
97             slicesinconf[slice] = {"host": host, "port": port}
98         f.close()
99     except IOError: logger.log_exc()
100     return slicesinconf
101
102 def restartService():
103     logger.log("codemux:  Restarting codemux service")
104     os.system("/etc/init.d/codemux stop")
105     f = os.popen("/sbin/pidof codemux")
106     tmp = f.readlines()
107     f.close()
108     if len(tmp) > 0: 
109         pids = tmp[0].rstrip("\n").split()
110         for pid in pids:
111             logger.log("codemux:  Killing stalled pid %s" % pid, 2)
112             os.kill(pid, 9)
113     os.system("/etc/init.d/codemux start")