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):
27 path = self.api.config.config_path
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)
38 Update the cached list of nodes
41 # Reload components list
42 now = datetime.datetime.now()
43 if not self.has_key('threshold') or not self.has_key('timestamp') or \
44 now > datetime.datetime.fromtimestamp(time.mktime(time.strptime(self['threshold'], self.api.time_format))):
45 if self.api.interface in ['aggregate']:
46 self.refresh_nodes_aggregate()
47 elif self.api.interface in ['slicemgr']:
48 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 refresh_nodes_smgr(self):
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 # get the rspec from the aggregate
117 agg_rspec = aggregates[aggregate].get_resources(credential)
118 # extract the netspec from each aggregates rspec
119 rspec.parseString(agg_rspec)
120 networks.extend([{'NetSpec': rspec.getDictsByTagName('NetSpec')}])
122 # XX print out to some error log
123 print >> log, "Error calling list nodes at aggregate %s" % aggregate
124 traceback.print_exc(log)
125 exc_type, exc_value, exc_traceback = sys.exc_info()
126 raise exc_type, exc_value
127 # create the rspec dict
128 resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
129 resourceDict = {'Rspec': resources}
130 # convert rspec dict to xml
131 rspec.parseDict(resourceDict)
133 # filter according to policy
134 blist = self.policy['node_blacklist']
135 wlist = self.policy['node_whitelist']
136 rspec.filter('NodeSpec', 'name', blacklist=blist, whitelist=wlist)
138 # update timestamp and threshold
139 timestamp = datetime.datetime.now()
140 hr_timestamp = timestamp.strftime(self.api.time_format)
141 delta = datetime.timedelta(hours=self.ttl)
142 threshold = timestamp + delta
143 hr_threshold = threshold.strftime(self.api.time_format)
145 nodedict = {'rspec': rspec.toxml(),
146 'timestamp': hr_timestamp,
147 'threshold': hr_threshold}
149 self.update(nodedict)
153 def get_rspec(self, hrn = None):
155 Get resource information from PLC
158 # Get the required nodes
160 nodes = self.api.plshell.GetNodes(self.api.plauth, {'peer_id': None})
161 try: linkspecs = self.api.plshell.GetLinkSpecs() # if call is supported
162 except: linkspecs = []
164 slicename = hrn_to_pl_slicename(hrn)
165 slices = self.api.plshell.GetSlices(self.api.plauth, [slicename])
170 node_ids = slice['node_ids']
171 nodes = self.api.plshell.GetNodes(self.api.plauth, {'peer_id': None, 'node_id': node_ids})
173 # Filter out whitelisted nodes
174 public_nodes = lambda n: n.has_key('slice_ids_whitelist') and not n['slice_ids_whitelist']
175 nodes = filter(public_nodes, nodes)
177 # Get all network interfaces
180 # The field name has changed in plcapi 4.3
181 if self.api.plshell_version in ['4.2']:
182 interface_ids.extend(node['nodenetwork_ids'])
183 elif self.api.plshell_version in ['4.3']:
184 interface_ids.extend(node['interface_ids'])
186 raise GeniAPIError, "Unsupported plcapi version ", \
187 self.api.plshell_version
189 if self.api.plshell_version in ['4.2']:
190 interfaces = self.api.plshell.GetNodeNetworks(self.api.plauth, interface_ids)
191 elif self.api.plshell_version in ['4.3']:
192 interfaces = self.api.plshell.GetInterfaces(self.api.plauth, interface_ids)
194 raise GeniAPIError, "Unsupported plcapi version ", \
195 self.api.plshell_version
197 for interface in interfaces:
198 if self.api.plshell_version in ['4.2']:
199 interface_dict[interface['nodenetwork_id']] = interface
200 elif self.api.plshell_version in ['4.3']:
201 interface_dict[interface['interface_id']] = interface
203 raise GeniAPIError, "Unsupported plcapi version", \
204 self.api.plshell_version
206 # join nodes with thier interfaces
208 node['interfaces'] = []
209 if self.api.plshell_version in ['4.2']:
210 for nodenetwork_id in node['nodenetwork_ids']:
211 node['interfaces'].append(interface_dict[nodenetwork_id])
212 elif self.api.plshell_version in ['4.3']:
213 for interface_id in node['interface_ids']:
214 node['interfaces'].append(interface_dict[interface_id])
216 raise GeniAPIError, "Unsupported plcapi version", \
217 self.api.plshell_version
219 # convert and threshold to ints
220 if self.has_key('timestamp') and self['timestamp']:
221 timestamp = datetime.datetime.fromtimestamp(time.mktime(time.strptime(self['timestamp'], self.api.time_format)))
222 threshold = datetime.datetime.fromtimestamp(time.mktime(time.strptime(self['threshold'], self.api.time_format)))
224 timestamp = datetime.datetime.now()
225 delta = datetime.timedelta(hours=self.ttl)
226 threshold = timestamp + delta
228 start_time = int(timestamp.strftime("%s"))
229 end_time = int(threshold.strftime("%s"))
230 duration = end_time - start_time
232 # create the plc dict
233 networks = [{'nodes': nodes,
234 'name': self.api.hrn,
235 'start_time': start_time,
236 'duration': duration}]
238 networks[0]['links'] = linkspecs
239 resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
241 # convert the plc dict to an rspec dict
242 resourceDict = RspecDict(resources)
243 # convert the rspec dict to xml
245 rspec.parseDict(resourceDict)