15003: Merge branch 'master' into 15003-preprocess-config
[arvados.git] / services / api / config / arvados_config.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 #
6 # Load Arvados configuration from /etc/arvados/config.yml, using defaults
7 # from config.default.yml
8 #
9 # Existing application.yml is migrated into the new config structure.
10 # Keys in the legacy application.yml take precedence.
11 #
12 # Use "bundle exec config:dump" to get the complete active configuration
13 #
14 # Use "bundle exec config:migrate" to migrate application.yml and
15 # database.yml to config.yml.  After adding the output of
16 # config:migrate to /etc/arvados/config.yml, you will be able to
17 # delete application.yml and database.yml.
18
19 require 'config_loader'
20
21 begin
22   # If secret_token.rb exists here, we need to load it first.
23   require_relative 'secret_token.rb'
24 rescue LoadError
25   # Normally secret_token.rb is missing and the secret token is
26   # configured by application.yml (i.e., here!) instead.
27 end
28
29 if (File.exist?(File.expand_path '../omniauth.rb', __FILE__) and
30     not defined? WARNED_OMNIAUTH_CONFIG)
31   Rails.logger.warn <<-EOS
32 DEPRECATED CONFIGURATION:
33  Please move your SSO provider config into config/application.yml
34  and delete config/initializers/omniauth.rb.
35 EOS
36   # Real values will be copied from globals by omniauth_init.rb. For
37   # now, assign some strings so the generic *.yml config loader
38   # doesn't overwrite them or complain that they're missing.
39   Rails.configuration.Login["ProviderAppID"] = 'xxx'
40   Rails.configuration.Login["ProviderAppSecret"] = 'xxx'
41   Rails.configuration.Services["SSO"]["ExternalURL"] = '//xxx'
42   WARNED_OMNIAUTH_CONFIG = true
43 end
44
45 # Load the defaults
46 $arvados_config_defaults = ConfigLoader.load "#{::Rails.root.to_s}/config/config.default.yml"
47 if $arvados_config_defaults.empty?
48   raise "Missing #{::Rails.root.to_s}/config/config.default.yml"
49 end
50
51 clusterID, clusterConfig = $arvados_config_defaults["Clusters"].first
52 $arvados_config_defaults = clusterConfig
53 $arvados_config_defaults["ClusterID"] = clusterID
54
55 # Initialize the global config with the defaults
56 $arvados_config_global = $arvados_config_defaults.deep_dup
57
58 # Load the global config file
59 confs = ConfigLoader.load "/etc/arvados/config.yml"
60 if !confs.empty?
61   clusterID, clusterConfig = confs["Clusters"].first
62   $arvados_config_global["ClusterID"] = clusterID
63
64   # Copy the cluster config over the defaults
65   $arvados_config_global.deep_merge!(clusterConfig)
66 end
67
68 # Now make a copy
69 $arvados_config = $arvados_config_global.deep_dup
70
71 # Declare all our configuration items.
72 arvcfg = ConfigLoader.new
73 arvcfg.declare_config "ClusterID", NonemptyString, :uuid_prefix
74 arvcfg.declare_config "ManagementToken", String, :ManagementToken
75 arvcfg.declare_config "Git.Repositories", String, :git_repositories_dir
76 arvcfg.declare_config "API.DisabledAPIs", Array, :disable_api_methods
77 arvcfg.declare_config "API.MaxRequestSize", Integer, :max_request_size
78 arvcfg.declare_config "API.MaxIndexDatabaseRead", Integer, :max_index_database_read
79 arvcfg.declare_config "API.MaxItemsPerResponse", Integer, :max_items_per_response
80 arvcfg.declare_config "API.AsyncPermissionsUpdateInterval", ActiveSupport::Duration, :async_permissions_update_interval
81 arvcfg.declare_config "API.RailsSessionSecretToken", NonemptyString, :secret_token
82 arvcfg.declare_config "Users.AutoSetupNewUsers", Boolean, :auto_setup_new_users
83 arvcfg.declare_config "Users.AutoSetupNewUsersWithVmUUID", String, :auto_setup_new_users_with_vm_uuid
84 arvcfg.declare_config "Users.AutoSetupNewUsersWithRepository", Boolean, :auto_setup_new_users_with_repository
85 arvcfg.declare_config "Users.AutoSetupUsernameBlacklist", Array, :auto_setup_name_blacklist
86 arvcfg.declare_config "Users.NewUsersAreActive", Boolean, :new_users_are_active
87 arvcfg.declare_config "Users.AutoAdminUserWithEmail", String, :auto_admin_user
88 arvcfg.declare_config "Users.AutoAdminFirstUser", Boolean, :auto_admin_first_user
89 arvcfg.declare_config "Users.UserProfileNotificationAddress", String, :user_profile_notification_address
90 arvcfg.declare_config "Users.AdminNotifierEmailFrom", String, :admin_notifier_email_from
91 arvcfg.declare_config "Users.EmailSubjectPrefix", String, :email_subject_prefix
92 arvcfg.declare_config "Users.UserNotifierEmailFrom", String, :user_notifier_email_from
93 arvcfg.declare_config "Users.NewUserNotificationRecipients", Array, :new_user_notification_recipients
94 arvcfg.declare_config "Users.NewInactiveUserNotificationRecipients", Array, :new_inactive_user_notification_recipients
95 arvcfg.declare_config "Login.ProviderAppSecret", NonemptyString, :sso_app_secret
96 arvcfg.declare_config "Login.ProviderAppID", NonemptyString, :sso_app_id
97 arvcfg.declare_config "TLS.Insecure", Boolean, :sso_insecure
98 arvcfg.declare_config "Services.SSO.ExternalURL", NonemptyString, :sso_provider_url
99 arvcfg.declare_config "AuditLogs.MaxAge", ActiveSupport::Duration, :max_audit_log_age
100 arvcfg.declare_config "AuditLogs.MaxDeleteBatch", Integer, :max_audit_log_delete_batch
101 arvcfg.declare_config "AuditLogs.UnloggedAttributes", Array, :unlogged_attributes
102 arvcfg.declare_config "SystemLogs.MaxRequestLogParamsSize", Integer, :max_request_log_params_size
103 arvcfg.declare_config "Collections.DefaultReplication", Integer, :default_collection_replication
104 arvcfg.declare_config "Collections.DefaultTrashLifetime", ActiveSupport::Duration, :default_trash_lifetime
105 arvcfg.declare_config "Collections.CollectionVersioning", Boolean, :collection_versioning
106 arvcfg.declare_config "Collections.PreserveVersionIfIdle", ActiveSupport::Duration, :preserve_version_if_idle
107 arvcfg.declare_config "Collections.TrashSweepInterval", ActiveSupport::Duration, :trash_sweep_interval
108 arvcfg.declare_config "Collections.BlobSigningKey", NonemptyString, :blob_signing_key
109 arvcfg.declare_config "Collections.BlobSigningTTL", Integer, :blob_signature_ttl
110 arvcfg.declare_config "Collections.BlobSigning", Boolean, :permit_create_collection_with_unsigned_manifest, ->(cfg, k, v) { ConfigLoader.set_cfg cfg, "Collections.BlobSigning", !v }
111 arvcfg.declare_config "Containers.SupportedDockerImageFormats", Array, :docker_image_formats
112 arvcfg.declare_config "Containers.LogReuseDecisions", Boolean, :log_reuse_decisions
113 arvcfg.declare_config "Containers.DefaultKeepCacheRAM", Integer, :container_default_keep_cache_ram
114 arvcfg.declare_config "Containers.MaxDispatchAttempts", Integer, :max_container_dispatch_attempts
115 arvcfg.declare_config "Containers.MaxRetryAttempts", Integer, :container_count_max
116 arvcfg.declare_config "Containers.UsePreemptibleInstances", Boolean, :preemptible_instances
117 arvcfg.declare_config "Containers.MaxComputeVMs", Integer, :max_compute_nodes
118 arvcfg.declare_config "Containers.Logging.LogBytesPerEvent", Integer, :crunch_log_bytes_per_event
119 arvcfg.declare_config "Containers.Logging.LogSecondsBetweenEvents", ActiveSupport::Duration, :crunch_log_seconds_between_events
120 arvcfg.declare_config "Containers.Logging.LogThrottlePeriod", ActiveSupport::Duration, :crunch_log_throttle_period
121 arvcfg.declare_config "Containers.Logging.LogThrottleBytes", Integer, :crunch_log_throttle_bytes
122 arvcfg.declare_config "Containers.Logging.LogThrottleLines", Integer, :crunch_log_throttle_lines
123 arvcfg.declare_config "Containers.Logging.LimitLogBytesPerJob", Integer, :crunch_limit_log_bytes_per_job
124 arvcfg.declare_config "Containers.Logging.LogPartialLineThrottlePeriod", ActiveSupport::Duration, :crunch_log_partial_line_throttle_period
125 arvcfg.declare_config "Containers.Logging.LogUpdatePeriod", ActiveSupport::Duration, :crunch_log_update_period
126 arvcfg.declare_config "Containers.Logging.LogUpdateSize", Integer, :crunch_log_update_size
127 arvcfg.declare_config "Containers.Logging.MaxAge", ActiveSupport::Duration, :clean_container_log_rows_after
128 arvcfg.declare_config "Containers.SLURM.Managed.DNSServerConfDir", Pathname, :dns_server_conf_dir
129 arvcfg.declare_config "Containers.SLURM.Managed.DNSServerConfTemplate", Pathname, :dns_server_conf_template
130 arvcfg.declare_config "Containers.SLURM.Managed.DNSServerReloadCommand", String, :dns_server_reload_command
131 arvcfg.declare_config "Containers.SLURM.Managed.DNSServerUpdateCommand", String, :dns_server_update_command
132 arvcfg.declare_config "Containers.SLURM.Managed.ComputeNodeDomain", String, :compute_node_domain
133 arvcfg.declare_config "Containers.SLURM.Managed.ComputeNodeNameservers", Array, :compute_node_nameservers
134 arvcfg.declare_config "Containers.SLURM.Managed.AssignNodeHostname", String, :assign_node_hostname
135 arvcfg.declare_config "Containers.JobsAPI.Enable", String, :enable_legacy_jobs_api, ->(cfg, k, v) { ConfigLoader.set_cfg cfg, "Containers.JobsAPI.Enable", v.to_s }
136 arvcfg.declare_config "Containers.JobsAPI.CrunchJobWrapper", String, :crunch_job_wrapper
137 arvcfg.declare_config "Containers.JobsAPI.CrunchJobUser", String, :crunch_job_user
138 arvcfg.declare_config "Containers.JobsAPI.CrunchRefreshTrigger", String, :crunch_refresh_trigger
139 arvcfg.declare_config "Containers.JobsAPI.GitInternalDir", String, :git_internal_dir
140 arvcfg.declare_config "Containers.JobsAPI.ReuseJobIfOutputsDiffer", Boolean, :reuse_job_if_outputs_differ
141 arvcfg.declare_config "Containers.JobsAPI.DefaultDockerImage", String, :default_docker_image_for_jobs
142 arvcfg.declare_config "Mail.MailchimpAPIKey", String, :mailchimp_api_key
143 arvcfg.declare_config "Mail.MailchimpListID", String, :mailchimp_list_id
144 arvcfg.declare_config "Services.Controller.ExternalURL", URI
145 arvcfg.declare_config "Services.Workbench1.ExternalURL", URI, :workbench_address
146 arvcfg.declare_config "Services.Websocket.ExternalURL", URI, :websocket_address
147 arvcfg.declare_config "Services.WebDAV.ExternalURL", URI, :keep_web_service_url
148 arvcfg.declare_config "Services.GitHTTP.ExternalURL", URI, :git_repo_https_base
149 arvcfg.declare_config "Services.GitSSH.ExternalURL", URI, :git_repo_ssh_base, ->(cfg, k, v) { ConfigLoader.set_cfg cfg, "Services.GitSSH.ExternalURL", "ssh://#{v}" }
150 arvcfg.declare_config "RemoteClusters", Hash, :remote_hosts, ->(cfg, k, v) {
151   h = if cfg["RemoteClusters"] then
152         cfg["RemoteClusters"].deep_dup
153       else
154         {}
155       end
156   v.each do |clusterid, host|
157     if h[clusterid].nil?
158       h[clusterid] = {
159         "Host" => host,
160         "Proxy" => true,
161         "Scheme" => "https",
162         "Insecure" => false,
163         "ActivateUsers" => false
164       }
165     end
166   end
167   ConfigLoader.set_cfg cfg, "RemoteClusters", h
168 }
169 arvcfg.declare_config "RemoteClusters.*.Proxy", Boolean, :remote_hosts_via_dns
170
171 dbcfg = ConfigLoader.new
172
173 dbcfg.declare_config "PostgreSQL.ConnectionPool", Integer, :pool
174 dbcfg.declare_config "PostgreSQL.Connection.Host", String, :host
175 dbcfg.declare_config "PostgreSQL.Connection.Port", String, :port
176 dbcfg.declare_config "PostgreSQL.Connection.User", String, :username
177 dbcfg.declare_config "PostgreSQL.Connection.Password", String, :password
178 dbcfg.declare_config "PostgreSQL.Connection.DBName", String, :database
179 dbcfg.declare_config "PostgreSQL.Connection.Template", String, :template
180 dbcfg.declare_config "PostgreSQL.Connection.Encoding", String, :encoding
181
182 application_config = {}
183 %w(application.default application).each do |cfgfile|
184   path = "#{::Rails.root.to_s}/config/#{cfgfile}.yml"
185   confs = ConfigLoader.load(path, erb: true)
186   # Ignore empty YAML file:
187   next if confs == false
188   application_config.deep_merge!(confs['common'] || {})
189   application_config.deep_merge!(confs[::Rails.env.to_s] || {})
190 end
191
192 db_config = {}
193 path = "#{::Rails.root.to_s}/config/database.yml"
194 if File.exist? path
195   db_config = ConfigLoader.load(path, erb: true)
196 end
197
198 $remaining_config = arvcfg.migrate_config(application_config, $arvados_config)
199 dbcfg.migrate_config(db_config[::Rails.env.to_s] || {}, $arvados_config)
200
201 if application_config[:auto_activate_users_from]
202   application_config[:auto_activate_users_from].each do |cluster|
203     if $arvados_config.RemoteClusters[cluster]
204       $arvados_config.RemoteClusters[cluster]["ActivateUsers"] = true
205     end
206   end
207 end
208
209 if application_config[:host] || application_config[:port] || application_config[:scheme]
210   if !application_config[:host] || application_config[:host].empty?
211     raise "Must set 'host' when setting 'port' or 'scheme'"
212   end
213   $arvados_config.Services["Controller"]["ExternalURL"] = URI((application_config[:scheme] || "https")+"://"+application_config[:host]+
214                                                               (if application_config[:port] then ":#{application_config[:port]}" else "" end))
215 end
216
217 # Checks for wrongly typed configuration items, coerces properties
218 # into correct types (such as Duration), and optionally raise error
219 # for essential configuration that can't be empty.
220 arvcfg.coercion_and_check $arvados_config_defaults, check_nonempty: false
221 arvcfg.coercion_and_check $arvados_config_global, check_nonempty: false
222 arvcfg.coercion_and_check $arvados_config, check_nonempty: true
223 dbcfg.coercion_and_check $arvados_config, check_nonempty: true
224
225 # * $arvados_config_defaults is the defaults
226 # * $arvados_config_global is $arvados_config_defaults merged with the contents of /etc/arvados/config.yml
227 # These are used by the rake config: tasks
228 #
229 # * $arvados_config is $arvados_config_global merged with the migrated contents of application.yml
230 # This is what actually gets copied into the Rails configuration object.
231
232 if $arvados_config["Collections"]["DefaultTrashLifetime"] < 86400.seconds then
233   raise "default_trash_lifetime is %d, must be at least 86400" % Rails.configuration.Collections.DefaultTrashLifetime
234 end
235
236 #
237 # Special case for test database where there's no database.yml,
238 # because the Arvados config.yml doesn't have a concept of multiple
239 # rails environments.
240 #
241 if ::Rails.env.to_s == "test" && db_config["test"].nil?
242   $arvados_config["PostgreSQL"]["Connection"]["DBName"] = "arvados_test"
243 end
244
245 if $arvados_config["PostgreSQL"]["Connection"]["Password"].empty?
246   raise "Database password is empty, PostgreSQL section is: #{$arvados_config["PostgreSQL"]}"
247 end
248
249 dbhost = $arvados_config["PostgreSQL"]["Connection"]["Host"]
250 if $arvados_config["PostgreSQL"]["Connection"]["Post"] != 0
251   dbhost += ":#{$arvados_config["PostgreSQL"]["Connection"]["Post"]}"
252 end
253
254 #
255 # If DATABASE_URL is set, then ActiveRecord won't error out if database.yml doesn't exist.
256 #
257 # For config migration, we've previously populated the PostgreSQL
258 # section of the config from database.yml
259 #
260 ENV["DATABASE_URL"] = "postgresql://#{$arvados_config["PostgreSQL"]["Connection"]["User"]}:"+
261                       "#{$arvados_config["PostgreSQL"]["Connection"]["Password"]}@"+
262                       "#{dbhost}/#{$arvados_config["PostgreSQL"]["Connection"]["DBName"]}?"+
263                       "template=#{$arvados_config["PostgreSQL"]["Connection"]["Template"]}&"+
264                       "encoding=#{$arvados_config["PostgreSQL"]["Connection"]["client_encoding"]}&"+
265                       "pool=#{$arvados_config["PostgreSQL"]["ConnectionPool"]}"
266
267 Server::Application.configure do
268   # Copy into the Rails config object.  This also turns Hash into
269   # OrderedOptions so that application code can use
270   # Rails.configuration.API.Blah instead of
271   # Rails.configuration.API["Blah"]
272   ConfigLoader.copy_into_config $arvados_config, config
273   ConfigLoader.copy_into_config $remaining_config, config
274   secrets.secret_key_base = $arvados_config["API"]["RailsSessionSecretToken"]
275 end