4139: Remove cloud node setup code from API server.
[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       elsif self.info['ec2_instance_id'] != o[:ec2_instance_id]
96         logger.debug "Multiple nodes have credentials for #{self.uuid}"
97         raise "#{self.uuid} is already running at #{self.info['ec2_instance_id']} so rejecting ping from #{o[:ec2_instance_id]}"
98       end
99     end
100
101     # Assign hostname
102     if self.slot_number.nil?
103       try_slot = 0
104       begin
105         self.slot_number = try_slot
106         begin
107           self.save!
108           break
109         rescue ActiveRecord::RecordNotUnique
110           try_slot += 1
111         end
112         raise "No available node slots" if try_slot == MAX_SLOTS
113       end while true
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 dnsmasq_update
136     if self.hostname_changed? or self.ip_address_changed?
137       if self.hostname and self.ip_address
138         self.class.dnsmasq_update(self.hostname, self.ip_address)
139       end
140     end
141   end
142
143   def self.dnsmasq_update(hostname, ip_address)
144     return unless @@confdir
145     ptr_domain = ip_address.
146       split('.').reverse.join('.').concat('.in-addr.arpa')
147     hostfile = File.join @@confdir, hostname
148     File.open hostfile, 'w' do |f|
149       f.puts "address=/#{hostname}/#{ip_address}"
150       f.puts "address=/#{hostname}.#{@@domain}/#{ip_address}" if @@domain
151       f.puts "ptr-record=#{ptr_domain},#{hostname}"
152     end
153     File.open(File.join(@@confdir, 'restart.txt'), 'w') do |f|
154       # this should trigger a dnsmasq restart
155     end
156   end
157
158   def self.hostname_for_slot(slot_number)
159     "compute#{slot_number}"
160   end
161
162   # At startup, make sure all DNS entries exist.  Otherwise, slurmctld
163   # will refuse to start.
164   if @@confdir and
165       !File.exists? (File.join(@@confdir, hostname_for_slot(MAX_SLOTS-1)))
166     (0..MAX_SLOTS-1).each do |slot_number|
167       hostname = hostname_for_slot(slot_number)
168       hostfile = File.join @@confdir, hostname
169       if !File.exists? hostfile
170         dnsmasq_update(hostname, '127.40.4.0')
171       end
172     end
173   end
174
175   def permission_to_update
176     @bypass_arvados_authorization or super
177   end
178
179   def permission_to_create
180     current_user and current_user.is_admin
181   end
182 end