Module: ElasticUtil

Defined in:
lib/elastic_util.rb

Overview

This module provides a way to backup and restore Elasticsearch data.

Examples:

Backup data from one elasticsearch cluster and restore it to another.


ElasticUtil.backup('http://localhost:9300', '/tmp/local-elastic-data', {size:5000})
ElasticUtil.restore('http://localhost:9301', '/tmp/local-elastic-data')

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =
"0.1.8"
DUMP_DIR =

The name of the data directory, relative to the user provided backup directory.

"es_data"

Class Method Summary collapse

Class Method Details

.api_get(uri, opts = {}) ⇒ Object



320
321
322
# File 'lib/elastic_util.rb', line 320

def self.api_get(uri, opts={})
  exec_request(uri, "GET", opts={})
end

.api_post(uri, payload, opts = {}) ⇒ Object



324
325
326
# File 'lib/elastic_util.rb', line 324

def self.api_post(uri, payload, opts={})
  exec_request(uri, "POST", opts.merge({payload:payload}))
end

.backup(url, backup_dir, opts = {}) ⇒ true

Backup Elasticsearch data to a local directory.

This uses ElasticSearch’s scroll api to fetch all records for indices and write the data to a local directory. The files it generates are given a .json.data extension. They are not valid JSON files, but rather are in the format expected by ElasticSearch’s _bulk api.

So #restore simply has to POST the contents of each file as Content-Type: application/x-ndjson

Use the :size option to change the number of results to fetch at once and also the size of the data files generated. Increasing size means larger files and fewer api requests for both #backup and the subsequent #restore of that data.

Examples:

Backup default Elasticsearch running locally.


ElasticUtil.backup('http://localhost:9300', '/tmp/local-elastic-data')

Parameters:

  • url (String)

    The url of the Elasticsearch cluster eg. ‘localhost:9300

  • backup_dir (String)

    The local directory to store data in. eg. ‘/tmp/es2.4’

  • opts (Hash) (defaults to: {})

    The options for this backup.

Options Hash (opts):

  • :indices (Array)

    The indices to backup. Default is all.

  • :exclude_indices (Array)

    Exclude certain indexes.

  • :exclude_fields (Array)

    Exclude certain fields. Default is [‘_id’].

  • :replace_types (Array)

    Replace certain types with a different type, separated by a colon. eg. ‘type1:type2’ or ‘stat:_doc’

  • :scroll (String)

    The scroll api parameter, Default is ‘5m’.

  • :size (Integer)

    The size api parameter. Default is 1000.

  • :force (true)

    Delete existing backup directory instead of erroring. Default is false.

  • :quiet (true)

    Don’t print anything. Default is false.

Returns:

  • (true)

    or raises an error



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/elastic_util.rb', line 54

def self.backup(url, backup_dir, opts={})
  start_time = Time.now
  url = url.strip.chomp("/")
  backup_dir = backup_dir.strip
  path = File.join(backup_dir.strip, DUMP_DIR)
  indices = []

  if opts[:dry]
    puts "(DRY RUN) Started backup" unless opts[:quiet]
  else
    puts "Started backup" unless opts[:quiet]
  end

  # ping it first
  response = nil
  uri = URI(url)
  response = api_get(uri)
  if !response.is_a?(Net::HTTPSuccess)
    raise Error, "Unable to reach Elasticsearch at url '#{url}'!\n#{response.inspect}\n#{response.body.to_s}"
  end

  # determine indices to backup, default is everything.
  if opts[:indices]
    indices = opts[:indices]
  else
    response = nil
    uri = URI(url + "/_cat/indices?format=json")
    response = api_get(uri)
    if !response.is_a?(Net::HTTPSuccess)
      raise Error, "HTTP request failure!\n#{response.inspect}\n#{response.body.to_s}"
    end
    json_response = JSON.parse(response.body)
    json_response.each do |record|
      indices.push(record['index'])
    end
  end
  if opts[:exclude_indices]
    indices = indices.reject {|it| opts[:exclude_indices].include?(it) }
  end

  if indices.empty?
    raise Error, "no indices to back up!"
  end
  
  opts[:scroll] ||= '5m'
  opts[:size] ||= 1000
  
  # exclude _id by default.
  if !opts.key?(:exclude_fields)
    opts[:exclude_fields] = ['_id']
  end

  # validate backup path
  if File.exists?(path)
    if opts[:force]
      FileUtils.rmtree(path)
    else
      raise Error, "backup path '#{path}' already exists! Delete it first or use --force"
    end
  end
  FileUtils.mkdir_p(path)

  if opts[:dry]
    indices.each_with_index do |index_name, i|
      puts "(#{i+1}/#{indices.size}) backing up index #{index_name}" unless opts[:quiet]
    end
    puts "(DRY RUN) Finished backup of Elasticsearch #{url} to directory #{backup_dir} (took #{(Time.now-start_time).round(3)}s)" unless opts[:quiet]
    return 0
  end

  # dump data
  indices.each_with_index do |index_name, i|
    puts "(#{i+1}/#{indices.size}) backing up index #{index_name}" unless opts[:quiet]
    # initial request
    file_index = 0
    uri = URI(url + "/#{index_name}/_search")
    params = { 
      :format => "json",
      :scroll => opts[:scroll], 
      :size => opts[:size],
      :sort => ["_doc"] 
    }
    uri.query = URI.encode_www_form(params)
    # puts "HTTP REQUEST #{uri.inspect}"
    response = api_get(uri)
    if !response.is_a?(Net::HTTPSuccess)
      raise Error, "HTTP request failure!\n#{response.inspect}\n#{response.body.to_s}"
    end
    json_response = JSON.parse(response.body)
    raise Error, "No scroll_id returned in response:\n#{response.inspect}" unless json_response['_scroll_id']
    scroll_id = json_response['_scroll_id']
    hits = json_response['hits']['hits']
    save_bulk_data(path, hits, nil, opts)
    
    file_index = 1
    # scroll requests
    while !hits.empty?
      uri = URI(url + "/_search/scroll")
      params = {
        :scroll_id => scroll_id, 
        :scroll => opts[:scroll]
      }
      uri.query = URI.encode_www_form(params)
      # puts "HTTP REQUEST #{uri.inspect}"
      response = api_get(uri)
      if !response.is_a?(Net::HTTPSuccess)
        raise Error, "HTTP request failure!\n#{response.inspect}\n#{response.body.to_s}"
      end
      json_response = JSON.parse(response.body)
      raise Error, "No scroll_id returned in response:\n#{response.inspect}\n#{response.body.to_s}" unless json_response['_scroll_id']
      scroll_id = json_response['_scroll_id']
      hits = json_response['hits']['hits']
      save_bulk_data(path, hits, file_index, opts)
      file_index += 1
    end
  end
  
  puts "Finished backup of Elasticsearch #{url} to directory #{backup_dir} (took #{(Time.now-start_time).round(3)}s)" unless opts[:quiet]
  return true
end

.exec_request(uri, http_method = "GET", opts = {}) ⇒ Object



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/elastic_util.rb', line 274

def self.exec_request(uri, http_method="GET", opts={})
  # parse request URI and options
  uri = uri.is_a?(URI) ? uri : URI(uri)
  http_method = http_method.to_s.upcase
  headers = opts[:headers] || {}
  payload = opts[:payload] || opts[:body]
  http = Net::HTTP.new(uri.host, uri.port)
  if uri.scheme == 'https'
    http.use_ssl = true
    # todo: always ignore ssl errors for now, but this should be an option
    # http.verify_mode = OpenSSL::SSL::VERIFY_PEER
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  end
  http.read_timeout = opts[:read_timeout] || (60*15)
  http.open_timeout = opts[:open_timeout] || 10
  request = nil
  if http_method == "GET"
    request = Net::HTTP::Get.new uri.request_uri
  elsif http_method == "POST"
    request = Net::HTTP::Post.new uri.request_uri
    request.body = payload if payload
  elsif http_method == "PUT"
    request = Net::HTTP::Put.new uri.request_uri
    request.body = payload if payload
  elsif http_method == "DELETE"
    request = Net::HTTP::Delete.new uri.request_uri
  else
    raise "HTTP method is unknown: '#{http_method}'"
  end
  # set headers
  headers.each { |k,v| request[k] = v }
  # todo: set default Accept: application/json  (probably, right?)
  # set default Content-Type
  if payload && headers['Content-Type'].nil?
    headers['Content-Type'] = "application/json"
  end
  # set basic auth
  if uri.user
    request.basic_auth uri.user, uri.password
  end
  # execute request
  response = http.request(request)
  # return the resulting Net::HTTPResponse
  return response
end

.restore(url, backup_dir, opts = {}) ⇒ true

Restore Elasticsearch data from a backup. This will do a POST to the _bulk api for each file in the backup directory.

Examples:

Restore local cluster with our backup.


ElasticUtil.restore('http://localhost:9301', '/tmp/local-elastic-data')

Parameters:

  • url (String)

    The url of the Elasticsearch cluster eg. ‘localhost:9200’.

  • backup_dir (String)

    The backup directory.

  • opts (Hash) (defaults to: {})

    The options for this backup.

Options Hash (opts):

  • :quiet (true)

    Don’t print anything. Default is false.

Returns:

  • (true)

    or raises an error



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/elastic_util.rb', line 189

def self.restore(url, backup_dir, opts={})
  start_time = Time.now
  url = url.strip.chomp("/")
  backup_dir = backup_dir.strip
  path = File.join(backup_dir.strip, DUMP_DIR)

  if opts[:dry]
    puts "(DRY RUN) Started restore" unless opts[:quiet]
  else
    puts "Started restore" unless opts[:quiet]
  end

  # validate backup path
  if !Dir.exists?(path)
    raise Error, "backup path '#{backup_dir}' does not exist!"
  end

  # ping it first
  uri = URI(url)
  response = api_get(uri)
  if !response.is_a?(Net::HTTPSuccess)
    raise Error, "Unable to reach Elasticsearch at url '#{url}'!\n#{response.inspect}\n#{response.body.to_s}"
  end

  # find files to import
  found_files = Dir[File.join(path, '**', '*.json.data' )]
  if found_files.empty?
    raise Error, "backup path '#{backup_dir}' does not exist!"
  else
    puts "Found #{found_files.size} files to import" unless opts[:quiet]
  end

  if opts[:dry]
    found_files.each_with_index do |file, i|
      puts "(#{i+1}/#{found_files.size}) bulk importing file #{file}" unless opts[:quiet]
    end
    puts "(DRY RUN) Finished restore of Elasticsearch #{url} with backup #{backup_dir} (took #{(Time.now-start_time).round(3)}s)" unless opts[:quiet]
    return 0
  end

  # bulk api request for each file
  found_files.each_with_index do |file, i|
    puts "(#{i+1}/#{found_files.size}) bulk importing file #{file}" unless opts[:quiet]
    payload = File.read(file)
    uri = URI(url + "/_bulk")
    response = api_post(uri, payload, {:headers => {"Content-Type" => "application/x-ndjson"} })
    if !response.is_a?(Net::HTTPSuccess)
      raise Error, "HTTP request failure!\n#{response.inspect}\n#{response.body.to_s}"
    end
  end

  puts "Finished restore of Elasticsearch #{url} with backup #{backup_dir} (took #{(Time.now-start_time).round(3)}s)" unless opts[:quiet]
  return true
end

.save_bulk_data(path, hits, file_index = nil, opts = {}) ⇒ Object

:nodoc:



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/elastic_util.rb', line 244

def self.save_bulk_data(path, hits, file_index=nil, opts={}) # :nodoc:
  if hits && !hits.empty?
    hits.each do |hit|
      index_name = hit['_index']
      index_type = hit['_type']
      dir_name = File.join(path, index_name)
      FileUtils.mkdir_p(dir_name)
      file_name = File.join(dir_name, index_type) + (file_index ? "_#{file_index}" : "") + ".json.data"
      # prepare record for bulk api injection
      doc_type = hit['_type']
      if opts[:replace_types] && opts[:replace_types][doc_type]
        doc_type = opts[:replace_types][doc_type]
      end
      action_json = {'index' => {
        '_index' => hit['_index'], '_type' => doc_type, '_id' => hit['_id']
      } }
      source_json = hit['_source']
      if opts[:exclude_fields] && source_json
        opts[:exclude_fields].each do |field|
          source_json.delete(field)
        end
      end

      File.open(file_name, 'a') do |file|
        file.write JSON.generate(action_json) + "\n" + JSON.generate(source_json) + "\n"
      end
    end
  end
end