]> git.openstreetmap.org Git - chef.git/blob - cookbooks/planet/templates/default/replicate-changesets.erb
Use volume for nested podman container storage
[chef.git] / cookbooks / planet / templates / default / replicate-changesets.erb
1 #!<%= node[:ruby][:interpreter] %>
2
3 require "rubygems"
4 require "bigdecimal"
5 require "pg"
6 require "yaml"
7 require "time"
8 require "fileutils"
9 require "xml/libxml"
10 require "zlib"
11 require "set"
12
13 # after this many changes, a changeset will be closed
14 CHANGES_LIMIT = 50000
15
16 # this is the scale factor for lat/lon values stored as integers in the database
17 GEO_SCALE = 10000000
18
19 ##
20 # replace characters which cannot be represented in XML 1.0.
21 def xml_sanitize(str)
22   str.gsub(/[\x00-\x08\x0b\x0c\x0e-\x1f]/, "?")
23 end
24
25 ##
26 # changeset class keeps some information about changesets downloaded from the
27 # database - enough to let us know which changesets are closed/open & recently
28 # closed.
29 class Changeset
30   attr_reader :id, :created_at, :closed_at, :num_changes
31
32   def initialize(row)
33     @id = row["id"].to_i
34     @created_at = Time.parse(row["created_at"])
35     @closed_at = Time.parse(row["closed_at"])
36     @num_changes = row["num_changes"].to_i
37   end
38
39   def closed?(t)
40     (@closed_at < t) || (@num_changes >= CHANGES_LIMIT)
41   end
42
43   def open?(t)
44     !closed?(t)
45   end
46
47   def activity_between?(t1, t2)
48     ((@closed_at >= t1) && (@closed_at < t2)) || ((@created_at >= t1) && (@created_at < t2))
49   end
50 end
51
52 ##
53 # builds an XML representation of a changeset from the database
54 class ChangesetBuilder
55   def initialize(now, conn)
56     @now = now
57     @conn = conn
58   end
59
60   def changeset_xml(cs)
61     xml = XML::Node.new("changeset")
62     xml["id"] = cs.id.to_s
63     xml["created_at"] = cs.created_at.getutc.xmlschema
64     xml["closed_at"] = cs.closed_at.getutc.xmlschema if cs.closed?(@now)
65     xml["open"] = cs.open?(@now).to_s
66     xml["num_changes"] = cs.num_changes.to_s
67
68     res = @conn.exec("select u.id, u.display_name, c.min_lat, c.max_lat, c.min_lon, c.max_lon from users u join changesets c on u.id=c.user_id where c.id=#{cs.id}")
69     xml["user"] = xml_sanitize(res[0]["display_name"])
70     xml["uid"] = res[0]["id"]
71
72     unless res[0]["min_lat"].nil? ||
73            res[0]["max_lat"].nil? ||
74            res[0]["min_lon"].nil? ||
75            res[0]["max_lon"].nil?
76       xml["min_lat"] = (res[0]["min_lat"].to_f / GEO_SCALE).to_s
77       xml["max_lat"] = (res[0]["max_lat"].to_f / GEO_SCALE).to_s
78       xml["min_lon"] = (res[0]["min_lon"].to_f / GEO_SCALE).to_s
79       xml["max_lon"] = (res[0]["max_lon"].to_f / GEO_SCALE).to_s
80     end
81
82     add_tags(xml, cs)
83     add_comments(xml, cs)
84
85     xml
86   end
87
88   def add_tags(xml, cs)
89     res = @conn.exec("select k, v from changeset_tags where changeset_id=#{cs.id}")
90     res.each do |row|
91       tag = XML::Node.new("tag")
92       tag["k"] = xml_sanitize(row["k"])
93       tag["v"] = xml_sanitize(row["v"])
94       xml << tag
95     end
96   end
97
98   def add_comments(xml, cs)
99     # grab the visible changeset comments as well
100     res = @conn.exec("select cc.id, cc.author_id, u.display_name as author, cc.body, (cc.created_at at time zone 'utc') as created_at from changeset_comments cc join users u on cc.author_id=u.id where cc.changeset_id=#{cs.id} and cc.visible order by cc.created_at asc")
101     xml["comments_count"] = res.num_tuples.to_s
102
103     # early return if there aren't any comments
104     return unless res.num_tuples.positive?
105
106     discussion = XML::Node.new("discussion")
107     res.each do |row|
108       comment = XML::Node.new("comment")
109       comment["id"] = row["id"]
110       comment["uid"] = row["author_id"]
111       comment["user"] = xml_sanitize(row["author"])
112       comment["date"] = Time.parse(row["created_at"]).getutc.xmlschema
113       text = XML::Node.new("text")
114       text.content = xml_sanitize(row["body"])
115       comment << text
116       discussion << comment
117     end
118     xml << discussion
119   end
120 end
121
122 ##
123 # sync a file to guarantee it's on disk
124 def fsync(f)
125   File.open(f, &:fsync)
126 end
127
128 ##
129 # sync a directory to guarantee it's on disk. have to recurse to the root
130 # to guarantee sync for newly created directories.
131 def fdirsync(d)
132   while d != "/" && d != "."
133     fsync(d)
134     d = File.dirname(d)
135   end
136 end
137
138 ##
139 # state and connections associated with getting changeset data
140 # replicated to a file.
141 class Replicator
142   def initialize(config)
143     @config = YAML.safe_load(File.read(config))
144     @state = YAML.safe_load(File.read(@config["state_file"]), :permitted_classes => [Time], :fallback => {})
145     @conn = PG::Connection.connect(@config["db"])
146     # get current time from the database rather than the current system
147     @now = @conn.exec("select now() as now").map { |row| Time.parse(row["now"]) }[0]
148   end
149
150   def open_changesets
151     last_run = @state["last_run"]
152     last_run = (@now - 60) if last_run.nil?
153     # pretty much all operations on a changeset will modify its closed_at
154     # time (see rails_port's changeset model). so it is probably enough
155     # for us to look at anything that was closed recently, and filter from
156     # there.
157     changesets = @conn
158                  .exec("select id, (created_at at time zone 'utc') as created_at, (closed_at at time zone 'utc') as closed_at, num_changes from changesets where (closed_at at time zone 'utc') > ((now() at time zone 'utc') - '1 hour'::interval)")
159                  .map { |row| Changeset.new(row) }
160                  .select { |cs| cs.activity_between?(last_run, @now) }
161
162     # set for faster presence lookups by ID
163     cs_ids = Set.new(changesets.map(&:id))
164
165     # but also add any changesets which have new comments
166     new_ids = @conn
167               .exec("select distinct changeset_id from changeset_comments where (created_at at time zone 'utc') >= '#{last_run}' and (created_at at time zone 'utc') < '#{@now}' and visible")
168               .map { |row| row["changeset_id"].to_i }
169               .reject { |c_id| cs_ids.include?(c_id) }
170
171     new_ids.each do |id|
172       @conn
173         .exec("select id, (created_at at time zone 'utc') as created_at, (closed_at at time zone 'utc') as closed_at, num_changes from changesets where id=#{id}")
174         .map { |row| Changeset.new(row) }
175         .each { |cs| changesets << cs }
176     end
177
178     changesets.sort_by(&:id)
179   end
180
181   # creates an XML file containing the changeset information from the
182   # list of changesets output by open_changesets.
183   def changeset_dump(changesets)
184     doc = XML::Document.new
185     doc.root = XML::Node.new("osm")
186     { "version" => "0.6",
187       "generator" => "replicate_changesets.rb",
188       "copyright" => "OpenStreetMap and contributors",
189       "attribution" => "https://www.openstreetmap.org/copyright",
190       "license" => "https://opendatacommons.org/licenses/odbl/1-0/" }
191       .each { |k, v| doc.root[k] = v }
192
193     builder = ChangesetBuilder.new(@now, @conn)
194     changesets.each do |cs|
195       doc.root << builder.changeset_xml(cs)
196     end
197
198     doc.to_s
199   end
200
201   def sequence
202     @state.key?("sequence") ? @state["sequence"] + 1 : 0
203   end
204
205   def data_stem
206     @config["data_dir"] + format("/%03d/%03d/%03d", sequence / 1000000, (sequence / 1000) % 1000, (sequence % 1000))
207   end
208
209   def s3_stem
210     @config["s3_dir"] + format("/%03d/%03d/%03d", sequence / 1000000, (sequence / 1000) % 1000, (sequence % 1000))
211   end
212
213   def write_tmp_files!(changesets)
214     data_file = data_stem + ".osm.gz"
215     tmp_state = @config["state_file"] + ".tmp"
216     tmp_data = data_file + ".tmp"
217
218     FileUtils.mkdir_p(File.dirname(data_file))
219     Zlib::GzipWriter.open(tmp_data) do |fh|
220       fh.write(changeset_dump(changesets))
221     end
222     File.write(tmp_state, YAML.dump(@state))
223
224     # fsync the files in their old locations.
225     fsync(tmp_data)
226     fsync(tmp_state)
227
228     # sync the directory as well, to ensure that the file is reachable
229     # from the dirent and has been updated to account for any allocations.
230     fdirsync(File.dirname(tmp_data))
231     fdirsync(File.dirname(tmp_state))
232
233     # sanity check: the files we're moving into place
234     # should be non-empty.
235     raise "Temporary gzip file should exist, but doesn't." unless File.exist?(tmp_data)
236     raise "Temporary state file should exist, but doesn't." unless File.exist?(tmp_state)
237     raise "Temporary gzip file should be non-empty, but isn't." if File.zero?(tmp_data)
238     raise "Temporary state file should be non-empty, but isn't." if File.zero?(tmp_state)
239   end
240
241   def move_tmp_files_into_place!
242     data_file = data_stem + ".osm.gz"
243     data_state_file = data_stem + ".state.txt"
244     tmp_state = @config["state_file"] + ".tmp"
245     tmp_data = data_file + ".tmp"
246
247     FileUtils.mv(tmp_data, data_file)
248     FileUtils.cp(tmp_state, @config["state_file"])
249     FileUtils.mv(tmp_state, data_state_file)
250
251     # fsync the files in their new locations, in case the inodes have
252     # changed in the move / copy.
253     fsync(data_file)
254     fsync(@config["state_file"])
255     fsync(data_state_file)
256
257     # sync the directory as well, to ensure that the file is reachable
258     # from the dirent and has been updated to account for any allocations.
259     fdirsync(File.dirname(data_file))
260     fdirsync(File.dirname(@config["state_file"]))
261
262     if @config["s3_dir"]
263       s3_file = s3_stem + ".osm.gz"
264       s3_state_file = s3_stem + ".state.txt"
265       s3_state_config_file = @config["s3_dir"] + "/state.yaml"
266
267       system("/opt/awscli/v2/current/bin/aws", "--profile=osm-pds-upload", "s3", "cp", "--storage-class=INTELLIGENT_TIERING", "--no-progress", data_file, s3_file)
268       system("/opt/awscli/v2/current/bin/aws", "--profile=osm-pds-upload", "s3", "cp", "--storage-class=INTELLIGENT_TIERING", "--no-progress", data_state_file, s3_state_file)
269       system("/opt/awscli/v2/current/bin/aws", "--profile=osm-pds-upload", "s3", "cp", "--storage-class=INTELLIGENT_TIERING", "--no-progress", @config["state_file"], s3_state_config_file)
270     end
271   end
272
273   # saves new state (including the changeset dump xml)
274   def save!
275     File.open(@config["lock_file"], File::RDWR | File::CREAT, 0o600) do |fl|
276       # take the lock in non-blocking mode. if this process doesn't get the lock
277       # then another will be run from cron shortly. this prevents a whole bunch
278       # of processes queueing on the lock and causing weirdness if/when they
279       # get woken up in a random order.
280       got_lock = fl.flock(File::LOCK_EX | File::LOCK_NB)
281       break unless got_lock
282
283       # try and write the files to tmp locations and then
284       # move them into place later, to avoid in-progress
285       # clashes, or people seeing incomplete files.
286       begin
287         changesets = open_changesets
288         @state["sequence"] = sequence
289         @state["last_run"] = @now
290
291         write_tmp_files!(changesets)
292
293         move_tmp_files_into_place!
294
295         fl.flock(File::LOCK_UN)
296       rescue StandardError
297         warn "Error! Couldn't update state."
298         fl.flock(File::LOCK_UN)
299         raise
300       end
301     end
302   end
303 end
304
305 begin
306   rep = Replicator.new(ARGV[0])
307   rep.save!
308 rescue StandardError => e
309   warn "ERROR: #{e.message}"
310   e.backtrace.each do |frame|
311     warn "ERROR: #{frame}"
312   end
313   exit 1
314 end