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