change argv syntax : entry URLs are normal args, not options
[sfa.git] / sfa / client / sfascan.py
1 #!/usr/bin/python
2
3 import sys
4 import socket
5 import re
6
7 import pygraphviz
8
9 from optparse import OptionParser
10
11 from sfa.client.sfi import Sfi
12 from sfa.util.sfalogging import sfa_logger,sfa_logger_goes_to_console
13 import sfa.util.xmlrpcprotocol as xmlrpcprotocol
14
15 m_url_with_proto=re.compile("\w+://(?P<hostname>[\w\-\.]+):(?P<port>[0-9]+).*")
16 m_url_without_proto=re.compile("(?P<hostname>[\w\-\.]+):(?P<port>[0-9]+).*")
17 def url_to_hostname_port (url):
18     match=m_url_with_proto.match(url)
19     if match:
20         return (match.group('hostname'),match.group('port'))
21     match=m_url_without_proto.match(url)
22     if match:
23         return (match.group('hostname'),match.group('port'))
24     return ('undefined','???')
25
26 ###
27 class Interface:
28
29     def __init__ (self,url):
30         self._url=url
31         try:
32             (self.hostname,self.port)=url_to_hostname_port(url)
33             self.ip=socket.gethostbyname(self.hostname)
34             self.probed=False
35         except:
36             import traceback
37             traceback.print_exc()
38             self.hostname="unknown"
39             self.ip='0.0.0.0'
40             self.port="???"
41             self.probed=True
42             self._version={}
43
44     def url(self):
45 #        return "http://%s:%s/"%(self.hostname,self.port)
46         return self._url
47
48     # this is used as a key for creating graph nodes and to avoid duplicates
49     def uid (self):
50         return "%s:%s"%(self.ip,self.port)
51
52     # connect to server and trigger GetVersion
53     def get_version(self):
54         if self.probed:
55             return self._version
56         # dummy to meet Sfi's expectations for its 'options' field
57         class DummyOptions:
58             pass
59         options=DummyOptions()
60         options.verbose=False
61         try:
62             client=Sfi(options)
63             client.read_config()
64             key_file = client.get_key_file()
65             cert_file = client.get_cert_file(key_file)
66             url="http://%s:%s/"%(self.hostname,self.port)
67             sfa_logger().info('issuing get version at %s'%url)
68             server=xmlrpcprotocol.get_server(url, key_file, cert_file, options)
69             self._version=server.GetVersion()
70         except:
71             self._version={}
72         self.probed=True
73         return self._version
74
75     # default is for when we can't determine the type of the service
76     # typically the server is down, or we can't authenticate, or it's too old code
77     shapes = {"registry": "diamond", "slicemgr":"ellipse", "aggregate":"box", 'default':'plaintext'}
78
79     def get_label(self):
80         version=self.get_version()
81         if 'hrn' not in version: return self.url()
82         hrn=version['hrn']
83         result=hrn
84         if 'code_tag' in version: 
85             result += " %s"%version['code_tag']
86         if 'testbed' in version:
87             # could not get so-called HTML-like labels to work
88             #"<TABLE><TR><TD>%s</TD></TR><TR><TD>%s</TD></TR></TABLE>"%(result,version['testbed'])
89             result += " (%s)"%version['testbed']
90         return result
91
92     def get_shape(self):
93         default=Interface.shapes['default']
94         try:
95             version=self.get_version()
96             return Interface.shapes.get(version['interface'],default)
97         except:
98             return default
99
100 class SfaScan:
101
102     # provide the entry points (a list of interfaces)
103     def __init__ (self):
104         pass
105
106     def graph (self,entry_points):
107         graph=pygraphviz.AGraph(directed=True)
108         self.scan(entry_points,graph)
109         return graph
110     
111     # scan from the given interfaces as entry points
112     def scan(self,interfaces,graph):
113         if not isinstance(interfaces,list):
114             interfaces=[interfaces]
115
116         # remember node to interface mapping
117         node2interface={}
118         # add entry points right away using the interface uid's as a key
119         to_scan=interfaces
120         for i in interfaces: 
121             graph.add_node(i.uid())
122             node2interface[graph.get_node(i.uid())]=i
123         scanned=[]
124         # keep on looping until we reach a fixed point
125         # don't worry about abels and shapes that will get fixed later on
126         while to_scan:
127             for interface in to_scan:
128                 # performing xmlrpc call
129                 version=interface.get_version()
130                 # 'sfa' is expected if the call succeeded at all
131                 # 'peers' is needed as well as AMs typically don't have peers
132                 if 'sfa' in version and 'peers' in version: 
133                     # proceed with neighbours
134                     for (next_name,next_url) in version['peers'].items():
135                         next_interface=Interface(next_url)
136                         # locate or create node in graph
137                         try:
138                             # if found, we're good with this one
139                             next_node=graph.get_node(next_interface.uid())
140                         except:
141                             # otherwise, let's move on with it
142                             graph.add_node(next_interface.uid())
143                             next_node=graph.get_node(next_interface.uid())
144                             node2interface[next_node]=next_interface
145                             to_scan.append(next_interface)
146                         graph.add_edge(interface.uid(),next_interface.uid())
147                 scanned.append(interface)
148                 to_scan.remove(interface)
149             # we've scanned the whole graph, let's get the labels and shapes right
150             for node in graph.nodes():
151                 interface=node2interface.get(node,None)
152                 if interface:
153                     node.attr['label']=interface.get_label()
154                     node.attr['shape']=interface.get_shape()
155                     node.attr['href']=interface.url()
156                 else:
157                     sfa_logger().info("MISSED interface with node %s"%node)
158     
159
160 default_outfiles=['sfa.png','sfa.svg','sfa.dot']
161
162 def main():
163     sfa_logger_goes_to_console()
164     usage="%prog [options] url-entry-point(s)"
165     parser=OptionParser(usage=usage)
166     parser.add_option("-o","--output",action='append',dest='outfiles',default=[],
167                       help="output filenames (cumulative) - defaults are %r"%default_outfiles)
168     (options,args)=parser.parse_args()
169     if not args:
170         parser.print_help()
171         sys.exit(1)
172     if not options.outfiles:
173         options.outfiles=default_outfiles
174     scanner=SfaScan()
175     entries = [ Interface(entry) for entry in args ]
176     g=scanner.graph(entries)
177     sfa_logger().info("creating layout")
178     g.layout(prog='dot')
179     for outfile in options.outfiles:
180         sfa_logger().info("drawing in %s"%outfile)
181         g.draw(outfile)
182     sfa_logger().info("done")
183
184 if __name__ == '__main__':
185     main()