f091b82df77b7f730d6d930672a74f5b50faf091
[myplc.git] / bin / plc-kml.py
1 #!/usr/bin/env plcsh
2 #
3 # this script generates a kml file, located under the default location below
4 # you should crontab this job from your myplc image
5 # you can then use the googlemap.js javascript for creating your applet
6 # more on this at http://svn.planet-lab.org/wiki/GooglemapSetup
7
8 # kml reference can be found at
9 # http://code.google.com/apis/kml/documentation/kmlreference.html
10 #
11
12 import sys
13
14 default_output           = "/var/www/html/sites/sites.kml"
15 default_local_icon       = "sites/google-local.png"
16 default_foreign_icon     = "sites/google-foreign.png"
17 default_local_builtin    = "palette-4.png"
18 default_foreign_builtin  = "palette-3.png"
19
20 class KmlMap:
21
22     def __init__ (self,outputname,options):
23         self.outputname=outputname
24         self.options=options
25
26     def open (self):
27         self.output = open(self.outputname,"w")
28
29     def close (self):
30         if self.output:
31             self.output.close()
32         self.output = None
33
34     def write(self,string):
35         self.output.write(string.encode("UTF-8"))
36
37     # mention local last 
38     @staticmethod
39     def site_compare (s1,s2):
40         p1 = p2 = 0
41         if s1['peer_id']: p1=s1['peer_id']
42         if s2['peer_id']: p2=s2['peer_id']
43         return p2-p1
44
45     def refresh (self):
46         self.open()
47         self.write_header()
48         # cache peers 
49         peers = GetPeers()
50         all_sites = GetSites({'enabled':True,'is_public':True})
51         all_sites.sort(KmlMap.site_compare)
52         for site in all_sites:
53             self.write_site(site,peers)
54         self.write_footer()
55         self.close()
56
57 # initial placement is for europe - dunno how to tune that yet
58     def write_header (self):
59         self.write("""<?xml version="1.0" encoding="UTF-8"?>
60 <kml xmlns="http://earth.google.com/kml/2.2">
61 <Document>
62 <name> PlanetLab Sites </name>
63 <LookAt>
64 <longitude>9.180821112577378</longitude>
65 <latitude>44.43275321178062</latitude>
66 <altitude>0</altitude>
67 <range>5782133.196489797</range>
68 <tilt>0</tilt>
69 <heading>-7.767386340832667</heading>
70 </LookAt>
71 <description> All the sites known to the PlanetLab testbed. </description>
72 """)
73
74     def write_footer (self):
75         self.write("""</Document></kml>
76 """)
77
78     def peer_info (self,site, peers):
79         if not site['peer_id']:
80             return (api.config.PLC_NAME, "http://%s/"%api.config.PLC_API_HOST,)
81         for peer in peers:
82             if peer['peer_id'] == site['peer_id']:
83                 return (peer['peername'],peer['peer_url'].replace("PLCAPI/",""),)
84         return "Unknown peer_name"
85
86     def write_site (self, site, peers):
87         # discard sites with missing lat or lon
88         if not site['latitude'] or not site['longitude']:
89             return
90         # discard sites with no nodes 
91         if len(site['node_ids']) == 0:
92             return
93
94         site_id=site['site_id']
95         name=site['name']
96         nb_nodes=len(site['node_ids'])
97         nb_slices=len(site['slice_ids'])
98         latitude=site['latitude']
99         longitude=site['longitude']
100         apiurl='https://%s:443'%api.config.PLC_WWW_HOST
101         baseurl='http://%s'%api.config.PLC_WWW_HOST
102         peer_id=site['peer_id']
103
104         # STYLE
105         # the size for google icons
106         if not self.options.use_custom_icons:
107             if not peer_id:
108                 # local sites
109                 iconfile=default_local_builtin
110                 xyspec="<x>128</x><y>0</y><w>32</w><h>32</h>"
111             else:
112                 # remote
113                 iconfile=default_foreign_builtin
114                 xyspec="<x>160</x><y>0</y><w>32</w><h>32</h>"
115             iconurl="root://icons/%(iconfile)s"%locals()
116         # the size for our own brew of icons
117         else:
118             if not peer_id:
119                 iconfile=self.options.local_icon
120             else:
121                 iconfile=self.options.foreign_icon
122             iconurl="%(baseurl)s/%(iconfile)s"%locals()
123             xyspec=""
124
125         iconspec="<href>%(iconurl)s</href>%(xyspec)s"%locals()
126
127         # open description
128         # can't seem to get classes to get through to the google maps API
129         # so have to use hard-wired settings
130         description = ""
131         description += "<table style='border: 1px solid black; padding: 3px; margin-top:5px;' width='300px'>"
132         description += "<thead></thead><tbody>"
133
134         # TESTBED
135         description += "<tr>"
136         description += "<td style='font-weight: bold'>Testbed</td>"
137         (peername,peerurl) = self.peer_info (site,peers)
138         description += "<td style='vertical-align:middle;'>"
139         description += "<p><img src='%(iconurl)s' style='vertical-align:middle;'/>"%locals()
140         description += "<a href='%(peerurl)s' style='text-decoration:none;vertical-align:middle;'> %(peername)s </a>"%locals()
141         description += "</p></td></tr>"
142
143         # URL
144         if site['url']:
145             site_url=site['url']
146             description += "<tr>"
147             description += "<td style='font-weight: bold'>Website</td>"
148             description += "<td>"
149             description += "<a style='text-decoration: none;' href='%(site_url)s'> %(site_url)s </a>"%locals()
150             description += "</td>"
151             description += "</tr>"
152
153         # Usage area
154         description += "<tr>"
155         description += "<td style='font-weight: bold; margin-bottom:2px;'>Usage</td>"
156
157         # encapsulate usage in a table of its own
158         description += "<td>"
159         description += "<table style=''>"
160         description += "<thead></thead><tbody>"
161
162         # NODES
163         description += "<tr><td align='center'>"
164         description += "<img src='%(apiurl)s/googlemap/node.png'/>"%locals()
165         description += "</td><td>"
166         if nb_nodes:
167             description += "<a style='text-decoration: none;' href='%(apiurl)s/db/nodes/index.php?site_id=%(site_id)d'>%(nb_nodes)d node(s)</a>"%locals()
168             #description += "<a style='text-decoration: none;' href='%(apiurl)s/db/nodes/comon.php?site_id=%(site_id)d'> (in Comon)</a>"%locals()
169         else:
170             description += "<i>No node</i>"
171         description += "</td></tr>"
172
173         #SLICES
174         description += "<tr><td align='center'>"
175         description += "<img src='%(apiurl)s/googlemap/slice.png'/>"%locals()
176         description += "</td><td>"
177         if nb_slices:
178             description += "<a style='text-decoration: none;' href='%(apiurl)s/db/slices/index.php?site_id=%(site_id)d'>%(nb_slices)d slice(s)</a>"%locals()
179         else:
180             description += "<span style='font-style:italic;'>No slice</span>"
181         description += "</td></tr>"
182         
183         # close usage table
184         description += "</tbody></table>"
185         description += "</td></tr>"
186
187         # close description
188         description += "</tbody></table>"
189
190         if not self.options.labels:
191             name=""
192             description=""
193
194         # set the camera 50km high
195         template="""<Placemark>
196 <Style><IconStyle><Icon>%(iconspec)s</Icon></IconStyle></Style>
197 <name><![CDATA[%(name)s]]></name>
198 <LookAt>
199   <latitude>%(latitude)f</latitude>
200   <longitude>%(longitude)f</longitude>
201   <altitude>0</altitude>
202   <altitudeMode>relativeToGround</altitudeMode>              
203   <range>50000.</range> 
204 </LookAt>
205 <description><![CDATA[%(description)s]]></description>
206 <Point> <coordinates>%(longitude)f,%(latitude)f,0</coordinates> </Point>
207 </Placemark>
208 """
209         self.write(template%locals())
210
211 def main () :
212     from optparse import OptionParser
213     usage = "Usage %prog [plcsh-options] [ -- options ]"
214     parser = OptionParser (usage=usage)
215
216     parser.add_option("-o","--output",action="store",dest="output",
217                       default=default_output,
218                       help="output file - default is %s"%default_output)
219     parser.add_option("-n","--no-label",action="store_false",dest="labels",
220                       default=True,
221                       help="outputs only geographic positions, no labels")
222     # default - for private depls. - is to use google-provided icons like palette-3
223     parser.add_option("-c","--custom",action="store_true",dest="use_custom_icons",
224                       default=False,
225                       help="use locally customized icons rather than the %s and %s defaults"%(default_local_builtin,default_foreign_builtin))
226     parser.add_option("-l","--local",action="store",dest="local_icon",
227                       default=default_local_icon,
228                       help="set icon url to use for local sites marker -- requires -c -- default is %s"%default_local_icon)
229     parser.add_option("-f","--foreign",action="store",dest="foreign_icon",
230                       default=default_foreign_icon,
231                       help="set icon url to use for foreign sites marker -- requires -c -- default is %s"%default_foreign_icon)
232
233     (options, args) = parser.parse_args()
234     if len(args) != 0:
235         parser.print_help()
236         sys.exit(1)
237     KmlMap(options.output,options).refresh()
238
239 ####################
240 if __name__ == "__main__":
241     main()