]> git.openstreetmap.org Git - chef.git/blob - cookbooks/tile/templates/default/export.erb
Get rid of the last traces of old style apache auth directives
[chef.git] / cookbooks / tile / templates / default / export.erb
1 #!/usr/bin/python -u
2 # -*- coding: utf-8 -*-
3
4 import cairo
5 import cgi
6 import mapnik
7 import os
8 import shutil
9 import sys
10 import tempfile
11 import resource
12
13 # Limit maximum CPU time
14 # The Postscript output format can sometimes take hours
15 resource.setrlimit(resource.RLIMIT_CPU,(180,180))
16
17 # Limit memory usage
18 # Some odd requests can cause extreme memory usage
19 resource.setrlimit(resource.RLIMIT_AS,(4000000000, 4000000000))
20
21 # Routine to output HTTP headers
22 def output_headers(content_type, filename = "", length = 0):
23   print "Content-Type: %s" % content_type
24   if filename:
25     print "Content-Disposition: attachment; filename=\"%s\"" % filename
26   if length:
27     print "Content-Length: %d" % length
28   print ""
29
30 # Routine to output the contents of a file
31 def output_file(file):
32   file.seek(0)
33   shutil.copyfileobj(file, sys.stdout)
34
35 # Routine to get the size of a file
36 def file_size(file):
37   return os.fstat(file.fileno()).st_size
38
39 # Routine to report an error
40 def output_error(message):
41   output_headers("text/html")
42   print "<html>"
43   print "<head>"
44   print "<title>Error</title>"
45   print "</head>"
46   print "<body>"
47   print "<h1>Error</h1>"
48   print "<p>%s</p>" % message
49   print "</body>"
50   print "</html>"
51
52 # Parse CGI parameters
53 form = cgi.FieldStorage()
54
55 # Make sure we have a user agent
56 if not os.environ.has_key('HTTP_USER_AGENT'):
57   os.environ['HTTP_USER_AGENT'] = 'NONE'
58
59 # Get the load average
60 cputimes = [float(n) for n in open("/proc/stat").readline().rstrip().split()[1:-1]]
61 idletime = cputimes[3] / sum(cputimes)
62
63 # Process the request
64 if idletime < 0.2:
65   # Abort if the CPU idle time on the machine is too low
66   print "Status: 503 Service Unavailable"
67   output_error("The server is too busy at the moment. Please wait a few minutes before trying again.")
68 <% @blocks["user_agents"].each do |user_agent| -%>
69 elif os.environ['HTTP_USER_AGENT'] == '<%= user_agent %>':
70   # Block scraper
71   print "Status: 503 Service Unavailable"
72   output_error("The server is too busy at the moment. Please wait a few minutes before trying again.")
73 <% end -%>
74 elif not form.has_key("bbox"):
75   # No bounding box specified
76   output_error("No bounding box specified")
77 elif not form.has_key("scale"):
78   # No scale specified
79   output_error("No scale specified")
80 elif not form.has_key("format"):
81   # No format specified
82   output_error("No format specified")
83 else:
84   # Create projection object
85   prj = mapnik.Projection("+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over");
86
87   # Get the bounds of the area to render
88   bbox = [float(x) for x in form.getvalue("bbox").split(",")]
89
90   if bbox[0] >= bbox[2] or bbox[1] >= bbox[3]:
91     # Bogus bounding box
92     output_error("Invalid bounding box")
93   else:
94     # Project the bounds to the map projection
95     bbox = mapnik.forward_(mapnik.Box2d(*bbox), prj)
96
97     # Get the style to use
98     style = form.getvalue("style", "default")
99
100     # Calculate the size of the final rendered image
101     scale = float(form.getvalue("scale"))
102     width = int(bbox.width() / scale / 0.00028)
103     height = int(bbox.height() / scale / 0.00028)
104
105     # Limit the size of map we are prepared to produce
106     if width * height > 4000000:
107       # Map is too large (limit is approximately A2 size)
108       output_error("Map too large")
109     else:
110       # Create map
111       map = mapnik.Map(width, height)
112
113       # Load map configuration
114       mapnik.load_map(map, "/srv/tile.openstreetmap.org/styles/%s/project.xml" % style)
115
116       # Zoom the map to the bounding box
117       map.zoom_to_box(bbox)
118
119       # Render the map
120       if form.getvalue("format") == "png":
121         image = mapnik.Image(map.width, map.height)
122         mapnik.render(map, image)
123         png = image.tostring("png")
124         output_headers("image/png", "map.png", len(png))
125         sys.stdout.write(png)
126       elif form.getvalue("format") == "jpeg":
127         image = mapnik.Image(map.width, map.height)
128         mapnik.render(map, image)
129         jpeg = image.tostring("jpeg")
130         output_headers("image/jpeg", "map.jpg", len(jpeg))
131         sys.stdout.write(jpeg)
132       elif form.getvalue("format") == "svg":
133         file = tempfile.NamedTemporaryFile(prefix = "export")
134         surface = cairo.SVGSurface(file.name, map.width, map.height)
135         mapnik.render(map, surface)
136         surface.finish()
137         output_headers("image/svg+xml", "map.svg", file_size(file))
138         output_file(file)
139       elif form.getvalue("format") == "pdf":
140         file = tempfile.NamedTemporaryFile(prefix = "export")
141         surface = cairo.PDFSurface(file.name, map.width, map.height)
142         mapnik.render(map, surface)
143         surface.finish()
144         output_headers("application/pdf", "map.pdf", file_size(file))
145         output_file(file)
146       elif form.getvalue("format") == "ps":
147         file = tempfile.NamedTemporaryFile(prefix = "export")
148         surface = cairo.PSSurface(file.name, map.width, map.height)
149         mapnik.render(map, surface)
150         surface.finish()
151         output_headers("application/postscript", "map.ps", file_size(file))
152         output_file(file)
153       else:
154         output_error("Unknown format '%s'" % form.getvalue("format"))