1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
7 class Node < ArvadosModel
10 include CommonApiTemplate
12 serialize :properties, Hash
13 before_validation :ensure_ping_secret
14 after_update :dns_server_update
16 # Only a controller can figure out whether or not the current API tokens
17 # have access to the associated Job. They're expected to set
18 # job_readable=true if the Job UUID can be included in the API response.
19 belongs_to(:job, foreign_key: :job_uuid, primary_key: :uuid)
20 attr_accessor :job_readable
22 UNUSED_NODE_IP = '127.40.4.0'
24 api_accessible :user, :extend => :common do |t|
31 t.add :api_job_uuid, as: :job_uuid
32 t.add :crunch_worker_state
35 api_accessible :superuser, :extend => :user do |t|
38 t.add lambda { |x| Rails.configuration.compute_node_nameservers }, :as => :nameservers
42 @bypass_arvados_authorization = false
46 super || Rails.configuration.compute_node_domain
50 job_readable ? job_uuid : nil
53 def crunch_worker_state
54 return 'down' if slot_number.nil?
55 case self.info.andand['slurm_state']
56 when 'alloc', 'comp', 'mix', 'drng'
67 if db_current_time - self.created_at > 5.minutes
72 elsif db_current_time - self.last_ping_at > 1.hours
80 raise "must have :ip and :ping_secret" unless o[:ip] and o[:ping_secret]
82 if o[:ping_secret] != self.info['ping_secret']
83 logger.info "Ping: secret mismatch: received \"#{o[:ping_secret]}\" != \"#{self.info['ping_secret']}\""
84 raise ArvadosModel::UnauthorizedError.new("Incorrect ping_secret")
87 current_time = db_current_time
88 self.last_ping_at = current_time
90 @bypass_arvados_authorization = true
93 if self.ip_address.nil?
94 logger.info "#{self.uuid} ip_address= #{o[:ip]}"
95 self.ip_address = o[:ip]
96 self.first_ping_at = current_time
99 # Record instance ID if not already known
100 if o[:ec2_instance_id]
101 if !self.info['ec2_instance_id']
102 self.info['ec2_instance_id'] = o[:ec2_instance_id]
103 elsif self.info['ec2_instance_id'] != o[:ec2_instance_id]
104 logger.debug "Multiple nodes have credentials for #{self.uuid}"
105 raise "#{self.uuid} is already running at #{self.info['ec2_instance_id']} so rejecting ping from #{o[:ec2_instance_id]}"
111 # Record other basic stats
112 ['total_cpu_cores', 'total_ram_mb', 'total_scratch_mb'].each do |key|
113 if value = (o[key] or o[key.to_sym])
114 self.properties[key] = value.to_i
116 self.properties.delete(key)
124 return if self.slot_number.andand > 0
126 self.slot_number = self.class.available_slot_number
127 if self.slot_number.nil?
128 raise "No available node slots"
132 return assign_hostname
133 rescue ActiveRecord::RecordNotUnique
142 if self.hostname.nil? and Rails.configuration.assign_node_hostname
143 self.hostname = self.class.hostname_for_slot(self.slot_number)
147 def self.available_slot_number
148 # Join the sequence 1..max with the nodes table. Return the first
149 # (i.e., smallest) value that doesn't match the slot_number of any
151 connection.exec_query('SELECT n FROM generate_series(1, $1) AS slot(n)
152 LEFT JOIN nodes ON n=slot_number
153 WHERE slot_number IS NULL
156 'Node.available_slot_number',
157 # [col_id, val] for $1 vars:
158 [[nil, Rails.configuration.max_compute_nodes]],
159 ).rows.first.andand.first
162 def ensure_ping_secret
163 self.info['ping_secret'] ||= rand(2**256).to_s(36)
166 def dns_server_update
167 if ip_address_changed? && ip_address
168 Node.where('id != ? and ip_address = ?',
169 id, ip_address).each do |stale_node|
170 # One or more(!) stale node records have the same IP address
171 # as the new node. Clear the ip_address field on the stale
172 # nodes. Otherwise, we (via SLURM) might inadvertently connect
173 # to the new node using the old node's hostname.
174 stale_node.update_attributes!(ip_address: nil)
177 if hostname_was && hostname_changed?
178 self.class.dns_server_update(hostname_was, UNUSED_NODE_IP)
180 if hostname && (hostname_changed? || ip_address_changed?)
181 self.class.dns_server_update(hostname, ip_address || UNUSED_NODE_IP)
185 def self.dns_server_update hostname, ip_address
188 ptr_domain = ip_address.
189 split('.').reverse.join('.').concat('.in-addr.arpa')
193 uuid_prefix: Rails.configuration.uuid_prefix,
194 ip_address: ip_address,
195 ptr_domain: ptr_domain,
198 if Rails.configuration.dns_server_conf_dir and Rails.configuration.dns_server_conf_template
202 template = IO.read(Rails.configuration.dns_server_conf_template)
203 rescue IOError, SystemCallError => e
204 logger.error "Reading #{Rails.configuration.dns_server_conf_template}: #{e.message}"
208 hostfile = File.join Rails.configuration.dns_server_conf_dir, "#{hostname}.conf"
209 Tempfile.open(["#{hostname}-", ".conf.tmp"],
210 Rails.configuration.dns_server_conf_dir) do |f|
212 f.puts template % template_vars
214 File.rename tmpfile, hostfile
215 rescue IOError, SystemCallError => e
216 logger.error "Writing #{hostfile}: #{e.message}"
219 if tmpfile and File.file? tmpfile
220 # Cleanup remaining temporary file.
226 if Rails.configuration.dns_server_update_command
227 cmd = Rails.configuration.dns_server_update_command % template_vars
229 logger.error "dns_server_update_command #{cmd.inspect} failed: #{$?}"
234 if Rails.configuration.dns_server_conf_dir and Rails.configuration.dns_server_reload_command
235 restartfile = File.join(Rails.configuration.dns_server_conf_dir, 'restart.txt')
237 File.open(restartfile, 'w') do |f|
238 # Typically, this is used to trigger a dns server restart
239 f.puts Rails.configuration.dns_server_reload_command
241 rescue IOError, SystemCallError => e
242 logger.error "Unable to write #{restartfile}: #{e.message}"
250 def self.hostname_for_slot(slot_number)
251 config = Rails.configuration.assign_node_hostname
253 return nil if !config
255 sprintf(config, {:slot_number => slot_number})
258 # At startup, make sure all DNS entries exist. Otherwise, slurmctld
259 # will refuse to start.
260 if Rails.configuration.dns_server_conf_dir and Rails.configuration.dns_server_conf_template and Rails.configuration.assign_node_hostname
261 (0..Rails.configuration.max_compute_nodes-1).each do |slot_number|
262 hostname = hostname_for_slot(slot_number)
263 hostfile = File.join Rails.configuration.dns_server_conf_dir, "#{hostname}.conf"
264 if !File.exist? hostfile
265 n = Node.where(:slot_number => slot_number).first
266 if n.nil? or n.ip_address.nil?
267 dns_server_update(hostname, UNUSED_NODE_IP)
269 dns_server_update(hostname, n.ip_address)
275 def permission_to_update
276 @bypass_arvados_authorization or super
279 def permission_to_create
280 current_user and current_user.is_admin