3960: Merge branch 'master' into 3960-show-more-repos
[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 :dnsmasq_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   MAX_SLOTS = 64
17
18   @@confdir = Rails.configuration.dnsmasq_conf_dir
19   @@domain = Rails.configuration.compute_node_domain rescue `hostname --domain`.strip
20   @@nameservers = Rails.configuration.compute_node_nameservers
21
22   api_accessible :user, :extend => :common do |t|
23     t.add :hostname
24     t.add :domain
25     t.add :ip_address
26     t.add :last_ping_at
27     t.add :slot_number
28     t.add :status
29     t.add :api_job_uuid, as: :job_uuid
30     t.add :crunch_worker_state
31     t.add :properties
32   end
33   api_accessible :superuser, :extend => :user do |t|
34     t.add :first_ping_at
35     t.add :info
36     t.add lambda { |x| @@nameservers }, :as => :nameservers
37   end
38
39   def domain
40     super || @@domain
41   end
42
43   def api_job_uuid
44     job_readable ? job_uuid : nil
45   end
46
47   def crunch_worker_state
48     return 'down' if slot_number.nil?
49     case self.info.andand['slurm_state']
50     when 'alloc', 'comp'
51       'busy'
52     when 'idle'
53       'idle'
54     else
55       'down'
56     end
57   end
58
59   def status
60     if !self.last_ping_at
61       if Time.now - self.created_at > 5.minutes
62         'startup-fail'
63       else
64         'pending'
65       end
66     elsif Time.now - self.last_ping_at > 1.hours
67       'missing'
68     else
69       'running'
70     end
71   end
72
73   def ping(o)
74     raise "must have :ip and :ping_secret" unless o[:ip] and o[:ping_secret]
75
76     if o[:ping_secret] != self.info['ping_secret']
77       logger.info "Ping: secret mismatch: received \"#{o[:ping_secret]}\" != \"#{self.info['ping_secret']}\""
78       raise ArvadosModel::UnauthorizedError.new("Incorrect ping_secret")
79     end
80     self.last_ping_at = Time.now
81
82     @bypass_arvados_authorization = true
83
84     # Record IP address
85     if self.ip_address.nil?
86       logger.info "#{self.uuid} ip_address= #{o[:ip]}"
87       self.ip_address = o[:ip]
88       self.first_ping_at = Time.now
89     end
90
91     # Record instance ID if not already known
92     if o[:ec2_instance_id]
93       if !self.info['ec2_instance_id']
94         self.info['ec2_instance_id'] = o[:ec2_instance_id]
95         if (Rails.configuration.compute_node_ec2_tag_enable rescue true)
96           tag_cmd = ("ec2-create-tags #{o[:ec2_instance_id]} " +
97                      "--tag 'Name=#{self.uuid}'")
98           `#{tag_cmd}`
99         end
100       elsif self.info['ec2_instance_id'] != o[:ec2_instance_id]
101         logger.debug "Multiple nodes have credentials for #{self.uuid}"
102         raise "#{self.uuid} is already running at #{self.info['ec2_instance_id']} so rejecting ping from #{o[:ec2_instance_id]}"
103       end
104     end
105
106     # Assign hostname
107     if self.slot_number.nil?
108       try_slot = 0
109       begin
110         self.slot_number = try_slot
111         begin
112           self.save!
113           break
114         rescue ActiveRecord::RecordNotUnique
115           try_slot += 1
116         end
117         raise "No available node slots" if try_slot == MAX_SLOTS
118       end while true
119       self.hostname = self.class.hostname_for_slot(self.slot_number)
120       if info['ec2_instance_id']
121         if (Rails.configuration.compute_node_ec2_tag_enable rescue true)
122           `ec2-create-tags #{self.info['ec2_instance_id']} --tag 'hostname=#{self.hostname}'`
123         end
124       end
125     end
126
127     # Record other basic stats
128     ['total_cpu_cores', 'total_ram_mb', 'total_scratch_mb'].each do |key|
129       if value = (o[key] or o[key.to_sym])
130         self.properties[key] = value.to_i
131       else
132         self.properties.delete(key)
133       end
134     end
135
136     save!
137   end
138
139   def start!(ping_url_method)
140     ensure_permission_to_save
141     ping_url = ping_url_method.call({ id: self.uuid, ping_secret: self.info['ping_secret'] })
142     if (Rails.configuration.compute_node_ec2run_args and
143         Rails.configuration.compute_node_ami)
144       ec2_args = ["--user-data '#{ping_url}'",
145                   "-t c1.xlarge -n 1",
146                   Rails.configuration.compute_node_ec2run_args,
147                   Rails.configuration.compute_node_ami
148                  ]
149       ec2run_cmd = ["ec2-run-instances",
150                     "--client-token", self.uuid,
151                     ec2_args].flatten.join(' ')
152       ec2spot_cmd = ["ec2-request-spot-instances",
153                      "-p #{Rails.configuration.compute_node_spot_bid} --type one-time",
154                      ec2_args].flatten.join(' ')
155     else
156       ec2run_cmd = ''
157       ec2spot_cmd = ''
158     end
159     self.info['ec2_run_command'] = ec2run_cmd
160     self.info['ec2_spot_command'] = ec2spot_cmd
161     self.info['ec2_start_command'] = ec2spot_cmd
162     logger.info "#{self.uuid} ec2_start_command= #{ec2spot_cmd.inspect}"
163     result = `#{ec2spot_cmd} 2>&1`
164     self.info['ec2_start_result'] = result
165     logger.info "#{self.uuid} ec2_start_result= #{result.inspect}"
166     result.match(/INSTANCE\s*(i-[0-9a-f]+)/) do |m|
167       instance_id = m[1]
168       self.info['ec2_instance_id'] = instance_id
169       if (Rails.configuration.compute_node_ec2_tag_enable rescue true)
170         `ec2-create-tags #{instance_id} --tag 'Name=#{self.uuid}'`
171       end
172     end
173     result.match(/SPOTINSTANCEREQUEST\s*(sir-[0-9a-f]+)/) do |m|
174       sir_id = m[1]
175       self.info['ec2_sir_id'] = sir_id
176       if (Rails.configuration.compute_node_ec2_tag_enable rescue true)
177         `ec2-create-tags #{sir_id} --tag 'Name=#{self.uuid}'`
178       end
179     end
180     self.save!
181   end
182
183   protected
184
185   def ensure_ping_secret
186     self.info['ping_secret'] ||= rand(2**256).to_s(36)
187   end
188
189   def dnsmasq_update
190     if self.hostname_changed? or self.ip_address_changed?
191       if self.hostname and self.ip_address
192         self.class.dnsmasq_update(self.hostname, self.ip_address)
193       end
194     end
195   end
196
197   def self.dnsmasq_update(hostname, ip_address)
198     return unless @@confdir
199     ptr_domain = ip_address.
200       split('.').reverse.join('.').concat('.in-addr.arpa')
201     hostfile = File.join @@confdir, hostname
202     File.open hostfile, 'w' do |f|
203       f.puts "address=/#{hostname}/#{ip_address}"
204       f.puts "address=/#{hostname}.#{@@domain}/#{ip_address}" if @@domain
205       f.puts "ptr-record=#{ptr_domain},#{hostname}"
206     end
207     File.open(File.join(@@confdir, 'restart.txt'), 'w') do |f|
208       # this should trigger a dnsmasq restart
209     end
210   end
211
212   def self.hostname_for_slot(slot_number)
213     "compute#{slot_number}"
214   end
215
216   # At startup, make sure all DNS entries exist.  Otherwise, slurmctld
217   # will refuse to start.
218   if @@confdir and
219       !File.exists? (File.join(@@confdir, hostname_for_slot(MAX_SLOTS-1)))
220     (0..MAX_SLOTS-1).each do |slot_number|
221       hostname = hostname_for_slot(slot_number)
222       hostfile = File.join @@confdir, hostname
223       if !File.exists? hostfile
224         dnsmasq_update(hostname, '127.40.4.0')
225       end
226     end
227   end
228
229   def permission_to_update
230     @bypass_arvados_authorization or super
231   end
232
233   def permission_to_create
234     current_user and current_user.is_admin
235   end
236 end