3d8b91b4b62df590edd2c1049a5ea69e17224bef
[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
110
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
115       else
116         self.properties.delete(key)
117       end
118     end
119
120     save!
121   end
122
123   def assign_slot
124     return if self.slot_number.andand > 0
125     while true
126       self.slot_number = self.class.available_slot_number
127       if self.slot_number.nil?
128         raise "No available node slots"
129       end
130       begin
131         save!
132         return assign_hostname
133       rescue ActiveRecord::RecordNotUnique
134         # try again
135       end
136     end
137   end
138
139   protected
140
141   def assign_hostname
142     if self.hostname.nil? and Rails.configuration.assign_node_hostname
143       self.hostname = self.class.hostname_for_slot(self.slot_number)
144     end
145   end
146
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
150     # existing node.
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
154                           LIMIT 1',
155                           # query label:
156                           'Node.available_slot_number',
157                           # [col_id, val] for $1 vars:
158                           [[nil, Rails.configuration.max_compute_nodes]],
159                          ).rows.first.andand.first
160   end
161
162   def ensure_ping_secret
163     self.info['ping_secret'] ||= rand(2**256).to_s(36)
164   end
165
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)
175       end
176     end
177     if hostname_was && hostname_changed?
178       self.class.dns_server_update(hostname_was, UNUSED_NODE_IP)
179     end
180     if hostname && (hostname_changed? || ip_address_changed?)
181       self.class.dns_server_update(hostname, ip_address || UNUSED_NODE_IP)
182     end
183   end
184
185   def self.dns_server_update hostname, ip_address
186     ok = true
187
188     ptr_domain = ip_address.
189       split('.').reverse.join('.').concat('.in-addr.arpa')
190
191     template_vars = {
192       hostname: hostname,
193       uuid_prefix: Rails.configuration.uuid_prefix,
194       ip_address: ip_address,
195       ptr_domain: ptr_domain,
196     }
197
198     if Rails.configuration.dns_server_conf_dir and Rails.configuration.dns_server_conf_template
199       tmpfile = nil
200       begin
201         begin
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}"
205           raise
206         end
207
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|
211           tmpfile = f.path
212           f.puts template % template_vars
213         end
214         File.rename tmpfile, hostfile
215       rescue IOError, SystemCallError => e
216         logger.error "Writing #{hostfile}: #{e.message}"
217         ok = false
218       ensure
219         if tmpfile and File.file? tmpfile
220           # Cleanup remaining temporary file.
221           File.unlink tmpfile
222         end
223       end
224     end
225
226     if Rails.configuration.dns_server_update_command
227       cmd = Rails.configuration.dns_server_update_command % template_vars
228       if not system cmd
229         logger.error "dns_server_update_command #{cmd.inspect} failed: #{$?}"
230         ok = false
231       end
232     end
233
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')
236       begin
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
240         end
241       rescue IOError, SystemCallError => e
242         logger.error "Unable to write #{restartfile}: #{e.message}"
243         ok = false
244       end
245     end
246
247     ok
248   end
249
250   def self.hostname_for_slot(slot_number)
251     config = Rails.configuration.assign_node_hostname
252
253     return nil if !config
254
255     sprintf(config, {:slot_number => slot_number})
256   end
257
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)
268         else
269           dns_server_update(hostname, n.ip_address)
270         end
271       end
272     end
273   end
274
275   def permission_to_update
276     @bypass_arvados_authorization or super
277   end
278
279   def permission_to_create
280     current_user and current_user.is_admin
281   end
282 end