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