use name as agreed with nicta
[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 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  
30 :uid: _slicename_@_hostname_
31 :uri: xmpp://_slicename_-_hostname_-<%= "#{Process.pid}" %>:_slicename_-_hostname_-<%= "#{Process.pid}" %>@_xmpp_server_
32 :environment: production
33 :debug: false
34  
35 :auth:
36   :root_cert_dir: /home/_slicename_/root_certs
37   :entity_cert: /home/_slicename_/entity.crt
38   :entity_key: /home/_slicename_/.ssh/id_rsa
39 """
40
41 # the path where the config is expected from within the sliver
42 yaml_slice_path="/etc/omf_rc/config.yml"
43 # the path for the script that we call when a change occurs
44 omf_rc_trigger_script="omf_rc_plc_trigger"
45
46 ### this returns the kind of virtualization on the node
47 # either 'vs' or 'lxc'
48 # also caches it in /etc/planetlab/virt for next calls
49 # could be promoted to core nm if need be
50 virt_stamp="/etc/planetlab/virt"
51 def get_node_virt ():
52     try:
53         return file(virt_stamp).read().strip()
54     except:
55         pass
56     logger.log("Computing virt..")
57     vs_retcod=subprocess.call ([ 'vserver', '--help' ])
58     if vs_retcod == 0:
59         virt='vs'
60     else:
61         virt='lxc'
62     with file(virt_stamp,"w") as f:
63         f.write(virt)
64     return virt
65
66 def command_in_slice (slicename, argv):
67     # with vserver this can be done using vserver .. exec <trigger-script>
68     # with lxc this is less clear as we are still discussing how lxcsu should behave
69     # ideally we'd need to run lxcsu .. <trigger-script>
70     virt=get_node_virt()
71     if virt=='vs':
72         return [ 'vserver', slicename, 'exec', ] + argv
73     elif virt=='lxc':
74         return [ 'lxcsu', slicename, ] + argv
75     logger.log("command_in_slice: WARNING: could not find a valid virt")
76     return argv
77
78 def GetSlivers(data, conf = None, plc = None):
79     logger.log("omf_resctl.GetSlivers")
80     if 'accounts' not in data:
81         logger.log_missing_data("omf_resctl.GetSlivers",'accounts')
82         return
83
84     try:
85         xmpp_server=data['xmpp']['server']
86         if not xmpp_server: 
87             # we have the key but no value, just as bad
88             raise Exception
89     except:
90         # disabled feature - bailing out
91         logger.log("omf_resctl: PLC_OMF config unsufficient (not enabled, or no server set), -- plugin exiting")
92         return
93
94     hostname = data['hostname']
95
96     def is_omf_friendly (sliver):
97         for chunk in sliver['attributes']:
98             if chunk['tagname']=='omf_control': return True
99
100     for sliver in data['slivers']:
101         # skip non OMF-friendly slices
102         if not is_omf_friendly (sliver): continue
103         slicename=sliver['name']
104         yaml_template = config_ple_template
105         yaml_contents = yaml_template\
106             .replace('_xmpp_server_',xmpp_server)\
107             .replace('_slicename_',slicename)\
108             .replace('_hostname_',hostname)
109         yaml_full_path="/vservers/%s/%s"%(slicename,yaml_slice_path)
110         yaml_full_dir=os.path.dirname(yaml_full_path)
111         if not os.path.isdir(yaml_full_dir):
112             try: os.makedirs(yaml_full_dir)
113             except OSError: pass
114
115         config_changes=tools.replace_file_with_string(yaml_full_path,yaml_contents)
116         logger.log("yaml_contents length=%d, config_changes=%r"%(len(yaml_contents),config_changes))
117         # would make sense to also check for changes to authorized_keys 
118         # would require saving a copy of that some place for comparison
119         # xxx todo
120         keys_changes = False
121         if config_changes or keys_changes:
122             # instead of restarting the service we call a companion script
123             try:
124                 # the trigger script actually needs to be run in the slice context of course
125                 # xxx we might need to use
126                 # slice_command=['bash','-l','-c',omf_rc_trigger_script] 
127                 slice_command = [omf_rc_trigger_script]
128                 to_run = command_in_slice (slicename, slice_command)
129                 sp=subprocess.Popen(to_run, stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
130                 (out,err)=sp.communicate()
131                 retcod=sp.returncode
132                 # we don't wait for that, try to display a retcod for info purpose only
133                 # might be None if that config script lasts or hangs whatever
134                 logger.log("omf_resctl: %s: called OMF rc control script (imm. retcod=%r)"%(slicename,retcod))
135                 logger.log("omf_resctl: got stdout\n%s"%out)
136                 logger.log("omf_resctl: got stderr\n%s"%err)
137             except:
138                 import traceback
139                 traceback.print_exc()
140                 logger.log_exc("omf_resctl: WARNING: Could not call trigger script %s"%\
141                                    omf_rc_trigger_script, name=slicename)
142         else:
143             logger.log("omf_resctl: %s: omf_control'ed sliver has no change" % slicename)