4533: Lock all tables, not just the ones with fixtures. refs #4533
[arvados.git] / services / api / app / controllers / database_controller.rb
1 class DatabaseController < ApplicationController
2   skip_before_filter :find_object_by_uuid
3   skip_before_filter :render_404_if_no_object
4   before_filter :admin_required
5   def reset
6     raise ArvadosModel::PermissionDeniedError unless Rails.env == 'test'
7
8     # Sanity check: If someone has actually logged in here, this might
9     # not really be a throwaway database. Client test suites should
10     # use @example.com email addresses when creating user records, so
11     # we can tell they're not valuable.
12     user_uuids = User.
13       where('email is null or email not like ?', '%@example.com').
14       collect &:uuid
15     fixture_uuids =
16       YAML::load_file(File.expand_path('../../../test/fixtures/users.yml',
17                                        __FILE__)).
18       values.collect { |u| u['uuid'] }
19     unexpected_uuids = user_uuids - fixture_uuids
20     if unexpected_uuids.any?
21       logger.error("Running in test environment, but non-fixture users exist: " +
22                    "#{unexpected_uuids}")
23       raise ArvadosModel::PermissionDeniedError
24     end
25
26     require 'active_record/fixtures'
27
28     # What kinds of fixtures do we have?
29     fixturesets = Dir.glob(Rails.root.join('test', 'fixtures', '*.yml')).
30       collect { |yml| yml.match(/([^\/]*)\.yml$/)[1] }
31
32     ActiveRecord::Base.transaction do
33       # Avoid deadlock by locking all tables before doing anything
34       # drastic.
35       table_names = '"' + ActiveRecord::Base.connection.tables.join('","') + '"'
36       ActiveRecord::Base.connection.execute \
37       "LOCK TABLE #{table_names} IN ACCESS EXCLUSIVE MODE"
38
39       # Delete existing fixtures (and everything else) from fixture
40       # tables
41       fixturesets.each do |x|
42         x.classify.constantize.unscoped.delete_all
43       end
44
45       # create_fixtures() is a no-op for cached fixture sets, so
46       # uncache them all.
47       ActiveRecord::Fixtures.reset_cache
48       ActiveRecord::Fixtures.
49         create_fixtures(Rails.root.join('test', 'fixtures'), fixturesets)
50
51       # Dump cache of permissions etc.
52       Rails.cache.clear
53       ActiveRecord::Base.connection.clear_query_cache
54
55       # Reload database seeds
56       DatabaseSeeds.install
57     end
58
59     # Done.
60     render json: {success: true}
61   end
62 end