Class: OpenVZ::Container
- Inherits:
-
Object
- Object
- OpenVZ::Container
- Defined in:
- lib/openvz/container.rb
Overview
OpenVZ::Container
Defined Under Namespace
Classes: Config, StatemachineError
Instance Attribute Summary collapse
-
#config ⇒ Object
Returns the value of attribute config.
-
#ctid ⇒ Object
readonly
Returns the value of attribute ctid.
-
#rw config(config) ⇒ Object
OpenVZ::Container.
Instance Method Summary collapse
-
#add_veth(veth) ⇒ Object
Add veth to a CT vzctl set <CTID> –netif_add <ifname>.
-
#checkpoint(snapshot_path) ⇒ Object
Checkpoint the container.
-
#command(command) ⇒ Object
Run a shell command within the container.
-
#cp_into(options = {}) ⇒ Object
Copy a file from the hardware node into the container.
-
#create(options = {}) ⇒ Object
Create a new empty instance from a template.
-
#debootstrap(options = {}) ⇒ Object
Bootstrap a Debian container, this requires /usr/sbin/debootstrap to be installed.
-
#destroy ⇒ Object
Destroy a container.
-
#execute(cmd) ⇒ Object
Execute a System Command.
-
#file(filename, options = {}) ⇒ Object
Write into or copy a file into a container.
-
#initialize(ctid = false) ⇒ Container
constructor
A new instance of Container.
-
#load_config_file ⇒ Object
Load the container configration file.
-
#migrate(destination_address, options = %w(--remove-area yes --online --rsync=-az))) ⇒ Object
Migrate container to another node.
-
#mount ⇒ Object
Mount a container.
-
#restart ⇒ Object
Restart a container.
-
#restore(snapshot_path) ⇒ Object
Restore a checkpoint.
-
#set(options = {}) ⇒ Object
Update one or multiple Container properties and keep the configration object up to date.
-
#start ⇒ Object
Start a container.
-
#state(mode, action) ⇒ Object
Check whether current_state == :require||:validate.
- #state_require(*opts) ⇒ Object
-
#status ⇒ Object
Return the current machine status string.
-
#stop ⇒ Object
Stop a container.
-
#umount ⇒ Object
Umount a container.
-
#update(key, value) ⇒ Object
Notify Method! :-) Config objects will notify, as soon as they are changed.
-
#uptime ⇒ Object
Return the current uptime in seconds.
Constructor Details
#initialize(ctid = false) ⇒ Container
Returns a new instance of Container.
37 38 39 40 41 42 43 44 45 |
# File 'lib/openvz/container.rb', line 37 def initialize(ctid=false) @ctid = ctid @vzctl = "/usr/sbin/vzctl" @vzmigrate = "/usr/sbin/vzmigrate" @configfile = "/etc/vz/conf/#{ctid}.conf" @config = Config.new(load_config_file) @config.add_observer(self) end |
Instance Attribute Details
#config ⇒ Object
Returns the value of attribute config.
30 31 32 |
# File 'lib/openvz/container.rb', line 30 def config @config end |
#ctid ⇒ Object (readonly)
Returns the value of attribute ctid.
31 32 33 |
# File 'lib/openvz/container.rb', line 31 def ctid @ctid end |
#rw config(config) ⇒ Object
OpenVZ::Container
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 |
# File 'lib/openvz/container.rb', line 28 class Container attr_accessor :config attr_reader :ctid class StatemachineError < StandardError;end class Config < ::OpenVZ::ConfigHash ; end def initialize(ctid=false) @ctid = ctid @vzctl = "/usr/sbin/vzctl" @vzmigrate = "/usr/sbin/vzmigrate" @configfile = "/etc/vz/conf/#{ctid}.conf" @config = Config.new(load_config_file) @config.add_observer(self) end # Start a container # def start cmd = "#{@vzctl} start #{@ctid}" execute(cmd) end # Stop a container # def stop cmd = "#{@vzctl} stop #{@ctid}" execute(cmd) end # Restart a container # def restart cmd = "#{@vzctl} restart #{@ctid}" execute(cmd) end # Mount a container # def mount cmd = "#{@vzctl} mount #{@ctid}" execute(cmd) end # Umount a container # def umount cmd = "#{@vzctl} umount #{@ctid}" execute(cmd) end # Destroy a container # def destroy cmd = "#{@vzctl} destroy #{@ctid}" execute(cmd) end # Checkpoint the container # def checkpoint(snapshot_path) cmd = "#{@vzctl} chkpnt #{@ctid} --dumpfile #{snapshot_path}" execute(cmd) end # Restore a checkpoint # def restore(snapshot_path) cmd = "#{@vzctl} restore #{@ctid} --dumpfile #{snapshot_path}" execute(cmd) end # Migrate container to another node # def migrate(destination_address, =%w(--remove-area yes --online --rsync=-az)) cmd = "#{@vzmigrate} #{.join ' '} #{destination_address} #{@ctid}" execute(cmd) end # Update one or multiple Container properties and keep the configration # object up to date # # @param [Hash] The options to update, eg. `{ :privvmpages => '123:123' }` def set( = {}) # Construct a set command cmd = "#{@vzctl} set #{@ctid} --save" .each do |opt,val| cmd << " --#{opt}" cmd << " #{val}" end execute(cmd) # Each time we update a setting, reload the configuration. @config.load(@ctid) end # Create a new empty instance from a template. # # @example Create a new empty container from a template. # The following example will create a container, from an empty # template, which can be used to bootstrap the whole installation # later on. It will as well apply the vps.unlimited template config. # # container.create(:ostemplate => "debian-6.0-bootstrap", :config => "vps.unlimited") # # @param [Hash] options you want to pass to the create statement. def create(={}) unless [:ostemplate] # We need at least a valid ostemplate raise ArgumentError, "Create requires argument :ostemplate." end cmd = "#{@vzctl} create #{@ctid}" .each do |opt,val| cmd << " --#{opt}" cmd << " #{val}" end execute(cmd) Log.debug("Reading new container configuration file: #{@configfile}") @config = Config.new(load_config_file) @config.add_observer(self) end # Bootstrap a Debian container, this requires /usr/sbin/debootstrap to # be installed. Executing this function usually takes a while. # # @example Debootstrap a container object. # container.debootstrap(:dist => "squeeze", :mirror => "http://cdn.debian.net/debian") # # @example Debootstrap a container, include and exclude certain packages. # container.debootstrap( # :dist => "squeeze", # :mirror => "http://cdn.debian.net/debian", # :include => "libreadline6,screen,file,less,dnsutils,tcpdump,vim-nox,puppet,facter", # :exclude => "dhcp-client,dhcp3-client,dhcp3-common,dmidecode,gcc-4.2-base,module-init-tools,tasksel,tasksel-data,libdb4.4,libsasl2-2,libgnutls26,libconsole,libgnutls13,libtasn1-3,liblzo2-2,libopencdk10,libgcrypt11", # ) # # @param [Hash] options you want to pass to the bootstrapping tool. def debootstrap(={}) cmd = "/usr/sbin/debootstrap" .each do |opt,val| unless opt.to_s =~ /dist|dest|mirror/ cmd << " --#{opt} #{val}" end end cmd << " #{[:dist]}" cmd << " #{@config.ve_private}" cmd << " #{[:mirror]}" execute(cmd) # FIXME - Remove gettys from inititab automatically. We # Need a searchandreplace function first... :-) # # Util.searchandreplace( "#{@config.ve_private}/etc/inittab", # "/^(?!#)(.*\/sbin\/getty)/", # '#\1') end # Write into or copy a file into a container # # The destination file will be prepended with the containers private directory. If # you specify a source, this is relative to the virtualization hosts root directory. # # # @example Create /etc/hostname # # container.file('/etc/hostname', :content => 'vm01') # # @example Copy a file from /etc/vz/template.conf/hosts (host) to /etc/hosts (container) # # container.file('/etc/hosts', :source => '/etc/hosts' # # # @param filename Destination filename, relative to the containers root # @param :source The source filename, relative to the virtualization hosts root directory # @param :content Pass a string which will be written to the file. # @param :mode Specify the file mode. def file(filename, ={}) unless filename raise ArgumentError, "file requires destination filename as first argument." end if [:source] and [:content] raise ArgumentError, "file can either take :source or :content as an argument." end destination ="#{@config.ve_private}/#{filename}" if [:source] FileUtils.cp([:source], destination) end if [:content] File.open(destination, 'w') { |file| file.write([:content]) } end if [:mode] FileUtils.chmod [:mode], destination end end # Copy a file from the hardware node into the container. (OBSOLETE) # # @example Copy resolv.conf # container.cp_into( # :src => '/etc/resolv.conf', # :dst => '/etc/resolv.conf' # ) # # @param [Hash] define def cp_into(={}) cmd = "/bin/cp #{[:src]} #{@config.ve_private}/#{[:dst]}" execute(cmd) end # Run a shell command within the container. # # @example Update the package sources. # container.command("aptitude update") # # @param [String] Command to be executed. def command(command) cmd = "#{@vzctl} exec2 #{@ctid} " cmd << command execute(cmd) end # Return the current machine status string. # # @example # puts container.status() # exist mounted running def status cmd = "#{@vzctl} status #{@ctid}" status = execute(cmd).split(/\s/) Log.debug("Container (#{@ctid}) status requested: #{status}") status.drop(2) end # Return the current uptime in seconds. # Return zero if the container is not running. # # @example # puts container.uptime() # 1188829 def uptime return 0 unless status.include? "running" raw = command "cat /proc/uptime" Log.debug("Container (#{@ctid}) uptime requested: #{raw}") raw.split(/\W/).first.to_i end # Add veth to a CT # vzctl set <CTID> --netif_add <ifname>[,<mac>,<host_ifname>,<host_mac>,<bridge>] # # @param [Hash] interface settings (keys as listed above) def add_veth veth cmd = "#{@vzctl} set #{@ctid} --netif_add #{veth[:ifname]},#{veth[:mac]},#{veth[:host_ifname]}," \ "#{veth[:host_mac]}, #{veth[:bridge]}" execute(cmd) end #### #### Helper methods #### def state_require(*opts) current_state = status if current_state & opts puts "req: #{opts.join("-")}, cur: #{current_state.join("-")}" return true else raise StateMachineError, "Required container status not met for this action. req: #{opts.join("-")}, cur: #{current_state.join("-")}" end end # Check whether current_state == :require||:validate # def state(mode, action) current_state = self.status() if current_state & @statemachine_options[action.to_sym][mode.to_sym] return true end raise StateMachineError, "Required container status not met. req: #{@state_control[:action]}, cur: #{state}" end # Notify Method! :-) Config objects will notify, as soon as they are changed. # def update(key, value) set(key.to_sym => value) end # Load the container configration file. # def load_config_file data = {} if File.exists?(@configfile) File.open(@configfile, "r").each_line do |line| # strip blank spaces, tabs etc. off the lines line.gsub!(/\s*$/, "") if (line =~ /^([^=]+)="([^=]*)"$/) key = $1.downcase val = $2 case key when /^ve_(private|root)$/ data[key] = val.gsub!(/\$VEID/, @ctid) else data[key] = val end end end end data end # TODO: implement :-) # # NETIF="ifname=eth0, # bridge=vzbr303, # mac=02:01:79:15:03:02, # host_ifname=veth17915.303, # host_mac=12:01:79:15:03:02" #def load_net_config # if @config.netif ### DOES THAT WORK? # str = @config.netif # if str =~ /ifname=([^,]+),bridge=([^,]+),mac=([^,]+),host_ifname=([^,]+),host_mac=([^,]+)/ # @net.ifname = $1 # @net.bridge = $2 # @net.mac = $3 # @net.host_ifname = $4 # @net.host_mac = $5 # @net.type = "bridged" # ### MISSING: IP, SUBNET, GATEWAY within VM # end # end #end # This will give us a nicer object feeling and dynamically # exposes variables to the outside. # # @examples Setting and getting a variable # container.config.ipaddress = 1.2.3.4 # # #def method_missing(sym, *args) # if sym.to_s =~ /(.+)=$/ # self[$1] = args.first # else # self[sym] # end #end # Execute a System Command def execute(cmd) Util.execute(cmd) end end |
Instance Method Details
#add_veth(veth) ⇒ Object
Add veth to a CT vzctl set <CTID> –netif_add <ifname>
312 313 314 315 316 |
# File 'lib/openvz/container.rb', line 312 def add_veth veth cmd = "#{@vzctl} set #{@ctid} --netif_add #{veth[:ifname]},#{veth[:mac]},#{veth[:host_ifname]}," \ "#{veth[:host_mac]}, #{veth[:bridge]}" execute(cmd) end |
#checkpoint(snapshot_path) ⇒ Object
Checkpoint the container
98 99 100 101 |
# File 'lib/openvz/container.rb', line 98 def checkpoint(snapshot_path) cmd = "#{@vzctl} chkpnt #{@ctid} --dumpfile #{snapshot_path}" execute(cmd) end |
#command(command) ⇒ Object
Run a shell command within the container.
275 276 277 278 279 |
# File 'lib/openvz/container.rb', line 275 def command(command) cmd = "#{@vzctl} exec2 #{@ctid} " cmd << command execute(cmd) end |
#cp_into(options = {}) ⇒ Object
Copy a file from the hardware node into the container. (OBSOLETE)
263 264 265 266 |
# File 'lib/openvz/container.rb', line 263 def cp_into(={}) cmd = "/bin/cp #{[:src]} #{@config.ve_private}/#{[:dst]}" execute(cmd) end |
#create(options = {}) ⇒ Object
Create a new empty instance from a template.
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 |
# File 'lib/openvz/container.rb', line 149 def create(={}) unless [:ostemplate] # We need at least a valid ostemplate raise ArgumentError, "Create requires argument :ostemplate." end cmd = "#{@vzctl} create #{@ctid}" .each do |opt,val| cmd << " --#{opt}" cmd << " #{val}" end execute(cmd) Log.debug("Reading new container configuration file: #{@configfile}") @config = Config.new(load_config_file) @config.add_observer(self) end |
#debootstrap(options = {}) ⇒ Object
Bootstrap a Debian container, this requires /usr/sbin/debootstrap to be installed. Executing this function usually takes a while.
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 |
# File 'lib/openvz/container.rb', line 185 def debootstrap(={}) cmd = "/usr/sbin/debootstrap" .each do |opt,val| unless opt.to_s =~ /dist|dest|mirror/ cmd << " --#{opt} #{val}" end end cmd << " #{[:dist]}" cmd << " #{@config.ve_private}" cmd << " #{[:mirror]}" execute(cmd) # FIXME - Remove gettys from inititab automatically. We # Need a searchandreplace function first... :-) # # Util.searchandreplace( "#{@config.ve_private}/etc/inittab", # "/^(?!#)(.*\/sbin\/getty)/", # '#\1') end |
#destroy ⇒ Object
Destroy a container
90 91 92 93 |
# File 'lib/openvz/container.rb', line 90 def destroy cmd = "#{@vzctl} destroy #{@ctid}" execute(cmd) end |
#execute(cmd) ⇒ Object
Execute a System Command
422 423 424 |
# File 'lib/openvz/container.rb', line 422 def execute(cmd) Util.execute(cmd) end |
#file(filename, options = {}) ⇒ Object
Write into or copy a file into a container
The destination file will be prepended with the containers private directory. If you specify a source, this is relative to the virtualization hosts root directory.
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 |
# File 'lib/openvz/container.rb', line 227 def file(filename, ={}) unless filename raise ArgumentError, "file requires destination filename as first argument." end if [:source] and [:content] raise ArgumentError, "file can either take :source or :content as an argument." end destination ="#{@config.ve_private}/#{filename}" if [:source] FileUtils.cp([:source], destination) end if [:content] File.open(destination, 'w') { |file| file.write([:content]) } end if [:mode] FileUtils.chmod [:mode], destination end end |
#load_config_file ⇒ Object
Load the container configration file.
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 |
# File 'lib/openvz/container.rb', line 358 def load_config_file data = {} if File.exists?(@configfile) File.open(@configfile, "r").each_line do |line| # strip blank spaces, tabs etc. off the lines line.gsub!(/\s*$/, "") if (line =~ /^([^=]+)="([^=]*)"$/) key = $1.downcase val = $2 case key when /^ve_(private|root)$/ data[key] = val.gsub!(/\$VEID/, @ctid) else data[key] = val end end end end data end |
#migrate(destination_address, options = %w(--remove-area yes --online --rsync=-az))) ⇒ Object
Migrate container to another node
113 114 115 116 |
# File 'lib/openvz/container.rb', line 113 def migrate(destination_address, =%w(--remove-area yes --online --rsync=-az)) cmd = "#{@vzmigrate} #{.join ' '} #{destination_address} #{@ctid}" execute(cmd) end |
#mount ⇒ Object
Mount a container
74 75 76 77 |
# File 'lib/openvz/container.rb', line 74 def mount cmd = "#{@vzctl} mount #{@ctid}" execute(cmd) end |
#restart ⇒ Object
Restart a container
66 67 68 69 |
# File 'lib/openvz/container.rb', line 66 def restart cmd = "#{@vzctl} restart #{@ctid}" execute(cmd) end |
#restore(snapshot_path) ⇒ Object
Restore a checkpoint
106 107 108 109 |
# File 'lib/openvz/container.rb', line 106 def restore(snapshot_path) cmd = "#{@vzctl} restore #{@ctid} --dumpfile #{snapshot_path}" execute(cmd) end |
#set(options = {}) ⇒ Object
Update one or multiple Container properties and keep the configration object up to date
123 124 125 126 127 128 129 130 131 132 133 134 135 136 |
# File 'lib/openvz/container.rb', line 123 def set( = {}) # Construct a set command cmd = "#{@vzctl} set #{@ctid} --save" .each do |opt,val| cmd << " --#{opt}" cmd << " #{val}" end execute(cmd) # Each time we update a setting, reload the configuration. @config.load(@ctid) end |
#start ⇒ Object
Start a container
50 51 52 53 |
# File 'lib/openvz/container.rb', line 50 def start cmd = "#{@vzctl} start #{@ctid}" execute(cmd) end |
#state(mode, action) ⇒ Object
Check whether current_state == :require||:validate
337 338 339 340 341 342 343 344 345 346 |
# File 'lib/openvz/container.rb', line 337 def state(mode, action) current_state = self.status() if current_state & @statemachine_options[action.to_sym][mode.to_sym] return true end raise StateMachineError, "Required container status not met. req: #{@state_control[:action]}, cur: #{state}" end |
#state_require(*opts) ⇒ Object
324 325 326 327 328 329 330 331 332 |
# File 'lib/openvz/container.rb', line 324 def state_require(*opts) current_state = status if current_state & opts puts "req: #{opts.join("-")}, cur: #{current_state.join("-")}" return true else raise StateMachineError, "Required container status not met for this action. req: #{opts.join("-")}, cur: #{current_state.join("-")}" end end |
#status ⇒ Object
Return the current machine status string.
287 288 289 290 291 292 |
# File 'lib/openvz/container.rb', line 287 def status cmd = "#{@vzctl} status #{@ctid}" status = execute(cmd).split(/\s/) Log.debug("Container (#{@ctid}) status requested: #{status}") status.drop(2) end |
#stop ⇒ Object
Stop a container
58 59 60 61 |
# File 'lib/openvz/container.rb', line 58 def stop cmd = "#{@vzctl} stop #{@ctid}" execute(cmd) end |
#umount ⇒ Object
Umount a container
82 83 84 85 |
# File 'lib/openvz/container.rb', line 82 def umount cmd = "#{@vzctl} umount #{@ctid}" execute(cmd) end |
#update(key, value) ⇒ Object
Notify Method! :-) Config objects will notify, as soon as they are changed.
351 352 353 |
# File 'lib/openvz/container.rb', line 351 def update(key, value) set(key.to_sym => value) end |
#uptime ⇒ Object
Return the current uptime in seconds. Return zero if the container is not running.
301 302 303 304 305 306 |
# File 'lib/openvz/container.rb', line 301 def uptime return 0 unless status.include? "running" raw = command "cat /proc/uptime" Log.debug("Container (#{@ctid}) uptime requested: #{raw}") raw.split(/\W/).first.to_i end |