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
21 class Nodes(SimpleStorage):
23 def __init__(self, api, ttl = 1, caller_cred=None):
27 path = self.api.config.SFA_BASE_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)
34 self.caller_cred=caller_cred
39 Update the cached list of nodes
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()
51 def refresh_nodes_aggregate(self):
53 rspec.parseString(self.get_rspec())
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)
60 # extract ifspecs from rspec to get 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'])
67 # extract nodespecs from rspec to get dns names
69 nodespecs = rspec.getDictsByTagName('NodeSpec')
70 for nodespec in nodespecs:
71 if nodespec.has_key('name') and nodespec['name']:
72 hostnames.append(nodespec['name'])
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)
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
88 self.update(node_details)
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)))
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)
105 start_time = int(timestamp.strftime("%s"))
106 end_time = int(threshold.strftime("%s"))
107 duration = end_time - start_time
109 aggregates = Aggregates(self.api)
113 credential = self.api.getCredential()
114 for aggregate in aggregates:
116 caller_cred = self.caller_cred
117 arg_list = [credential, hrn]
118 request_hash = self.api.key.compute_hash(arg_list)
120 # get the rspec from the aggregate
121 agg_rspec = aggregates[aggregate].get_resources(credential, hrn, request_hash, caller_cred)
122 # extract the netspec from each aggregates rspec
123 rspec.parseString(agg_rspec)
124 networks.extend([{'NetSpec': rspec.getDictsByTagName('NetSpec')}])
126 # XX print out to some error log
127 print >> log, "Error getting resources at aggregate %s" % aggregate
128 traceback.print_exc(log)
129 print >> log, "%s" % (traceback.format_exc())
130 # create the rspec dict
131 resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
132 resourceDict = {'RSpec': resources}
133 # convert rspec dict to xml
134 rspec.parseDict(resourceDict)
137 def refresh_nodes_smgr(self):
139 rspec = self.get_remote_resources()
140 # filter according to policy
141 blist = self.policy['node_blacklist']
142 wlist = self.policy['node_whitelist']
143 rspec.filter('NodeSpec', 'name', blacklist=blist, whitelist=wlist)
145 # update timestamp and threshold
146 timestamp = datetime.datetime.now()
147 hr_timestamp = timestamp.strftime(self.api.time_format)
148 delta = datetime.timedelta(hours=self.ttl)
149 threshold = timestamp + delta
150 hr_threshold = threshold.strftime(self.api.time_format)
152 nodedict = {'rspec': rspec.toxml(),
153 'timestamp': hr_timestamp,
154 'threshold': hr_threshold}
156 self.update(nodedict)
159 def get_rspec(self, hrn = None):
161 if self.api.interface in ['slicemgr']:
162 return self.get_rspec_smgr(hrn)
163 elif self.api.interface in ['aggregate']:
164 return self.get_rspec_aggregate(hrn)
166 def get_rspec_smgr(self, hrn = None):
168 rspec = self.get_remote_resources(hrn)
171 def get_rspec_aggregate(self, hrn = None):
173 Get resource information from PLC
176 # Get the required nodes
178 nodes = self.api.plshell.GetNodes(self.api.plauth, {'peer_id': None})
179 try: linkspecs = self.api.plshell.GetLinkSpecs() # if call is supported
180 except: linkspecs = []
182 slicename = hrn_to_pl_slicename(hrn)
183 slices = self.api.plshell.GetSlices(self.api.plauth, [slicename])
188 node_ids = slice['node_ids']
189 nodes = self.api.plshell.GetNodes(self.api.plauth, {'peer_id': None, 'node_id': node_ids})
191 # Filter out whitelisted nodes
192 public_nodes = lambda n: n.has_key('slice_ids_whitelist') and not n['slice_ids_whitelist']
193 nodes = filter(public_nodes, nodes)
195 # Get all network interfaces
198 # The field name has changed in plcapi 4.3
199 if self.api.plshell_version in ['4.2']:
200 interface_ids.extend(node['nodenetwork_ids'])
201 elif self.api.plshell_version in ['4.3']:
202 interface_ids.extend(node['interface_ids'])
204 raise GeniAPIError, "Unsupported plcapi version ", \
205 self.api.plshell_version
207 if self.api.plshell_version in ['4.2']:
208 interfaces = self.api.plshell.GetNodeNetworks(self.api.plauth, interface_ids)
209 elif self.api.plshell_version in ['4.3']:
210 interfaces = self.api.plshell.GetInterfaces(self.api.plauth, interface_ids)
212 raise GeniAPIError, "Unsupported plcapi version ", \
213 self.api.plshell_version
215 for interface in interfaces:
216 if self.api.plshell_version in ['4.2']:
217 interface_dict[interface['nodenetwork_id']] = interface
218 elif self.api.plshell_version in ['4.3']:
219 interface_dict[interface['interface_id']] = interface
221 raise GeniAPIError, "Unsupported plcapi version", \
222 self.api.plshell_version
224 # join nodes with thier interfaces
226 node['interfaces'] = []
227 if self.api.plshell_version in ['4.2']:
228 for nodenetwork_id in node['nodenetwork_ids']:
229 node['interfaces'].append(interface_dict[nodenetwork_id])
230 elif self.api.plshell_version in ['4.3']:
231 for interface_id in node['interface_ids']:
232 node['interfaces'].append(interface_dict[interface_id])
234 raise GeniAPIError, "Unsupported plcapi version", \
235 self.api.plshell_version
237 # convert and threshold to ints
238 if self.has_key('timestamp') and self['timestamp']:
239 timestamp = datetime.datetime.fromtimestamp(time.mktime(time.strptime(self['timestamp'], self.api.time_format)))
240 threshold = datetime.datetime.fromtimestamp(time.mktime(time.strptime(self['threshold'], self.api.time_format)))
242 timestamp = datetime.datetime.now()
243 delta = datetime.timedelta(hours=self.ttl)
244 threshold = timestamp + delta
246 start_time = int(timestamp.strftime("%s"))
247 end_time = int(threshold.strftime("%s"))
248 duration = end_time - start_time
250 # create the plc dict
251 networks = [{'nodes': nodes,
252 'name': self.api.hrn,
253 'start_time': start_time,
254 'duration': duration}]
256 networks[0]['links'] = linkspecs
257 resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
259 # convert the plc dict to an rspec dict
260 resourceDict = RSpecDict(resources)
261 # convert the rspec dict to xml
263 rspec.parseDict(resourceDict)