closes #6156
[arvados.git] / services / api / app / models / node.rb
1 class Node < ArvadosModel
2   include HasUuid
3   include KindAndEtag
4   include CommonApiTemplate
5   serialize :info, Hash
6   serialize :properties, Hash
7   before_validation :ensure_ping_secret
8   after_update :dns_server_update
9
10   # Only a controller can figure out whether or not the current API tokens
11   # have access to the associated Job.  They're expected to set
12   # job_readable=true if the Job UUID can be included in the API response.
13   belongs_to(:job, foreign_key: :job_uuid, primary_key: :uuid)
14   attr_accessor :job_readable
15
16   api_accessible :user, :extend => :common do |t|
17     t.add :hostname
18     t.add :domain
19     t.add :ip_address
20     t.add :last_ping_at
21     t.add :slot_number
22     t.add :status
23     t.add :api_job_uuid, as: :job_uuid
24     t.add :crunch_worker_state
25     t.add :properties
26   end
27   api_accessible :superuser, :extend => :user do |t|
28     t.add :first_ping_at
29     t.add :info
30     t.add lambda { |x| Rails.configuration.compute_node_nameservers }, :as => :nameservers
31   end
32
33   def domain
34     super || Rails.configuration.compute_node_domain
35   end
36
37   def api_job_uuid
38     job_readable ? job_uuid : nil
39   end
40
41   def crunch_worker_state
42     return 'down' if slot_number.nil?
43     case self.info.andand['slurm_state']
44     when 'alloc', 'comp'
45       'busy'
46     when 'idle'
47       'idle'
48     else
49       'down'
50     end
51   end
52
53   def status
54     if !self.last_ping_at
55       if db_current_time - self.created_at > 5.minutes
56         'startup-fail'
57       else
58         'pending'
59       end
60     elsif db_current_time - self.last_ping_at > 1.hours
61       'missing'
62     else
63       'running'
64     end
65   end
66
67   def ping(o)
68     raise "must have :ip and :ping_secret" unless o[:ip] and o[:ping_secret]
69
70     if o[:ping_secret] != self.info['ping_secret']
71       logger.info "Ping: secret mismatch: received \"#{o[:ping_secret]}\" != \"#{self.info['ping_secret']}\""
72       raise ArvadosModel::UnauthorizedError.new("Incorrect ping_secret")
73     end
74
75     current_time = db_current_time
76     self.last_ping_at = current_time
77
78     @bypass_arvados_authorization = true
79
80     # Record IP address
81     if self.ip_address.nil?
82       logger.info "#{self.uuid} ip_address= #{o[:ip]}"
83       self.ip_address = o[:ip]
84       self.first_ping_at = current_time
85     end
86
87     # Record instance ID if not already known
88     if o[:ec2_instance_id]
89       if !self.info['ec2_instance_id']
90         self.info['ec2_instance_id'] = o[:ec2_instance_id]
91       elsif self.info['ec2_instance_id'] != o[:ec2_instance_id]
92         logger.debug "Multiple nodes have credentials for #{self.uuid}"
93         raise "#{self.uuid} is already running at #{self.info['ec2_instance_id']} so rejecting ping from #{o[:ec2_instance_id]}"
94       end
95     end
96
97     # Assign slot_number
98     if self.slot_number.nil?
99       try_slot = 0
100       begin
101         self.slot_number = try_slot
102         begin
103           self.save!
104           break
105         rescue ActiveRecord::RecordNotUnique
106           try_slot += 1
107         end
108         raise "No available node slots" if try_slot == Rails.configuration.max_compute_nodes
109       end while true
110     end
111
112     # Assign hostname
113     if self.hostname.nil? and Rails.configuration.assign_node_hostname
114       self.hostname = self.class.hostname_for_slot(self.slot_number)
115     end
116
117     # Record other basic stats
118     ['total_cpu_cores', 'total_ram_mb', 'total_scratch_mb'].each do |key|
119       if value = (o[key] or o[key.to_sym])
120         self.properties[key] = value.to_i
121       else
122         self.properties.delete(key)
123       end
124     end
125
126     save!
127   end
128
129   protected
130
131   def ensure_ping_secret
132     self.info['ping_secret'] ||= rand(2**256).to_s(36)
133   end
134
135   def dns_server_update
136     if self.hostname_changed? or self.ip_address_changed?
137       if not self.ip_address.nil?
138         stale_conflicting_nodes = Node.where('id != ? and ip_address = ? and last_ping_at < ?',self.id,self.ip_address,10.minutes.ago)
139         if not stale_conflicting_nodes.empty?
140           # One or more stale compute node records have the same IP address as the new node.
141           # Clear the ip_address field on the stale nodes.
142           stale_conflicting_nodes.each do |stale_node|
143             stale_node.ip_address = nil
144             stale_node.save!
145           end
146         end
147       end
148       if self.hostname and self.ip_address
149         self.class.dns_server_update(self.hostname, self.ip_address)
150       end
151     end
152   end
153
154   def self.dns_server_update hostname, ip_address
155     ok = true
156
157     ptr_domain = ip_address.
158       split('.').reverse.join('.').concat('.in-addr.arpa')
159
160     template_vars = {
161       hostname: hostname,
162       uuid_prefix: Rails.configuration.uuid_prefix,
163       ip_address: ip_address,
164       ptr_domain: ptr_domain,
165     }
166
167     if Rails.configuration.dns_server_conf_dir and Rails.configuration.dns_server_conf_template
168       begin
169         begin
170           template = IO.read(Rails.configuration.dns_server_conf_template)
171         rescue => e
172           logger.error "Reading #{Rails.configuration.dns_server_conf_template}: #{e.message}"
173           raise
174         end
175
176         hostfile = File.join Rails.configuration.dns_server_conf_dir, "#{hostname}.conf"
177         File.open hostfile+'.tmp', 'w' do |f|
178           f.puts template % template_vars
179         end
180         File.rename hostfile+'.tmp', hostfile
181       rescue => e
182         logger.error "Writing #{hostfile}: #{e.message}"
183         ok = false
184       end
185     end
186
187     if Rails.configuration.dns_server_update_command
188       cmd = Rails.configuration.dns_server_update_command % template_vars
189       if not system cmd
190         logger.error "dns_server_update_command #{cmd.inspect} failed: #{$?}"
191         ok = false
192       end
193     end
194
195     if Rails.configuration.dns_server_conf_dir and Rails.configuration.dns_server_reload_command
196       restartfile = File.join(Rails.configuration.dns_server_conf_dir, 'restart.txt')
197       begin
198         File.open(restartfile, 'w') do |f|
199           # Typically, this is used to trigger a dns server restart
200           f.puts Rails.configuration.dns_server_reload_command
201         end
202       rescue => e
203         logger.error "Unable to write #{restartfile}: #{e.message}"
204         ok = false
205       end
206     end
207
208     ok
209   end
210
211   def self.hostname_for_slot(slot_number)
212     config = Rails.configuration.assign_node_hostname
213
214     return nil if !config
215
216     sprintf(config, {:slot_number => slot_number})
217   end
218
219   # At startup, make sure all DNS entries exist.  Otherwise, slurmctld
220   # will refuse to start.
221   if Rails.configuration.dns_server_conf_dir and Rails.configuration.dns_server_conf_template and Rails.configuration.assign_node_hostname
222     (0..Rails.configuration.max_compute_nodes-1).each do |slot_number|
223       hostname = hostname_for_slot(slot_number)
224       hostfile = File.join Rails.configuration.dns_server_conf_dir, "#{hostname}.conf"
225       if !File.exists? hostfile
226         n = Node.where(:slot_number => slot_number).first
227         if n.nil? or n.ip_address.nil?
228           dns_server_update(hostname, '127.40.4.0')
229         else
230           dns_server_update(hostname, n.ip_address)
231         end
232       end
233     end
234   end
235
236   def permission_to_update
237     @bypass_arvados_authorization or super
238   end
239
240   def permission_to_create
241     current_user and current_user.is_admin
242   end
243 end