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