1 #!<%= node[:ruby][:interpreter] %>
13 # after this many changes, a changeset will be closed
16 # this is the scale factor for lat/lon values stored as integers in the database
20 # replace characters which cannot be represented in XML 1.0.
22 str.gsub(/[\x00-\x08\x0b\x0c\x0e-\x1f]/, "?")
26 # changeset class keeps some information about changesets downloaded from the
27 # database - enough to let us know which changesets are closed/open & recently
30 attr_reader :id, :created_at, :closed_at, :num_changes
34 @created_at = Time.parse(row["created_at"])
35 @closed_at = Time.parse(row["closed_at"])
36 @num_changes = row["num_changes"].to_i
40 (@closed_at < t) || (@num_changes >= CHANGES_LIMIT)
47 def activity_between?(t1, t2)
48 ((@closed_at >= t1) && (@closed_at < t2)) || ((@created_at >= t1) && (@created_at < t2))
53 # builds an XML representation of a changeset from the database
54 class ChangesetBuilder
55 def initialize(now, conn)
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
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"]
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
89 res = @conn.exec("select k, v from changeset_tags where changeset_id=#{cs.id}")
91 tag = XML::Node.new("tag")
92 tag["k"] = xml_sanitize(row["k"])
93 tag["v"] = xml_sanitize(row["v"])
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
103 # early return if there aren't any comments
104 return unless res.num_tuples.positive?
106 discussion = XML::Node.new("discussion")
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"])
116 discussion << comment
123 # sync a file to guarantee it's on disk
125 File.open(f, &:fsync)
129 # sync a directory to guarantee it's on disk. have to recurse to the root
130 # to guarantee sync for newly created directories.
132 while d != "/" && d != "."
139 # state and connections associated with getting changeset data
140 # replicated to a file.
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]
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
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) }
162 # set for faster presence lookups by ID
163 cs_ids = Set.new(changesets.map(&:id))
165 # but also add any changesets which have new comments
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) }
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 }
178 changesets.sort_by(&:id)
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 }
193 builder = ChangesetBuilder.new(@now, @conn)
194 changesets.each do |cs|
195 doc.root << builder.changeset_xml(cs)
202 @state.key?("sequence") ? @state["sequence"] + 1 : 0
206 @config["data_dir"] + format("/%03d/%03d/%03d", sequence / 1000000, (sequence / 1000) % 1000, (sequence % 1000))
210 @config["s3_dir"] + format("/%03d/%03d/%03d", sequence / 1000000, (sequence / 1000) % 1000, (sequence % 1000))
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"
218 FileUtils.mkdir_p(File.dirname(data_file))
219 Zlib::GzipWriter.open(tmp_data) do |fh|
220 fh.write(changeset_dump(changesets))
222 File.write(tmp_state, YAML.dump(@state))
224 # fsync the files in their old locations.
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))
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)
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"
247 FileUtils.mv(tmp_data, data_file)
248 FileUtils.cp(tmp_state, @config["state_file"])
249 FileUtils.mv(tmp_state, data_state_file)
251 # fsync the files in their new locations, in case the inodes have
252 # changed in the move / copy.
254 fsync(@config["state_file"])
255 fsync(data_state_file)
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"]))
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"
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)
273 # saves new state (including the changeset dump xml)
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
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.
287 changesets = open_changesets
288 @state["sequence"] = sequence
289 @state["last_run"] = @now
291 write_tmp_files!(changesets)
293 move_tmp_files_into_place!
295 fl.flock(File::LOCK_UN)
297 warn "Error! Couldn't update state."
298 fl.flock(File::LOCK_UN)
306 rep = Replicator.new(ARGV[0])
308 rescue StandardError => e
309 warn "ERROR: #{e.message}"
310 e.backtrace.each do |frame|
311 warn "ERROR: #{frame}"