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