have omf_resctl run after sliverauth
[nodemanager.git] / plugins / omf_resctl.py
1 #
2 # NodeManager plugin - first step of handling omf_controlled slices
3 #
4
5 """
6 Overwrites the 'resctl' tag of slivers controlled by OMF so slivermanager.py does the right thing
7 """
8
9 import os, os.path
10 import glob
11 import subprocess
12
13 import tools
14 import logger
15
16 # we need this to run after sliverauth
17 priority = 150
18
19 def start():
20     pass
21
22 ### the new template for OMF v6
23 # hard-wire this for now
24 # once the variables are expanded, this is expected to go into
25 config_ple_template="""---
26 # Example:
27 # _slicename_ = nicta_ruby
28 # _hostname_ = planetlab1.research.nicta.com.au
29 # _xmpp_server_ = xmpp.planet-lab.eu
30 # we extract expires time here, even in a comment so that the
31 # trigger script gets called whenever this changes
32 # expires: _expires_
33  
34 :uid: _slicename_@_hostname_
35 :uri: xmpp://_slicename_-_hostname_-<%= "#{Process.pid}" %>:_slicename_-_hostname_-<%= "#{Process.pid}" %>@_xmpp_server_
36 :environment: production
37 :debug: false
38  
39 :auth:
40   :root_cert_dir: /home/_slicename_/root_certs
41   :entity_cert: /home/_slicename_/entity.crt
42   :entity_key: /home/_slicename_/.ssh/id_rsa
43 """
44
45 # the path where the config is expected from within the sliver
46 yaml_slice_path="/etc/omf_rc/config.yml"
47 # the path for the script that we call when a change occurs
48 # given that we're now responsible for fetching this one, I have to
49 # decide on an actual path - not jsut a name to search for in PATH
50 omf_rc_trigger_script="/usr/bin/plc_trigger_omf_rc"
51
52 # hopefully temporary: when trigger script is missing, fetch it at the url here
53 omf_rc_trigger_url="http://git.mytestbed.net/?p=omf.git;a=blob_plain;f=omf_rc/bin/plc_trigger_omf_rc;hb=HEAD"
54 def fetch_trigger_script_if_missing (slicename):
55     full_path="/vservers/%s/%s"%(slicename,omf_rc_trigger_script)
56     if not os.path.isfile (full_path):
57         retcod=subprocess.call (['curl','--silent','-o',full_path,omf_rc_trigger_url])
58         if retcod!=0:
59             logger.log("Could not fetch %s"%omf_rc_trigger_url)
60         else:
61             subprocess.call(['chmod','+x',full_path])
62             logger.log("omf_resctl: fetched %s"%(full_path))
63             logger.log("omf_resctl: from %s"%(omf_rc_trigger_url))
64
65 def GetSlivers(data, conf = None, plc = None):
66     logger.log("omf_resctl.GetSlivers")
67     if 'accounts' not in data:
68         logger.log_missing_data("omf_resctl.GetSlivers",'accounts')
69         return
70
71     try:
72         xmpp_server=data['xmpp']['server']
73         if not xmpp_server: 
74             # we have the key but no value, just as bad
75             raise Exception
76     except:
77         # disabled feature - bailing out
78         logger.log("omf_resctl: PLC_OMF config unsufficient (not enabled, or no server set), -- plugin exiting")
79         return
80
81     hostname = data['hostname']
82
83     def is_omf_friendly (sliver):
84         for chunk in sliver['attributes']:
85             if chunk['tagname']=='omf_control': return True
86
87     for sliver in data['slivers']:
88         # skip non OMF-friendly slices
89         if not is_omf_friendly (sliver): continue
90         slicename=sliver['name']
91         expires=str(sliver['expires'])
92         yaml_template = config_ple_template
93         yaml_contents = yaml_template\
94             .replace('_xmpp_server_',xmpp_server)\
95             .replace('_slicename_',slicename)\
96             .replace('_hostname_',hostname)\
97             .replace('_expires_',expires)
98         yaml_full_path="/vservers/%s/%s"%(slicename,yaml_slice_path)
99         yaml_full_dir=os.path.dirname(yaml_full_path)
100         if not os.path.isdir(yaml_full_dir):
101             try: os.makedirs(yaml_full_dir)
102             except OSError: pass
103
104         config_changes=tools.replace_file_with_string(yaml_full_path,yaml_contents)
105         logger.log("yaml_contents length=%d, config_changes=%r"%(len(yaml_contents),config_changes))
106         # would make sense to also check for changes to authorized_keys 
107         # would require saving a copy of that some place for comparison
108         # xxx todo
109         keys_changes = False
110         if config_changes or keys_changes:
111             # instead of restarting the service we call a companion script
112             try:
113                 fetch_trigger_script_if_missing (slicename)
114                 # the trigger script actually needs to be run in the slice context of course
115                 slice_command = [ "sudo", "-i",  omf_rc_trigger_script ]
116                 to_run = tools.command_in_slice (slicename, slice_command)
117                 logger.log("command_in_slice: %s"%to_run)
118                 sp=subprocess.Popen(to_run, stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
119                 (out,err)=sp.communicate()
120                 retcod=sp.returncode
121                 # we don't wait for that, try to display a retcod for info purpose only
122                 # might be None if that config script lasts or hangs whatever
123                 logger.log("omf_resctl: %s: called OMF rc control script (imm. retcod=%r)"%(slicename,retcod))
124                 logger.log("omf_resctl: got stdout\n%s"%out)
125                 logger.log("omf_resctl: got stderr\n%s"%err)
126             except:
127                 import traceback
128                 traceback.print_exc()
129                 logger.log_exc("omf_resctl: WARNING: Could not call trigger script %s"%\
130                                    omf_rc_trigger_script, name=slicename)
131         else:
132             logger.log("omf_resctl: %s: omf_control'ed sliver has no change" % slicename)