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