Merge branch '8784-dir-listings'
[arvados.git] / services / api / app / models / node.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require 'tempfile'
6
7 class Node < ArvadosModel
8   include HasUuid
9   include KindAndEtag
10   include CommonApiTemplate
11   serialize :info, Hash
12   serialize :properties, Hash
13   before_validation :ensure_ping_secret
14   after_update :dns_server_update
15
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
21
22   UNUSED_NODE_IP = '127.40.4.0'
23
24   api_accessible :user, :extend => :common do |t|
25     t.add :hostname
26     t.add :domain
27     t.add :ip_address
28     t.add :last_ping_at
29     t.add :slot_number
30     t.add :status
31     t.add :api_job_uuid, as: :job_uuid
32     t.add :crunch_worker_state
33     t.add :properties
34   end
35   api_accessible :superuser, :extend => :user do |t|
36     t.add :first_ping_at
37     t.add :info
38     t.add lambda { |x| Rails.configuration.compute_node_nameservers }, :as => :nameservers
39   end
40
41   after_initialize do
42     @bypass_arvados_authorization = false
43   end
44
45   def domain
46     super || Rails.configuration.compute_node_domain
47   end
48
49   def api_job_uuid
50     job_readable ? job_uuid : nil
51   end
52
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'
57       'busy'
58     when 'idle'
59       'idle'
60     else
61       'down'
62     end
63   end
64
65   def status
66     if !self.last_ping_at
67       if db_current_time - self.created_at > 5.minutes
68         'startup-fail'
69       else
70         'pending'
71       end
72     elsif db_current_time - self.last_ping_at > 1.hours
73       'missing'
74     else
75       'running'
76     end
77   end
78
79   def ping(o)
80     raise "must have :ip and :ping_secret" unless o[:ip] and o[:ping_secret]
81
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")
85     end
86
87     current_time = db_current_time
88     self.last_ping_at = current_time
89
90     @bypass_arvados_authorization = true
91
92     # Record IP address
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
97     end
98
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]}"
106       end
107     end
108
109     # Assign slot_number
110     if self.slot_number.nil?
111       while true
112         n = self.class.available_slot_number
113         if n.nil?
114           raise "No available node slots"
115         end
116         self.slot_number = n
117         begin
118           self.save!
119           break
120         rescue ActiveRecord::RecordNotUnique
121           # try again
122         end
123       end
124     end
125
126     # Assign hostname
127     if self.hostname.nil? and Rails.configuration.assign_node_hostname
128       self.hostname = self.class.hostname_for_slot(self.slot_number)
129     end
130
131     # Record other basic stats
132     ['total_cpu_cores', 'total_ram_mb', 'total_scratch_mb'].each do |key|
133       if value = (o[key] or o[key.to_sym])
134         self.properties[key] = value.to_i
135       else
136         self.properties.delete(key)
137       end
138     end
139
140     save!
141   end
142
143   protected
144
145   def self.available_slot_number
146     # Join the sequence 1..max with the nodes table. Return the first
147     # (i.e., smallest) value that doesn't match the slot_number of any
148     # existing node.
149     connection.exec_query('SELECT n FROM generate_series(1, $1) AS slot(n)
150                           LEFT JOIN nodes ON n=slot_number
151                           WHERE slot_number IS NULL
152                           LIMIT 1',
153                           # query label:
154                           'Node.available_slot_number',
155                           # [col_id, val] for $1 vars:
156                           [[nil, Rails.configuration.max_compute_nodes]],
157                          ).rows.first.andand.first
158   end
159
160   def ensure_ping_secret
161     self.info['ping_secret'] ||= rand(2**256).to_s(36)
162   end
163
164   def dns_server_update
165     if ip_address_changed? && ip_address
166       Node.where('id != ? and ip_address = ?',
167                  id, ip_address).each do |stale_node|
168         # One or more(!) stale node records have the same IP address
169         # as the new node. Clear the ip_address field on the stale
170         # nodes. Otherwise, we (via SLURM) might inadvertently connect
171         # to the new node using the old node's hostname.
172         stale_node.update_attributes!(ip_address: nil)
173       end
174     end
175     if hostname_was && hostname_changed?
176       self.class.dns_server_update(hostname_was, UNUSED_NODE_IP)
177     end
178     if hostname && (hostname_changed? || ip_address_changed?)
179       self.class.dns_server_update(hostname, ip_address || UNUSED_NODE_IP)
180     end
181   end
182
183   def self.dns_server_update hostname, ip_address
184     ok = true
185
186     ptr_domain = ip_address.
187       split('.').reverse.join('.').concat('.in-addr.arpa')
188
189     template_vars = {
190       hostname: hostname,
191       uuid_prefix: Rails.configuration.uuid_prefix,
192       ip_address: ip_address,
193       ptr_domain: ptr_domain,
194     }
195
196     if Rails.configuration.dns_server_conf_dir and Rails.configuration.dns_server_conf_template
197       tmpfile = nil
198       begin
199         begin
200           template = IO.read(Rails.configuration.dns_server_conf_template)
201         rescue IOError, SystemCallError => e
202           logger.error "Reading #{Rails.configuration.dns_server_conf_template}: #{e.message}"
203           raise
204         end
205
206         hostfile = File.join Rails.configuration.dns_server_conf_dir, "#{hostname}.conf"
207         Tempfile.open(["#{hostname}-", ".conf.tmp"],
208                                  Rails.configuration.dns_server_conf_dir) do |f|
209           tmpfile = f.path
210           f.puts template % template_vars
211         end
212         File.rename tmpfile, hostfile
213       rescue IOError, SystemCallError => e
214         logger.error "Writing #{hostfile}: #{e.message}"
215         ok = false
216       ensure
217         if tmpfile and File.file? tmpfile
218           # Cleanup remaining temporary file.
219           File.unlink tmpfile
220         end
221       end
222     end
223
224     if Rails.configuration.dns_server_update_command
225       cmd = Rails.configuration.dns_server_update_command % template_vars
226       if not system cmd
227         logger.error "dns_server_update_command #{cmd.inspect} failed: #{$?}"
228         ok = false
229       end
230     end
231
232     if Rails.configuration.dns_server_conf_dir and Rails.configuration.dns_server_reload_command
233       restartfile = File.join(Rails.configuration.dns_server_conf_dir, 'restart.txt')
234       begin
235         File.open(restartfile, 'w') do |f|
236           # Typically, this is used to trigger a dns server restart
237           f.puts Rails.configuration.dns_server_reload_command
238         end
239       rescue IOError, SystemCallError => e
240         logger.error "Unable to write #{restartfile}: #{e.message}"
241         ok = false
242       end
243     end
244
245     ok
246   end
247
248   def self.hostname_for_slot(slot_number)
249     config = Rails.configuration.assign_node_hostname
250
251     return nil if !config
252
253     sprintf(config, {:slot_number => slot_number})
254   end
255
256   # At startup, make sure all DNS entries exist.  Otherwise, slurmctld
257   # will refuse to start.
258   if Rails.configuration.dns_server_conf_dir and Rails.configuration.dns_server_conf_template and Rails.configuration.assign_node_hostname
259     (0..Rails.configuration.max_compute_nodes-1).each do |slot_number|
260       hostname = hostname_for_slot(slot_number)
261       hostfile = File.join Rails.configuration.dns_server_conf_dir, "#{hostname}.conf"
262       if !File.exist? hostfile
263         n = Node.where(:slot_number => slot_number).first
264         if n.nil? or n.ip_address.nil?
265           dns_server_update(hostname, UNUSED_NODE_IP)
266         else
267           dns_server_update(hostname, n.ip_address)
268         end
269       end
270     end
271   end
272
273   def permission_to_update
274     @bypass_arvados_authorization or super
275   end
276
277   def permission_to_create
278     current_user and current_user.is_admin
279   end
280 end