1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
7 class Node < ArvadosModel
10 include CommonApiTemplate
12 # Posgresql JSONB columns should NOT be declared as serialized, Rails 5
13 # already know how to properly treat them.
15 before_validation :fill_field_defaults
16 before_validation :ensure_ping_secret
17 after_update :dns_server_update
19 # Only a controller can figure out whether or not the current API tokens
20 # have access to the associated Job. They're expected to set
21 # job_readable=true if the Job UUID can be included in the API response.
22 belongs_to(:job, foreign_key: :job_uuid, primary_key: :uuid)
23 attr_accessor :job_readable
25 UNUSED_NODE_IP = '127.40.4.0'
27 api_accessible :user, :extend => :common do |t|
34 t.add :api_job_uuid, as: :job_uuid
35 t.add :crunch_worker_state
38 api_accessible :superuser, :extend => :user do |t|
41 t.add lambda { |x| Rails.configuration.compute_node_nameservers }, :as => :nameservers
45 @bypass_arvados_authorization = false
49 super || Rails.configuration.compute_node_domain
53 job_readable ? job_uuid : nil
56 def crunch_worker_state
57 return 'down' if slot_number.nil?
58 case self.info.andand['slurm_state']
59 when 'alloc', 'comp', 'mix', 'drng'
70 if db_current_time - self.created_at > 5.minutes
75 elsif db_current_time - self.last_ping_at > 1.hours
83 raise "must have :ip and :ping_secret" unless o[:ip] and o[:ping_secret]
85 if o[:ping_secret] != self.info['ping_secret']
86 logger.info "Ping: secret mismatch: received \"#{o[:ping_secret]}\" != \"#{self.info['ping_secret']}\""
87 raise ArvadosModel::UnauthorizedError.new("Incorrect ping_secret")
90 current_time = db_current_time
91 self.last_ping_at = current_time
93 @bypass_arvados_authorization = true
96 if self.ip_address.nil?
97 logger.info "#{self.uuid} ip_address= #{o[:ip]}"
98 self.ip_address = o[:ip]
99 self.first_ping_at = current_time
102 # Record instance ID if not already known
103 if o[:ec2_instance_id]
104 if !self.info['ec2_instance_id']
105 self.info['ec2_instance_id'] = o[:ec2_instance_id]
106 elsif self.info['ec2_instance_id'] != o[:ec2_instance_id]
107 logger.debug "Multiple nodes have credentials for #{self.uuid}"
108 raise "#{self.uuid} is already running at #{self.info['ec2_instance_id']} so rejecting ping from #{o[:ec2_instance_id]}"
114 # Record other basic stats
115 ['total_cpu_cores', 'total_ram_mb', 'total_scratch_mb'].each do |key|
116 if value = (o[key] or o[key.to_sym])
117 self.properties[key] = value.to_i
119 self.properties.delete(key)
127 return if self.slot_number.andand > 0
129 self.slot_number = self.class.available_slot_number
130 if self.slot_number.nil?
131 raise "No available node slots"
135 return assign_hostname
136 rescue ActiveRecord::RecordNotUnique
144 def fill_field_defaults
146 self.properties ||= {}
150 if self.hostname.nil? and Rails.configuration.assign_node_hostname
151 self.hostname = self.class.hostname_for_slot(self.slot_number)
155 def self.available_slot_number
156 # Join the sequence 1..max with the nodes table. Return the first
157 # (i.e., smallest) value that doesn't match the slot_number of any
159 connection.exec_query('SELECT n FROM generate_series(1, $1) AS slot(n)
160 LEFT JOIN nodes ON n=slot_number
161 WHERE slot_number IS NULL
164 'Node.available_slot_number',
165 # [col_id, val] for $1 vars:
166 [[nil, Rails.configuration.max_compute_nodes]],
167 ).rows.first.andand.first
170 def ensure_ping_secret
171 self.info['ping_secret'] ||= rand(2**256).to_s(36)
174 def dns_server_update
175 if ip_address_changed? && ip_address
176 Node.where('id != ? and ip_address = ?',
177 id, ip_address).each do |stale_node|
178 # One or more(!) stale node records have the same IP address
179 # as the new node. Clear the ip_address field on the stale
180 # nodes. Otherwise, we (via SLURM) might inadvertently connect
181 # to the new node using the old node's hostname.
182 stale_node.update_attributes!(ip_address: nil)
185 if hostname_was && hostname_changed?
186 self.class.dns_server_update(hostname_was, UNUSED_NODE_IP)
188 if hostname && (hostname_changed? || ip_address_changed?)
189 self.class.dns_server_update(hostname, ip_address || UNUSED_NODE_IP)
193 def self.dns_server_update hostname, ip_address
196 ptr_domain = ip_address.
197 split('.').reverse.join('.').concat('.in-addr.arpa')
201 uuid_prefix: Rails.configuration.uuid_prefix,
202 ip_address: ip_address,
203 ptr_domain: ptr_domain,
206 if Rails.configuration.dns_server_conf_dir and Rails.configuration.dns_server_conf_template
210 template = IO.read(Rails.configuration.dns_server_conf_template)
211 rescue IOError, SystemCallError => e
212 logger.error "Reading #{Rails.configuration.dns_server_conf_template}: #{e.message}"
216 hostfile = File.join Rails.configuration.dns_server_conf_dir, "#{hostname}.conf"
217 Tempfile.open(["#{hostname}-", ".conf.tmp"],
218 Rails.configuration.dns_server_conf_dir) do |f|
220 f.puts template % template_vars
222 File.rename tmpfile, hostfile
223 rescue IOError, SystemCallError => e
224 logger.error "Writing #{hostfile}: #{e.message}"
227 if tmpfile and File.file? tmpfile
228 # Cleanup remaining temporary file.
234 if Rails.configuration.dns_server_update_command
235 cmd = Rails.configuration.dns_server_update_command % template_vars
237 logger.error "dns_server_update_command #{cmd.inspect} failed: #{$?}"
242 if Rails.configuration.dns_server_conf_dir and Rails.configuration.dns_server_reload_command
243 restartfile = File.join(Rails.configuration.dns_server_conf_dir, 'restart.txt')
245 File.open(restartfile, 'w') do |f|
246 # Typically, this is used to trigger a dns server restart
247 f.puts Rails.configuration.dns_server_reload_command
249 rescue IOError, SystemCallError => e
250 logger.error "Unable to write #{restartfile}: #{e.message}"
258 def self.hostname_for_slot(slot_number)
259 config = Rails.configuration.assign_node_hostname
261 return nil if !config
263 sprintf(config, {:slot_number => slot_number})
266 # At startup, make sure all DNS entries exist. Otherwise, slurmctld
267 # will refuse to start.
268 if Rails.configuration.dns_server_conf_dir and Rails.configuration.dns_server_conf_template and Rails.configuration.assign_node_hostname
269 (0..Rails.configuration.max_compute_nodes-1).each do |slot_number|
270 hostname = hostname_for_slot(slot_number)
271 hostfile = File.join Rails.configuration.dns_server_conf_dir, "#{hostname}.conf"
272 if !File.exist? hostfile
273 n = Node.where(:slot_number => slot_number).first
274 if n.nil? or n.ip_address.nil?
275 dns_server_update(hostname, UNUSED_NODE_IP)
277 dns_server_update(hostname, n.ip_address)
283 def permission_to_update
284 @bypass_arvados_authorization or super
287 def permission_to_create
288 current_user and current_user.is_admin