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