c3f6a26e01590795d57c7a3cd38c047cb2ea5cc6
[sfa.git] / sfa / plc / nodes.py
1 ### $Id$
2 ### $URL$
3
4 import os
5 import time
6 import datetime
7 import sys
8 import traceback
9
10 from sfa.util.misc import *
11 from sfa.util.rspec import *
12 from sfa.util.specdict import * 
13 from sfa.util.faults import *
14 from sfa.util.storage import *
15 from sfa.util.debug import log
16 from sfa.util.rspec import *
17 from sfa.util.specdict import * 
18 from sfa.util.policy import Policy
19 from sfa.server.aggregate import Aggregates 
20
21 class Nodes(SimpleStorage):
22
23     def __init__(self, api, ttl = 1, caller_cred=None):
24         self.api = api
25         self.ttl = ttl
26         self.threshold = None
27         path = self.api.config.SFA_DATA_DIR
28         filename = ".".join([self.api.interface, self.api.hrn, "nodes"])
29         filepath = path + os.sep + filename
30         self.nodes_file = filepath
31         SimpleStorage.__init__(self, self.nodes_file)
32         self.policy = Policy(api)
33         self.load()
34         self.caller_cred=caller_cred
35
36
37     def refresh(self):
38         """
39         Update the cached list of nodes
40         """
41
42         # Reload components list
43         now = datetime.datetime.now()
44         if not self.has_key('threshold') or not self.has_key('timestamp') or \
45            now > datetime.datetime.fromtimestamp(time.mktime(time.strptime(self['threshold'], self.api.time_format))): 
46             if self.api.interface in ['aggregate']:
47                 self.refresh_nodes_aggregate()
48             elif self.api.interface in ['slicemgr']:
49                 self.refresh_nodes_smgr()
50
51     def refresh_nodes_aggregate(self):
52         rspec = RSpec()
53         rspec.parseString(self.get_rspec())
54         
55         # filter nodes according to policy
56         blist = self.policy['node_blacklist']
57         wlist = self.policy['node_whitelist']
58         rspec.filter('NodeSpec', 'name', blacklist=blist, whitelist=wlist)
59
60         # extract ifspecs from rspec to get ips'
61         ips = []
62         ifspecs = rspec.getDictsByTagName('IfSpec')
63         for ifspec in ifspecs:
64             if ifspec.has_key('addr') and ifspec['addr']:
65                 ips.append(ifspec['addr'])
66
67         # extract nodespecs from rspec to get dns names
68         hostnames = []
69         nodespecs = rspec.getDictsByTagName('NodeSpec')
70         for nodespec in nodespecs:
71             if nodespec.has_key('name') and nodespec['name']:
72                 hostnames.append(nodespec['name'])
73
74         # update timestamp and threshold
75         timestamp = datetime.datetime.now()
76         hr_timestamp = timestamp.strftime(self.api.time_format)
77         delta = datetime.timedelta(hours=self.ttl)
78         threshold = timestamp + delta
79         hr_threshold = threshold.strftime(self.api.time_format)
80
81         node_details = {}
82         node_details['rspec'] = rspec.toxml()
83         node_details['ip'] = ips
84         node_details['dns'] = hostnames
85         node_details['timestamp'] = hr_timestamp
86         node_details['threshold'] = hr_threshold
87         # save state 
88         self.update(node_details)
89         self.write()       
90  
91     def get_remote_resources(self, hrn = None):
92         # convert and threshold to ints
93         if self.has_key('timestamp') and self['timestamp']:
94             hr_timestamp = self['timestamp']
95             timestamp = datetime.datetime.fromtimestamp(time.mktime(time.strptime(hr_timestamp, self.api.time_format)))
96             hr_threshold = self['threshold']
97             threshold = datetime.datetime.fromtimestamp(time.mktime(time.strptime(hr_threshold, self.api.time_format)))
98         else:
99             timestamp = datetime.datetime.now()
100             hr_timestamp = timestamp.strftime(self.api.time_format)
101             delta = datetime.timedelta(hours=self.ttl)
102             threshold = timestamp + delta
103             hr_threshold = threshold.strftime(self.api.time_format)
104
105         start_time = int(timestamp.strftime("%s"))
106         end_time = int(threshold.strftime("%s"))
107         duration = end_time - start_time
108
109         aggregates = Aggregates(self.api)
110         rspecs = {}
111         networks = []
112         rspec = RSpec()
113         credential = self.api.getCredential() 
114         for aggregate in aggregates:
115             try:
116                 caller_cred = self.caller_cred
117                 # get the rspec from the aggregate
118                 try:
119                     agg_rspec = aggregates[aggregate].get_resources(credential, hrn, caller_cred)
120                 except:
121                     arg_list = [credential, hrn]
122                     request_hash = self.api.key.compute_hash(arg_list)
123                     agg_rspec = aggregates[aggregate].get_resources(credential, hrn, request_hash, caller_cred)
124                 # extract the netspec from each aggregates rspec
125                 rspec.parseString(agg_rspec)
126                 networks.extend([{'NetSpec': rspec.getDictsByTagName('NetSpec')}])
127             except:
128                 # XX print out to some error log
129                 print >> log, "Error getting resources at aggregate %s" % aggregate
130                 traceback.print_exc(log)
131                 print >> log, "%s" % (traceback.format_exc())
132         # create the rspec dict
133         resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
134         resourceDict = {'RSpec': resources}
135         # convert rspec dict to xml
136         rspec.parseDict(resourceDict)
137         return rspec
138
139     def refresh_nodes_smgr(self):
140
141         rspec = self.get_remote_resources()        
142         # filter according to policy
143         blist = self.policy['node_blacklist']
144         wlist = self.policy['node_whitelist']    
145         rspec.filter('NodeSpec', 'name', blacklist=blist, whitelist=wlist)
146
147         # update timestamp and threshold
148         timestamp = datetime.datetime.now()
149         hr_timestamp = timestamp.strftime(self.api.time_format)
150         delta = datetime.timedelta(hours=self.ttl)
151         threshold = timestamp + delta
152         hr_threshold = threshold.strftime(self.api.time_format)
153
154         nodedict = {'rspec': rspec.toxml(),
155                     'timestamp': hr_timestamp,
156                     'threshold':  hr_threshold}
157
158         self.update(nodedict)
159         self.write()
160
161     def get_rspec(self, hrn = None):
162
163         if self.api.interface in ['slicemgr']:
164             return self.get_rspec_smgr(hrn)
165         elif self.api.interface in ['aggregate']:
166             return self.get_rspec_aggregate(hrn)     
167
168     def get_rspec_smgr(self, hrn = None):
169         
170         rspec = self.get_remote_resources(hrn)
171         return rspec.toxml()
172
173     def get_rspec_aggregate(self, hrn = None):
174         """
175         Get resource information from PLC
176         """
177
178         slicename = None
179         # Get the required nodes
180         if not hrn:
181             nodes = self.api.plshell.GetNodes(self.api.plauth, {'peer_id': None})
182             try:  linkspecs = self.api.plshell.GetLinkSpecs() # if call is supported
183             except:  linkspecs = []
184         else:
185             slicename = hrn_to_pl_slicename(hrn)
186             slices = self.api.plshell.GetSlices(self.api.plauth, [slicename])
187             if not slices:
188                 nodes = []
189             else:
190                 slice = slices[0]
191                 node_ids = slice['node_ids']
192                 nodes = self.api.plshell.GetNodes(self.api.plauth, {'peer_id': None, 'node_id': node_ids})
193
194         # Filter out whitelisted nodes
195         public_nodes = lambda n: n.has_key('slice_ids_whitelist') and not n['slice_ids_whitelist']
196             
197         # ...only if they are not already assigned to this slice.
198         if (not slicename):        
199             nodes = filter(public_nodes, nodes)
200
201         # Get all network interfaces
202         interface_ids = []
203         for node in nodes:
204             # The field name has changed in plcapi 4.3
205             if self.api.plshell_version in ['4.2']:
206                 interface_ids.extend(node['nodenetwork_ids'])
207             elif self.api.plshell_version in ['4.3']:
208                 interface_ids.extend(node['interface_ids'])
209             else:
210                 raise GeniAPIError, "Unsupported plcapi version ", \
211                                  self.api.plshell_version
212
213         if self.api.plshell_version in ['4.2']:
214             interfaces = self.api.plshell.GetNodeNetworks(self.api.plauth, interface_ids)
215         elif self.api.plshell_version in ['4.3']:
216             interfaces = self.api.plshell.GetInterfaces(self.api.plauth, interface_ids)
217         else:
218             raise GeniAPIError, "Unsupported plcapi version ", \
219                                 self.api.plshell_version 
220         interface_dict = {}
221         for interface in interfaces:
222             if self.api.plshell_version in ['4.2']:
223                 interface_dict[interface['nodenetwork_id']] = interface
224             elif self.api.plshell_version in ['4.3']:
225                 interface_dict[interface['interface_id']] = interface
226             else:
227                 raise GeniAPIError, "Unsupported plcapi version", \
228                                     self.api.plshell_version 
229
230         # join nodes with thier interfaces
231         for node in nodes:
232             node['interfaces'] = []
233             if self.api.plshell_version in ['4.2']:
234                 for nodenetwork_id in node['nodenetwork_ids']:
235                     node['interfaces'].append(interface_dict[nodenetwork_id])
236             elif self.api.plshell_version in ['4.3']:
237                 for interface_id in node['interface_ids']:
238                     node['interfaces'].append(interface_dict[interface_id])
239             else:
240                 raise GeniAPIError, "Unsupported plcapi version", \
241                                     self.api.plshell_version
242
243         # convert and threshold to ints
244         if self.has_key('timestamp') and self['timestamp']:
245             timestamp = datetime.datetime.fromtimestamp(time.mktime(time.strptime(self['timestamp'], self.api.time_format)))
246             threshold = datetime.datetime.fromtimestamp(time.mktime(time.strptime(self['threshold'], self.api.time_format)))
247         else:
248             timestamp = datetime.datetime.now()
249             delta = datetime.timedelta(hours=self.ttl)
250             threshold = timestamp + delta
251
252         start_time = int(timestamp.strftime("%s"))
253         end_time = int(threshold.strftime("%s"))
254         duration = end_time - start_time
255
256         # create the plc dict
257         networks = [{'nodes': nodes,
258                      'name': self.api.hrn,
259                      'start_time': start_time,
260                      'duration': duration}]
261         if not hrn:
262             networks[0]['links'] = linkspecs
263         resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
264
265         # convert the plc dict to an rspec dict
266         resourceDict = RSpecDict(resources)
267         # convert the rspec dict to xml
268         rspec = RSpec()
269         rspec.parseDict(resourceDict)
270         return rspec.toxml()
271