Class: TestIds::Allocator

Inherits:
Object
  • Object
show all
Defined in:
lib/test_ids/allocator.rb

Overview

The allocator is responsible for assigning new numbers and keeping a record of existing assignments.

There is one allocator instance per configuration, and each has its own database file.

Constant Summary collapse

STORE_FORMAT_REVISION =
2

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(configuration) ⇒ Allocator

Returns a new instance of Allocator.



13
14
15
# File 'lib/test_ids/allocator.rb', line 13

def initialize(configuration)
  @config = configuration
end

Instance Attribute Details

#config ⇒ Object (readonly)

Returns the value of attribute config.



11
12
13
# File 'lib/test_ids/allocator.rb', line 11

def config
  @config
end

Instance Method Details

#allocate(instance, options) ⇒ Object

Main method to inject generated bin and test numbers, the given options instance is modified accordingly



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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/test_ids/allocator.rb', line 78

def allocate(instance, options)
  orig_options = options.dup
  clean(options)
  @callbacks = []
  name = extract_test_name(instance, options)
  name = "#{name}_#{options[:index]}" if options[:index]

  # First work out the test ID to be used for each of the numbers, and how many numbers
  # should be reserved
  if (options[:bin].is_a?(Symbol) || options[:bin].is_a?(String)) && options[:bin] != :none
    bin_id = options[:bin].to_s
  else
    bin_id = name
  end
  if (options[:softbin].is_a?(Symbol) || options[:softbin].is_a?(String)) && options[:softbin] != :none
    softbin_id = options[:softbin].to_s
  else
    softbin_id = name
  end
  if (options[:number].is_a?(Symbol) || options[:number].is_a?(String)) && options[:number] != :none
    number_id = options[:number].to_s
  else
    number_id = name
  end

  bin_size = options[:bin_size] || config.bins.size
  softbin_size = options[:softbin_size] || config.softbins.size
  number_size = options[:number_size] || config.numbers.size

  bin = store['assigned']['bins'][bin_id] ||= {}
  softbin = store['assigned']['softbins'][softbin_id] ||= {}
  number = store['assigned']['numbers'][number_id] ||= {}

  # If the user has supplied any of these, that number should be used
  # and reserved so that it is not automatically generated later
  if options[:bin] && options[:bin].is_a?(Numeric)
    bin['number'] = options[:bin]
    bin['size'] = bin_size
    store['manually_assigned']['bins'][options[:bin].to_s] = true
  # Regenerate the bin if the original allocation has since been applied
  # manually elsewhere
  elsif store['manually_assigned']['bins'][bin['number'].to_s]
    bin['number'] = nil
    bin['size'] = nil
    # Also regenerate these as they could be a function of the bin
    if config.softbins.function?
      softbin['number'] = nil
      softbin['size'] = nil
    end
    if config.numbers.function?
      number['number'] = nil
      number['size'] = nil
    end
  end
  if options[:softbin] && options[:softbin].is_a?(Numeric)
    softbin['number'] = options[:softbin]
    softbin['size'] = softbin_size
    store['manually_assigned']['softbins'][options[:softbin].to_s] = true
  elsif store['manually_assigned']['softbins'][softbin['number'].to_s]
    softbin['number'] = nil
    softbin['size'] = nil
    # Also regenerate the number as it could be a function of the softbin
    if config.numbers.function?
      number['number'] = nil
      number['size'] = nil
    end
  end
  if options[:number] && options[:number].is_a?(Numeric)
    number['number'] = options[:number]
    number['size'] = number_size
    store['manually_assigned']['numbers'][options[:number].to_s] = true
  elsif store['manually_assigned']['numbers'][number['number'].to_s]
    number['number'] = nil
    number['size'] = nil
    # Also regenerate the softbin as it could be a function of the number
    if config.softbins.function?
      softbin['number'] = nil
      softbin['size'] = nil
    end
  end

  # Otherwise generate the missing ones
  bin['number'] ||= allocate_bin(options.merge(size: bin_size))
  bin['size'] ||= bin_size
  # If the softbin is based on the test number, then need to calculate the
  # test number first.
  # Also do the number first if the softbin is a callback and the number is not.
  if (config.softbins.algorithm && config.softbins.algorithm.to_s =~ /n/) ||
     (config.softbins.callback && !config.numbers.function?)
    number['number'] ||= allocate_number(options.merge(bin: bin['number'], size: number_size))
    number['size'] ||= number_size
    softbin['number'] ||= allocate_softbin(options.merge(bin: bin['number'], number: number['number'], size: softbin_size))
    softbin['size'] ||= softbin_size
  else
    softbin['number'] ||= allocate_softbin(options.merge(bin: bin['number'], size: softbin_size))
    softbin['size'] ||= softbin_size
    number['number'] ||= allocate_number(options.merge(bin: bin['number'], softbin: softbin['number'], size: number_size))
    number['size'] ||= number_size
  end

  # Record that there has been a reference to the final numbers
  time = Time.now.to_f
  bin_size.times do |i|
    store['references']['bins'][(bin['number'] + i).to_s] = time if bin['number'] && options[:bin] != :none
  end
  softbin_size.times do |i|
    store['references']['softbins'][(softbin['number'] + i).to_s] = time if softbin['number'] && options[:softbin] != :none
  end
  number_size.times do |i|
    store['references']['numbers'][(number['number'] + i).to_s] = time if number['number'] && options[:number] != :none
  end

  # Update the supplied options hash that will be forwarded to the program generator
  unless options.delete(:bin) == :none
    options[:bin] = bin['number']
    options[:bin_size] = bin['size']
  end
  unless options.delete(:softbin) == :none
    options[:softbin] = softbin['number']
    options[:softbin_size] = softbin['size']
  end
  unless options.delete(:number) == :none
    options[:number] = number['number']
    options[:number_size] = number['size']
  end

  options
end

#clear(options) ⇒ Object

Clear the :bins, :softbins and/or :numbers by setting the options for each item to true



320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# File 'lib/test_ids/allocator.rb', line 320

def clear(options)
  if options[:softbin] || options[:softbins]
    store['assigned']['softbins'] = {}
    store['manually_assigned']['softbins'] = {}
    store['pointers']['softbins'] = nil
    store['references']['softbins'] = {}
  end
  if options[:bin] || options[:bins]
    store['assigned']['bins'] = {}
    store['manually_assigned']['bins'] = {}
    store['pointers']['bins'] = nil
    store['references']['bins'] = {}
  end
  if options[:number] || options[:numbers]
    store['assigned']['numbers'] = {}
    store['manually_assigned']['numbers'] = {}
    store['pointers']['numbers'] = nil
    store['references']['numbers'] = {}
  end
end

#file ⇒ Object

Returns a path to the file that will be used to store the allocated bins/numbers, returns nil if remote storage not enabled



384
385
386
# File 'lib/test_ids/allocator.rb', line 384

def file
  TestIds.database_file(id)
end

#id ⇒ Object



388
389
390
# File 'lib/test_ids/allocator.rb', line 388

def id
  config.id
end

#load_configuration_from_store ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



393
394
395
# File 'lib/test_ids/allocator.rb', line 393

def load_configuration_from_store
  config.load_from_serialized(store['configuration']) if store['configuration']
end

#next_in_range(range, options) ⇒ Object

Allocates a softbin number from the range specified in the test flow It also keeps a track of the last softbin assigned out from a particular range and uses that to increment the pointers accordingly. If a numeric number is passed to the softbin, it uses that number. The configuration for the TestId plugin needs to pass in the bin number and the options from the test flow For this method to work as intended.



23
24
25
# File 'lib/test_ids/allocator.rb', line 23

def next_in_range(range, options)
  range_item(range, options)
end

#range_item(range, options) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/test_ids/allocator.rb', line 27

def range_item(range, options)
  orig_options = options.dup
  # Now Check if the database (JSON file) exists.
  # If file exists, load the database and create the alias for ['pointer']['ranges']
  if file && File.exist?(file)
    lines = File.readlines(file)
    # Remove any header comment lines since these are not valid JSON
    lines.shift while lines.first =~ /^\/\// && !lines.empty?
    s = JSON.load(lines.join("\n"))
    rangehash = s['pointers']['ranges']
    rangehash = Hash[rangehash.map { |k, v| [k.to_sym, v] }]
  else
    # Create an alias for the databse that stores the pointers per range
    rangehash = store['pointers']['ranges'] ||= {}
  end
  # Check the database to see if the passed in range has already been included in the database hash
  if rangehash.key?(:"#{range}")
    # Read out the database hash to see what the last_softbin given out was for that range.
    # This hash is updated whenever a new softbin is assigned, so it should have the updated values for each range.
    previous_assigned_value = rangehash[:"#{range}"].to_i
    # Now calculate the new pointer.
    @pointer = previous_assigned_value - range.min
    # Check if the last_softbin given out is the same as the range[@pointer],
    # if so increment pointer by softbin size, default size is 1, config.softbins.size is configurable.
    # from example above, pointer was calculated as 1,range[1] is 10101 and is same as last_softbin, so pointer is incremented
    # and new value is assigned to the softbin.
    if previous_assigned_value == range.to_a[@pointer]
      @pointer += options[:size]
      assigned_value = range.to_a[@pointer]
    else
      # Because of the pointer calculations above, I don't think it will ever reach here, has not in my test cases so far!
      assigned_value = range.to_a[@pointer]
    end
    # Now update the database pointers to point to the lastest assigned softbin for a given range.
    rangehash.merge!(:"#{range}" => "#{range.to_a[@pointer]}")
  else
    # This is the case for a brand new range that has not been passed before
    # We start from the first value as the assigned softbin and update the database to reflect.
    @pointer = 0
    rangehash.merge!(:"#{range}" => "#{range.to_a[@pointer]}")
    assigned_value = range.to_a[@pointer]
  end
  unless !assigned_value.nil? && assigned_value.between?(range.min, range.max)
    Origen.log.error 'Assigned value not in range'
    fail
  end
  assigned_value
end

#repair(options = {}) ⇒ Object



262
263
264
265
266
267
268
269
270
271
272
273
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
# File 'lib/test_ids/allocator.rb', line 262

def repair(options = {})
  #####################################################################
  # Add any numbers that are missing from the references pool if the
  # allocator has moved onto the reclamation phase
  #####################################################################
  { 'bins' => 'bins', 'softbins' => 'softbins', 'numbers' => 'test_numbers' }.each do |type, name|
    if !config.send(type).function? && store['pointers'][type] == 'done'
      Origen.log.info "Checking for missing #{name}..."
      recovered = add_missing_references(config.send(type), store['references'][type])
      if recovered == 0
        Origen.log.info "  All #{name} are already available."
      else
        Origen.log.success "  Another #{recovered} #{name} have been made available!"
      end
    end
  end

  #####################################################################
  # Check that all assignments are valid based on the current config,
  # if not remove them and they will be re-allocated next time
  #####################################################################
  { 'bins' => 'bins', 'softbins' => 'softbins', 'numbers' => 'test_numbers' }.each do |type, name|
    next if config.send(type).function?
    Origen.log.info "Checking all #{name} assignments are valid..."
    also_remove_from = []
    if type == 'bin'
      also_remove_from << store['assigned']['softbins'] if config.softbins.function?
      also_remove_from << store['assigned']['numbers'] if config.numbers.function?
    elsif type == 'softbin'
      also_remove_from << store['assigned']['numbers'] if config.numbers.function?
    else
      also_remove_from << store['assigned']['softbins'] if config.softbins.function?
    end
    removed = remove_invalid_assignments(config.send(type), store['assigned'][type], store['manually_assigned'][type], also_remove_from)
    if removed == 0
      Origen.log.info "  All #{name} assignments are already valid."
    else
      Origen.log.success "  #{removed} #{name} assignments have been removed!"
    end
  end

  #####################################################################
  # Check that all references are valid based on the current config,
  # if not remove them
  #####################################################################
  { 'bins' => 'bins', 'softbins' => 'softbins', 'numbers' => 'test_numbers' }.each do |type, name|
    next if config.send(type).function?
    Origen.log.info "Checking all #{name} references are valid..."
    removed = remove_invalid_references(config.send(type), store['references'][type], store['manually_assigned'][type])
    if removed == 0
      Origen.log.info "  All #{name} references are already valid."
    else
      Origen.log.success "  #{removed} #{name} references have been removed!"
    end
  end
end

#save ⇒ Object

Saves the current allocator state to the repository



342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# File 'lib/test_ids/allocator.rb', line 342

def save
  if file
    # Ensure the current store has been loaded before we try to re-write it, this
    # is necessary if the program generator has crashed before creating a test
    store
    store['configuration'] = config
    p = Pathname.new(file)
    FileUtils.mkdir_p(p.dirname)
    File.open(p, 'w') do |f|
      f.puts '// The structure of this file is as follows:'
      f.puts '//'
      f.puts '//  {'
      f.puts '//    // A revision number used by TestIDs to identify the format of this file'
      f.puts "//    'format_revision'   => STORE_FORMAT_REVISION,"
      f.puts '//'
      f.puts '//    // Captures the configuration that was used the last time this database was updated.'
      f.puts "//    'configuration'          => { 'bins' => {}, 'softbins' => {}, 'numbers' => {} },"
      f.puts '//'
      f.puts '//    // If some number are still to be allocated, these point to the last number given out.'
      f.puts '//    // If all numbers have been allocated and we are now on the reclamation phase, the pointer'
      f.puts '//    // will contain "done".'
      f.puts "//    'pointers'          => { 'bins' => nil, 'softbins' => nil, 'numbers' => nil, 'ranges' => nil },"
      f.puts '//'
      f.puts '//    // This is the record of all numbers which have been previously assigned.'
      f.puts "//    'assigned'          => { 'bins' => {}, 'softbins' => {}, 'numbers' => {} },"
      f.puts '//'
      f.puts '//    // This is a record of any numbers which have been manually assigned.'
      f.puts "//    'manually_assigned' => { 'bins' => {}, 'softbins' => {}, 'numbers' => {} },"
      f.puts '//'
      f.puts '//    // This contains all assigned numbers with a timestamp of when they were last referenced.'
      f.puts '//    // When numbers need to be reclaimed, they will be taken from the bottom of this list, i.e.'
      f.puts '//    // the numbers which have not been used for the longest time, e.g. because the test they'
      f.puts '//    // were assigned to has since been removed.'
      f.puts "//    'references'        => { 'bins' => {}, 'softbins' => {}, 'numbers' => {} }"
      f.puts '//  }'
      f.puts JSON.pretty_generate(store)
    end
  end
end

#store ⇒ Object



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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/test_ids/allocator.rb', line 207

def store
  @store ||= begin
    if file && File.exist?(file)
      lines = File.readlines(file)
      # Remove any header comment lines since these are not valid JSON
      lines.shift while lines.first =~ /^\/\// && !lines.empty?
      s = JSON.load(lines.join("\n"))
    end
    if s
      unless s['format_revision']
        # Upgrade the original store format
        t = { 'bin' => {}, 'softbin' => {}, 'number' => {} }
        s['tests'].each do |name, numbers|
          t['bin'][name] = { 'number' => numbers['bin'], 'size' => 1 }
          t['softbin'][name] = { 'number' => numbers['softbin'], 'size' => 1 }
          t['number'][name] = { 'number' => numbers['number'], 'size' => 1 }
        end
        s = {
          'format_revision'   => 1,
          'assigned'          => t,
          'manually_assigned' => s['manually_assigned'],
          'pointers'          => s['pointers'],
          'references'        => s['references']
        }
      end
      # Change the keys to plural versions, this makes it easier to search for in the file
      # since 'number' is used within individual records
      if s['format_revision'] == 1
        s = {
          'format_revision'   => 2,
          'configuration'     => nil,
          'pointers'          => { 'bins' => s['pointers']['bin'], 'softbins' => s['pointers']['softbin'], 'numbers' => s['pointers']['number'] },
          'assigned'          => { 'bins' => s['assigned']['bin'], 'softbins' => s['assigned']['softbin'], 'numbers' => s['assigned']['number'] },
          'manually_assigned' => { 'bins' => s['manually_assigned']['bin'], 'softbins' => s['manually_assigned']['softbin'], 'numbers' => s['manually_assigned']['number'] },
          'references'        => { 'bins' => s['references']['bin'], 'softbins' => s['references']['softbin'], 'numbers' => s['references']['number'] }
        }
      end

      @last_bin = s['pointers']['bins']
      @last_softbin = s['pointers']['softbins']
      @last_number = s['pointers']['numbers']
      s
    else
      {
        'format_revision'   => STORE_FORMAT_REVISION,
        'configuration'     => nil,
        'pointers'          => { 'bins' => nil, 'softbins' => nil, 'numbers' => nil },
        'assigned'          => { 'bins' => {}, 'softbins' => {}, 'numbers' => {} },
        'manually_assigned' => { 'bins' => {}, 'softbins' => {}, 'numbers' => {} },
        'references'        => { 'bins' => {}, 'softbins' => {}, 'numbers' => {} }
      }
    end
  end
end