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