My idiotic encounter with accepts_nested_attributes_for in Rails 3

I was using accepts_nested_attributes_for for the first times in Rails 3 to create forms that have fields from a parent model and its child model. I made a number of mistakes that make me feel like an idiot right now. Actually, the last one did but I saw it fit to blog about it in case anyone else finds themselves wasting an hour or more trying to get their forms to work.

N/B

  • I was using Rails 3.0.5 and Ruby 1.8.7 (MRI)
  • The Parent model had a has_one relationship to the child. (This shouldn’t matter though)

Mistake 1

In this case, my fields_for helper wasn’t evaluating to anything. The textfields and textareas were therefore not being created in the view. The issue was that in Rails 3, the helpers form_for and fields_for use <%= instead of <% !! I used the latter. (i)

Therefore, my form_for and fields_for helpers should have looked like this:

<%= form_for ......... %>
<%= fields_for ......... %>

This made the text fields visible but the values weren’t there.

Mistake 2

I didn’t make the attributes of the child model accessible to the parent model. This is done using attr_accessible and passing child_attributes.

e.g

def Dog < ActiveRecord::Base
has_one :puppy
accepts_nested_attributes_for :puppy
attr_accessible: puppy_attributes
end

Mistake 3 (Epic Fail)

Now this is the part that got me cursing all over the place. My form was being created using the variable from the controller rather than a symbol i.e

<%= form_for @dog do |f| %>

INSTEAD OF

<%= form_for :dog do |f| %>

The field_for was supposed to accept an object of the puppy model referenced from the @dog variable passed to the form. Problem is I was so frustrated by the fact that my text fields were empty that I started binging on Google search results and ended up with a fields_for that accepted the object of the puppy model as a symbol hahaha! yeah stupid.. i know. This is how it looked:

<%= fields_for :puppy do |puppy_fields| %>
<%= puppy_fields.text_field :breed %>
<% end %>

It obviously should have been like this:

<%= fields_for @dog.puppy do |puppy_fields| %>
<%= puppy_fields.text_field :breed %>
<% end %>

I’m going to cringe away in a dark corner now… Cheers!!

 

FTP file upload with custom port number in Rails

Its quite weird that I’ve never come across a scenario task that needed the involvement of FTP, at least as far as Rails is concerned. In this case, it involved a FTP PUSH whereby the application was to upload a file to a remote FTP Server. Its pretty simple:

ftp=Net::FTP.new
 ftp.passive = true
 ftp.connect("URL","PORT")
 ftp.login("USERNAME", "PASSWORD")
 ftp.putbinaryfile("/PATH/TO/FILE")
 ftp.close

In most cases, the port number defaults to 21 and hence you can use the open method instead of connect:

Net::FTP.open('URL') do |ftp|
 ftp.passive = true
 ftp.login('USERNAME', 'PASSWORD')
 ftp.putbinaryfile("/PATH/TO/FILE")

end

But in my case, the FTP server had a different command port hence had to use the connect method.  The other thing that’s worth mentioning is the passive flag. Rails sends files via FTP in active mode by default. In active mode, the server initiates a connection from its command port to the client through a random port (in the client). This method has issues because firewalls block the TCP connection from the server to the client.

In passive mode however, the client initiates both connections to the server, solving the problem of firewalls filtering the incoming data port connection to the client from the server.

Cheers!

Get the Network Manager working in Ubuntu 10.04 in LXDE (Lubuntu)

I was trying out XFCE and LXDE as alternative desktop environments for a setup that required the OS to be less resource hungry. LXDE was my preferred choice. I was impressed by its minimal use of resources. Anyway, the network manager doesn’t show up in the default LXDE desktop i.e in the panel like in GNOME. This is just a simple post showing how to make that happen.. at lease with GNOME’s network manager. I read somewhere that theres a lighter version for LXDE but not too sure about that. Was in a hurry and thus settled for GNOME’s network manager.

Open the autostart file for LXDE:

sudo nano /etc/xdg/lxsession/LXDE/autostart

Add the following line to enable wireless features for the user:

@nm-applet

Save the changes and reboot the system.

The applet will show up in the lower right of the panel.

attr_accessible and attr_protected in the Model

This is a word for word copy-paste from an answer to a question on StackOverflow. The first time I had issues with attr_accessible (which was the fact that I was missing the mass assignment bit), my thoughts were quelled by this excellent explanation. I just came across it accidentally today and thought that I should post it here.. even for my own sake.

Source: http://stackoverflow.com/questions/2652907/what-is-difference-between-attr-accessibleattributes-attr-protectedattrib

 

attr_accessible (documentation) says “the specified attributes are accessible and all others are protected” (think of it as whitelisting.)

whereas

attr_protected (documentation) says “the specified attributes are protected and all others are accessible” (think of it as blacklisting.)

protected attribute is one that can only be modified explicitly (e.g. via attribute=) and can’t be updated via mass assignment (e.g. using model.update_attributes or by passing attributes to new). Attempts to update protected attributes via mass assignment are silently ignored without raising an exception.

The classic example would be if a User model had an is_admin attribute you could protect that attribute to prevent form submissions that would allow any user to be set as an administrator.

Example:

class User < ActiveRecord::Base
# explicitly protect is_admin, any new attributes added to the model
# in future will be unprotected so we need to remember to come back
# and add any other sensitive attributes here in the future
attr_protected :is_admin
end

compared with:

class User < ActiveRecord::Base
# explicitly unprotect name and bio, any new attributes added to the model
# in the future will need to be listed here if we want them to be accessible
attr_accessible :name, :bio
end

Now, assuming is_admin attribute is protected:

> u = User.find_by_name('mikej')
> u.is_admin?
false
> u.update_attributes(:name => 'new name', :is_admin => true)
> u.is_admin?
false
> u.name
"new name" 
> u.is_admin = true # setting it explicitly
> u.save
> u.is_admin?
true









Remove all gems and Rubygems completely

One fuck-up led to another (don’t ask 🙂 ) and I had to do whats up there in the title. These are two links that helped me most:

Quickest way to remove all gems

gem list | cut -d” ” -f1 | xargs gem uninstall -aIx

Source:

http://geekystuff.net/2009/01/14/remove-all-ruby-gems/

Removing rubygems completely:

http://www.decentmind.com/2010/05/how-to-uninstall-remove-ruby-gems-on-ubuntu/

“File not found: lib” error while installing Rails 3.0.7

I was installing Rails 3.0.7 on my local machine yesterday and on a server today. I came across the same error both times:

This is the problematic part:

File not found: lib
ERROR:  While generating documentation for rails-3.0.7
... MESSAGE:   exit
... RDOC args: --ri --op /usr/local/rvm/gems/ruby-1.8.7-p334/doc/rails-3.0.7/ri lib --title rails-3.0.7 Documentation --quiet

Rails installed successfully but the Rdoc and ri documentation failed with this error. I ignored it in my local machine since I was in a hurry and Rdoc/ri were the least of my worries. But when it hapenned again in the server I just had to find out what the issue was. If you google it, many sources advise you to just uninstall that Rails version (in my case 3.0.7) and do this:

sudo gem install rails –no-ri –no-rdoc

I find that to be plain stupid! You are running away from the problem rather than solving it. The above command would just ignore the Rdoc/ri documentation.

The issue is that the new Rails version you are installing uses a more recent version of Rdoc/ri and thus when the installation process gets to Rdoc/ri installation, it fails. I don’t know why the ROR developers didn’t think of checking for this and updating Rdoc/ri for you. Anyway, the correct way to solve this issue is to first uninstall the Rails version you just installed with no Rdoc/ri data:

sudo gem uninstall rails –version 3.0.7

Install the latest version of the rdoc-data gem. This will install ri data for core and stdlib:

gem install rdoc-data

Then run:

rdoc-data –install

In case you want rdoc-data for all your gems run (not necessary.. takes a while if you have as many gems as i do):

gem rdoc –all –overwrite

To install ri data for RDoc 2.5+ run:

rdoc-data

Now you can install your Rails version and it will successfully install all the rdoc-data too.

sudo gem install rails

Output:

Successfully installed rails-3.0.7
1 gem installed
Installing ri documentation for rails-3.0.7...
Installing RDoc documentation for rails-3.0.7...

Installing and setting up RVM (Ruby Version Manager)

Sometime last month I had to set up a Rails 3 app on a RHEL5 server. From what I have experienced so far, Redhat is a shit server especially when it comes to updated libraries… thats just the point.. they’re not updated. It’s like whoever works on the Redhat packages/libraries is always a step behind. In this particular case, the ruby version provided by Redhat’s software channel was 1.8.6… can you believe that crap??? I didn’t complain earlier on because most of my apps on that particular server were running on Rails 2.3 so no drama. But Rails 3 need ruby 1.8.7 or 1.9.2 or later. I’m sure you’re wondering “why didn’t he just build it from source”…. well I did but on my third try I decided it was overkill.. the installation had so many dependencies missing (maybe redhat also has to blame) and when I thought it had finally worked, Ruby was ‘halfway’ working (sigh) ruby tcl/tk support was compromised and on other tries some other libraries were causing ruby to function erroneously. Then came the saviour (cue orchestra music and shut eyes for bright white light) RUBY VERSION MANAGER

I have to say, this is singl;e-handedly one of the most amazing ruby tools I have ever used. It is just breathtaking that someone created such a useful piece of software. RVM enables you to install different versions of Ruby on it. It is basically a wrapper for Ruby installations that is independent from your system Ruby. The cool thing is you are installing Ruby from,through and into RVM. It takes care of the whole process; just tell you what Ruby you want and it will get it and set it up for you. All you need is to select which one you want to use and it has other cooler features like gemsets that allow you to compartmentalize your rails installations with their gems… fuckin amazing!!

Anyway, enough rambling… here are the steps I went through:

Installation
1. It is recommended to install RVM from the github repository:

$ bash < <( curl http://rvm.beginrescueend.com/releases/rvm-install-head )

2. Then put the following into your ~/.bash_profile at the end

[[ -s “$HOME/.rvm/scripts/rvm” ]] && . “$HOME/.rvm/scripts/rvm”

Doing so ensures rvm is loaded as a function (versus as a binary), ensuring commands such as      rvm use work as expected

3. Confirm that this worked by opening a new shell (or restart the server) and running:

$ type rvm | head -1

On success, it should output:

rvm is a function

RVM’s most compelling feature is that it caters for six different distributions out of the box (MRI 1.8.6, MRI 1.8.7, 1.9.1, 1.9.2, Ruby Enterprise Edition 1.8.6, JRuby 1.3.1)

To install a ruby version on RVM, do the following e.g for ruby 1.8.7

rvm install ruby-1.8.7-p334

If you would like to make one specific Ruby be the default ruby that is selected when you open a new terminal shell, use the –default flag

rvm –default use 1.8.7

Output:

Using /usr/local/rvm/gems/ruby-1.8.7-p334

If you also check the version in the normal way it should output rvm’s default ruby version:

ruby -v
ruby 1.8.7 (2011-02-18 patchlevel 334) [x86_64-linux]

Other stuff you can do
To switch back to your system ruby:

$ rvm use system
Now using system ruby.
$ ruby -v
ruby 1.8.6 (2007-09-24 patchlevel 111) [x86_64-linux]

To switch back to RVM’s default ruby:

$ rvm default

$ ruby -v

ruby 1.8.7 (2011-02-18 patchlevel 334) [x86_64-linux]

To show what ruby is currently the selected default:

$ rvm list default

Default Ruby (for new shells)

ruby-1.8.7-p334 [ x86_64 ]

If you wish to switch back to your system ruby as default, remember that RVM does not “manage” the system ruby and is “hands off”.
This means to set the “system” ruby as default, you reset RVM’s defaults as follows.

$ rvm reset

Installing  Passenger
N/B Bear in mind that if you’re installing Rails 3 like I was, you’re current passenger instalation is using the system’s ruby version. Install passenger 3:

$ gem install passenger

Then:
$ passenger-install-apache2-module

The installation will give you the lines you are supposed to add to your apache configuration file. These lines will ensure passenger uses your RVMs ruby and not the system’s.

There is much more to learn on RVM. It has many more features. I will post something on gemsets in future but for now you can get all the in formation you want at http://beginrescueend.com/

Creating A RAID1 (Software RAID) Setup in Ubuntu Server 9.10

For many, creating a RAID setup may seem like an elusive task. Frankly, its not as I will show you.

Redundant Array of Independent Disks is a method whereby many hard drives are configured to act as one. There are two main types of setup in RAID:-

RAID0 is in favour of performance/speed while RAID1 is in favour of redundancy/reliability. Disks that are to be configured in RAID1 or RAID0 (which are supposed to be 2 in number) are supposed to be identical. There are other RAID setups that involve more hard disks but I won’t get into them here. In Brief, these are the ones i theoretically know of:-

* RAID0+1 – uses RAID0 and RAID1 at the same time with four identical hard disk drives. If one of the hard disk drive fails, the system becomes a RAID0 system.

* RAID10 – uses RAID0 and RAID1 at the same time also with four identical hard disk drives. If one of the hard disk drive fails, the system becomes a RAID1 system.

* RAID5 – this one is actually a RAID0 system that needs at least three identical hard disk drives. It stores parity information to improve the reliability of the disks. In a case whereby three drives are used, the total capacity will be double the size of each hard disk drive. e.g If I use three 750GB hard drives, my total hard disk space will be 1500GB since the rest of the space will be used to store this parity data.

Aaaaaaanayway….

In RAID0, when data is written to the hard disks, it is divided into several chunks whereby each chunk will be saved on a different drive. I won’t get into the intricacies of how RAID divides and distributes the data today. However, the main point is that if a 500KB file is stored and 250KB stored on each hard drive, it takes half the time to store each file since the hard disks are working in parallel therefore meaning MORE SPEED.

RAID1 on the other hand shows the two hard disks as one. By this i mean, like in my case, two 750GB hard drives set up in RAID1 will show as 750GB in your system. This is because, data that is sent to the 750GB RAID Volume is copied to both physical hard drives. This is why RAID1 is also known as mirroring. If one hard drive fails, all the data exists in the other hard drive..alas! REDUNDANCY and RELIABILITY in the flesh!I opted for data redundancy since i was setting up a server.

The next option that comes along the way is which method of RAID setup to use. RAID can either be setup as Hardware RAID or Software RAID. Hardware RAID can only work on machines whose motherboards have so called RAID Controllers. In this case, RAID is set up in the BIOS. The controller makes the OS think there’s only one drive and maintains the drives ‘invisibly’. I opted for Software RAID whereby no controller is needed. In this case, the OS knows about both drives and actively maintains both of them. The truth is, Linux software RAID is ideal for mirroring, and due to kernel disk caching and buffering it can actually be faster than RAID1 on lower end RAID hardware. However, for larger requirements like RAID 5, the CPU can still get bogged down with software RAID.

So… lets set up our two hard disks with Ubuntu Server 9.10 (Karmic Koala).

Follow the installation steps until you get to the Partition disks step, then:

  1. Select Manual as the partition method.
  2. Select the first hard drive, and agree to “Create a new empty partition table on this device?”.

    Repeat this step for each drive you wish to be part of the RAID array.

  3. Select the “FREE SPACE” on the first drive then select “Create a new partition”.
  4. Next, select the Size of the partition. This partition will be the swap partition, and a general rule for swap size is twice that of RAM. Enter the partition size, then choose Primary, then Beginning.
  5. Select the “Use as:” line at the top. By default this is “Ext3 journaling file system”, change that to “physical volume for RAID” then “Done setting up partition”.
  6. For the / partition once again select “Free Space” on the first drive then “Create a new partition”.
  7. Use the rest of the free space on the drive and choose Continue, then Primary.
  8. As with the swap partition, select the “Use as:” line at the top, changing it to “physical volume for RAID” then choose “Done setting up partition”.
  9. Repeat steps three through eight for the other disk and partitions.

There should now be a list of hard drives and RAID devices. The next step is to format and set the mount point for the RAID devices. Treat the RAID device as a local hard drive, format and mount accordingly.

  1. Select the RAID1 device #0 partition.
  2. Choose “Use as:”. Then select “swap area”, then “Done setting up partition”.
  3. Next, select the RAID1 device #1 partition.
  4. Choose “Use as:”. Then select “Ext3 journaling file system”.
  5. Then select the “Mount point” and choose “/ – the root file system”. Change any of the other options as appropriate, then select “Done setting up partition”.
  6. Finally, select “Finish partitioning and write changes to disk”.

If you choose to place the root partition on a RAID array, the installer will then ask if you would like to boot in a degraded state. At some point in the life of the computer a disk failure event may occur. When this happens, using Software RAID, the operating system will place the array into what is known as a degraded state. If the array has become degraded, due to the chance of data corruption, by default Ubuntu Server Edition will boot to initramfs after thirty seconds. Once the initramfs has booted there is a fifteen second prompt giving you the option to go ahead and boot the system, or attempt manual recover. Booting to the initramfs prompt may or may not be the desired behavior, especially if the machine is in a remote location. Booting to a degraded array can be configured several ways:

  • The dpkg-reconfigure utility can be used to configure the default behavior, and during the p rocess you will be queried about additional settings related to the array. Such as monitoring, email alerts, etc. To reconfigure mdadm enter the following:
    sudo dpkg-reconfigure mdadm
  • The dpkg-reconfigure mdadm process will change the /etc/initramfs-tools/conf.d/mdadm configuration file. The file has the advantage of being able to pre-configure the system’s behavior, and can also be manually edited by setting the ‘boot degraded’ option to true (BOOT_DEGRADED=true)

Finish the rest of the install and you’re good to go. For a more detailed and visual example, check out this guy’s detailed setup in Ubuntu Server 8.04. Not much has changed in the setup. CHEERS!

http://kuparinen.org/martti/comp/ubuntu/en/raid.html

Getting rid of virbr0/virbr1 interface in Ubuntu Server 9.10

After a fresh install of Ubuntu 9.04,  you might have a network interface virbr0 if you’ve selected to install a virtual machine emulator.  During the CD install, selecting vm, it will install kvm and xen.  It will create a network interface virbr0 or virbr1 to perform host networking.

Later, if you decide to install VMWare, VirtualBox or decide you really didn’t want a virtual machine server, you can remove the applications easily.  Just do a (sudo):

apt-get purge kvm

apt-get purge libxen3

Installation and configuration of a headless Ubuntu Server

Bear in mind that at the time of this exercise I was installing a Ubuntu Server 9.10 on VirtualBox 3.0.10.

1. First install all necessary packages. Apt-get virtualbox from the ubuntu repositories:

sudo apt-get install virtualbox-ose

You can also download the deb and install it manually:-

e.g

sudo dpkg -i virtualbox-3.0_3.0.10-54097_Ubuntu_karmic_amd64.deb

To get the proprietary version:-

(/etc/apt/sources.list)

deb http://download.virtualbox.org/virtualbox/debian karmic non-free

Then download Sun’s public key:- 

And finally:- 

sudo aptitude install linux-headers-$(uname -r) build-essential virtualbox-3.0 dkms

dkms is optional. Its a package that ensures that the VirtualBox host kernel modules are properly updated if the Linux kernel version changes

The group vboxusers will be created during installation. Note that a user who is going to run VirtualBox must be member of that group:-

sudo usermod -a -G vboxusers username


2. Since we want to setup our network in such a way that we have network bridges, we need to install bridge-utils.

sudo apt-get install bridge-utils

                                                                                                                 

3. The next step is to edit /etc/network/interfaces on the host machine and add the br0 interface with the same address as you primary interface, in this case eth0. Before you begin, backup your interfaces file since it is vital to your networking functionality.

sudo cp /etc/network/interfaces /etc/network/interfaces.`date +%F~%T`

This process varies depending on whether you’re host uses a static or dynamic IP address.

Dynamic

           $ sudo nano /etc/network/interfaces

           auto eth0

           iface eth0 inet manual

           auto br0

           iface br0 inet dhcp

               bridge_ports eth0 vbox0

           # The loopback network interface

           auto lo

           iface lo inet loopback

eth0 is the name of your interface, it can be different depending on your machine.br0 is an arbitrary name for the bridge.vbox0 is an arbitrary name for the device VBox will use. If you want more devices , you can add them:- bridge_ports eth0 vbox0 vbox1 vbox2 vbox3 vbox4  blah..blah..blahh

Static

       $ sudo nano /etc/network/interfaces

        auto eth0

        iface eth0 inet manual

        auto br0

        iface br0 inet static

             address xxx.xxx.xxx.xxx

             netmask xxx.xxx.xxx.xxx

             gateway xxx.xxx.xxx.xxx

             bridge_ports eth0 vbox0 vbox1

        # The loopback network interface

             auto lo

             iface lo inet loopback

4. Now restart your networking:- 

sudo /etc/init.d/networking restart

Ignore the messages complaining about the vbox# interface

Afterwards, ifconfig and you should see your br0 interface

5. Now create a file/etc/vbox/interfaces and add the following:-

vbox root br0

This file is used to declare the virtual interfaces needed by VirtualBox. Each line should be of the format [] . Declare as many interfaces as you want here for all your virtual machines. Just make sure they also exist in /etc/network/interfaces as shown earlier.

And now restart virtualbox to register the changes:-

/etc/init.d/vboxdrv restart

 

 N/B

Most sources on the internet indicate that you should use /etc/init.d/virtualbox-ose restart for VirtualBox OSE and /etc/init.d/vboxnet restart and for the proprietary version. On my version, only vboxdrv existed in init.d so if any of the two are the ones that exist in yours, don’t hesitate.

6. The last thing in the host’s network configuration would be to set the permissions on /dev/net/tun

                         $ sudo chown root:vboxusers /dev/net/tun

                         $ sudo chmod g+rw /dev/net/tun

This file is created with the default permissions every time the system restarts, so the best option would be to run the vms everytime as root. At this point its safe to say that installation and host configuration is complete. It is advised to restart your system.

Creating A New VM

1. First Register the Virtualbox machine with the machine name, in this case ubuntu_server1 (think of it as a shell we’ll customize later) :-

VBoxManage createvm –name ubuntu_server_1 –register

2. Then now give the VirtualBox machine all its properties:- 

VBoxManage modifyvm “ubuntu_server_1” –memory “256MB” –acpi on –boot1 dvd –nic1 bridged –bridgeadapter1 eth1

If you need to change any of the properties in future, do it the same way its done above e.g If I want to turn vrdp off at a later point, all I have to do is VBoxManage modifyvm ubuntu_server_1 –vrdp off   

3. Tell VirtualBox to mount the install ISO you want to install as the OS:- 

VBoxManage modifyvm ubuntu_server_1 –dvd /home/avallainafrica/images/ubuntu-9.10-server-i386.iso

4. Create a virtual hd for the virtual machine. In this case, the drive has been allocated 10GB :- 

VBoxManage createhd –filename “ubuntuserver1.vdi” –size 10000 –remember

5. Tell the virtual machine to use the hard drive you just created:-

VBoxManage modifyvm “ubuntu_server_1” –hda “ubuntuserver1.vdi”

Your virtual machine is now good to go. VirtualBox comes with a front-end called

VBoxHeadless, which produces no visible output on the host at all, but instead only delivers VRDP data. To start the virtual machine in your host, do this :-

 VBoxHeadless –startvm ubuntu_server_1

You should see such output when the machine is started:-

        VirtualBox Headless Interface 3.0.10

       (C) 2008-2009 Sun Microsystems, Inc.

       All rights reserved.

       Listening on port 3389

If you want to start the machine headless and detached in it’s own screen session so it’ll keep running even after you close your terminal session or log out of your machine:-

screen -d -m -S ubuntu_server_1 VBoxHeadless –startvm ubuntu_server_1

OR 

nohup VBoxHeadless –startvm &amp;

To access the machine remotely, all you need to do is use the remote desktop client of your choice. Rdesktop worked swell for me on Ubuntu (sudo apt-get install rdesktop) . In this case:-

rdesktop 192.168.0.157

Remember that the virtual machine needs to be running in the host/server.

You will see the OS image you mounted booting and the rest is just normal installation of the OS in this case, Ubuntu Server. After installation, one thing you’ll notice when you start the machine again and access it via VRDP is that it will still boot from the ISO image. This is because the –boot1 option is still on dvd which is the mounted drive. Here’s how to fix this:-

VBoxManage modifyvm ubuntu_server_1 –-dvd none

There are quite a number of things you can do to tweak the configuration of your existing Vboxserver using VBoxManage. The best source for the wide array of commands is the VirtualBox user manual(http://www.virtualbox.org/manual/UserManual.html#vboxmanage) but I’ve compiled some

useful ones here:-


How to list VM information.

How to show the VirtualBox VM info

VBoxManage showvminfo

How to show the VM Harddrive info

VBoxManage showhdinfo

How to list running VM

VBoxManage list runningvms

How to list available VM

VBoxManage list vms

How to list available VM Harddrives

VBoxManage list hdds

How to list available ISO’s

VBoxManage list dvds

                                                                                                               
How to control the vm

How to pause VM

VBoxManage controlvm pause

How to resume VM

VBoxManage controlvm resume

How to reset VM

VBoxManage controlvm reset

How to poweroff VM (hard poweroff eg. pull the plug)

VBoxManage controlvm poweroff

How to send poweroff single to VM (tells VM OS to shutdown)

VBoxManage controlvm acpipowerbutton

How to attach a DVD / CD to a running vm

VBoxManage controlvm dvdattach

How to de-attach a DVD / CD from a running vm

VBoxManage controlvm dvdattach none