Mounting a Microsoft Azure CloudDrive in a VMRole
- by SeanBarlow
Mounting a Drive in a VMRole is a little more complicated then a web or worker. The Web and Worker roles offer OnStart and OnStop events, which you can use to mount or unmount your drives. The VMRole does not have these same events so you have to provide another way for the drives to be mounted or unmounted. The problem I have run into is what if you have multiple drives and you only want to mount certain drives. How do you let your user mount the drive.
I am not going to go into details on what kind of GUI to present to the user. I have done this in a simple WPF application as well as a console application.
We are going to need to get the storage account details. One thing to note when you are mounting cloud drives you cannot use https and have to use http. We force the use of http by using false when we create the CloudStorageAccount.
StorageCredentialsAccountAndKey credentials = new StorageCredentialsAccountAndKey("AccountName", "AccountKey");
CloudStorageAccount storageAccount = new CloudStorageAccount(credentials, false);
Next we need to get a reference to the container.
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("ContainerName");
Now we need to get a list of the drives in the container
var drives = container.ListBlobs();
Now that we have a list of the drives in the container we can let the user choose which drive they want to mount. I am just selecting the 1st drive in the list for the example and getting the Uri of the drive.
var driveUri = drives.First().Uri;
Now that we have the Uri we need to get the reference to the drive.
var drive = new CloudDrive(driveUri, storageAccount.Credentials);
Now all that is left is to mount the drive.
var driveLetter = drive.Mount(0, DriveMountOptions.None);
To unmount the drive all you have to do is call unmount on the drive.
drive.Unmount();
You do need to make sure you unount the drives when you are done with them. I have run into issues with the drives being locked until the VMRole is rebooted. I have also managed to have a drive be permanently locked and I was forced to delete it and upload it again. I have been unable to reproduce the permanent lock but I am still trying.
The CloudDrive class provides a handy method to retrieve all the mounted drives in the Role.
foreach (var drive in CloudDrive.GetMountedDrives()) {
var mountedDrive = Account.CreateCloudDrive(drive.Value.PathAndQuery);
mountedDrive.Unmount();
}