Thursday, August 23, 2012

Reversing a string in C

I was asked today if I could write a C function that reversed a string without knowing the string size. What a boring question! I don't think they were particularly interested in whether I could reverse strings. I had told them I could write C, and I think they were trying to verify this by handing me some rope. Here's what I whiteboarded.



Let's assume the string is HELLO BURGER!. Why hello burger? Because "Hello World!" is overdone and I like burgers. Burgers from Grill'd, to be specific. Grill'd is a faux-90's Australian hamburger chain aimed at Sydney hipsters with too much disposable money. To be clear, I'm not a hipster and I don't have much disposable income unless you count pocket lint as disposable income, I just like their burgers.

HELLO BURGER in a table with corresponding index numbers
I recommend the Zen Hen.

I've placed an index grid above the phrase. Keep in mind that in C, we start counting at 0. So even though there are 13 letters in "HELLO BURGER!", the final character (an exclamation mark) is at index 12. 

If we were to print the string with the statement printf("%s", input)then "HELLO BURGER!" would appear. The statement printf("%c", input[0]) would print "H" and printf("%c", input[6]) would print "B". Pretty straight forward. You might have noticed there's a \0 in the end: in C, this is a "end of string" terminator. In C, a string is defined as a...err..string of letters followed by a \0. The \0 tells C that the string has ended. If a string consists only of \0 then it's empty.

The empty string is a \0 in string position 0
This is an empty string. If input[0] is \0, it's empty.

The following is not a string. And because it's not a string, functions like strlen() that iterate until they see the terminator won't work.

BURGER as a string without \0
Not a banana either.

Let's go line by line through this application.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

First of all, let's get the basics out of the way: include string.h along with your usual libraries: you'll need it to calculate the length of an input string. The reason why this is required will become obvious later.

char* reverseString(char* input) 

In our function signature, we'll be accepting string input. Since we're accepting a string, the type of the input will be a character pointer (char*). We'll also be returning a reversed string, which is why we return the same type. Remember, there's no string datatype in C, which is a reason why the language is unsuited for any quick and dirty string manipulation.

int length = strlen(input);
int i = 0;
int j = 0;

To reverse a string in C, we'll be using a for loop. We'll need to iterate through each character in the string which will require us to know how long the string is. We'll use the variable i to iterate from the end of the string, and j to iterate from the beginning. This will make sense later.

char* newString = malloc(sizeof(char)*length+1);

This line allocates some memory for the string. malloc() allocates memory by giving you a pointer to a block of memory you can play with. To do this, malloc() needs to know how much memory you want: do you want 1kb? 2TB? I can't think of a string that would require 2TB of memory (maybe an e-mail from my mother, if she knew how to send e-mails).

We know how many characters we want: this in the variable length. However, malloc() needs to know how much memory you need, not the string length. To figure this, we use the function sizeof() which returns the amount of memory used by a type. On most computers, a char is 1 byte. But this isn't guaranteed, so we need to use sizeof(). If we multiply the size of the unit we need (a char) by the length (and add one char for the \0), we'll get the size of memory we need.

for (i=length-1, j=0; i>=0; i--, j++) {}

To reverse the string, the end is a good place to start! The final character in the string (an exclamation mark) is at input[12]. Using input[length] results in position 13 (which is the \0 and definitely isn't what we want), so our start position i should be length-1. We want to iterate until we reach index 0: the H, so we continue while the statement i>= 0 is true. After every iteration, we decrease i. In a normal for loop, you increase your loop control variable, but in our case we're iterating through the string backwards so we decrease the loop variable.

HELLO BURGER in a table with corresponding index numbers
Did I mention the fries at Grill'd? Do yourself a favour and upsize.

We'll use j as the loop control variable to write the reversed string. When writing the new string, j will start at index 0 and increment for each new character written.

newString() is ready to be written to...
newString[] is ready to be written to...

newString[j] = input[i];
This takes the current position of input[i] and writes it to the position of newString[j]. Because i starts from the end of the input string and j starts from the beginning of the new string, we are writing the reverse of the input string!
return newString;
We return a character pointer to the reversed string. This pointer points to a block of memory containing the reversed string. Because it was allocated by malloc(), the memory needs to be returned with free() once you're done with it.

Done! You can give it a try by pasting the code into Eclipse.

Why didn't you just use an array to store the reversed string?
Variable length arrays like char newString[strlen(input)] are illegal in C89 standard C. In C89, the memory structure required to store an array is allocated at compile time and not runtime. This means we needed to use a function that allocates memory at runtime, like malloc().

Why didn't you use a large array like char newString[50000]?
Because the string could have 50001 elements! Plus, that's a waste of memory: you'd be allocating sizeof(char)*50000 bytes instead of just sizeof(char)*strlen(input)+1 bytes. If you were running this function once, nobody would care. If this function were being called 20,000 times a minute (say, if you were writing some sort of function to parse every song lyric even written to see if there were any hidden backward messages), you'd want it to be efficient. In fact, there are more efficient ways of writing this function.

Are there any other ways to reverse a string?
Heaps, this isn't Python!

Tuesday, June 19, 2012

Chess in C (Part 2) - Insert Pawn Pun Here

I'm glad you could make it to the second instalment of Chess in C! In my last blog post, we made a chessboard out of an array (board[i][j], where i represented rows and j represented columns), put some pieces on the board, and found out that if you have a picnic on a farm that cows, chickens, dogs and ducks will come to share your food.

Sure, invite yourself along.

When we left off, the chess board was looking like this.


Today I'm going to discuss how we can chart the possible moves of pieces. To do this, we need to do some housekeeping. I'm going to add some macros/#define's so that we can mark a square being a potential move for a piece. If you're playing with this code and compiling as we go, take a moment now to stop, copy and paste! If you haven't got this code already, open your IDE and download the code at the end of my previous blog post so you can start modifying it.


I'm also going to update the board display code with extra case statements so that we can display the potential moves. Potential moves will be represented with +.


To simply things, I'll start by removing every piece on the board except for two pawns.


To comment out a line in C, simply surround it with /* and */, or put a // in front of it. If a line is commented out, the compiler will ignore it. Alright, now we're ready to start! Let's take a look at our board now.

Hapless losers!
Let's model a pawn's move. In this exercise, we will assume that the two hapless pawns are in their starting position, and moving forward means they will move downward.

According to the Wikipedia article on chess pawns, there are three valid moves:
1) A pawn can move to the square directly in front of itself, if that square is clear.
2) A pawn on its starting rank can move forward two squares
3) A pawn can move front-left diagonally or front-right diagonally to capture another piece.

We're going to keep it simple and only implement the first and second pawn moves. We can always add functionality later.

If a pawn is in its starting position at board[1][1], then there are two valid moves: board[2][1] (if the pawn moves forward one square) and board[3][1](if the pawn moves forward two squares). You can confirm on the board below: place your finger (or pencil or assorted pointing apparatus) on the board square represented by board[1][1]. Now move your finger down one square to simulate a pawn moving forward once: you're now at board[2][1]. If you move your finger down one square again, you will reach board[3][1]. Easy!

Use this as an aid. Wipe after use.

Obviously, we can't code every permutation of move into our chess application. If we had infinite time, we could write a million if statements for each square and piece. But I don't have that sort of time: Crust Pizza closes in an hour! Instead, we can write a simple algorithm that calculates possible moves for a piece. If we represent the board row as i, we could say that the valid move for any pawn at board[i][j] is board[i+1][j]. If a pawn is in its starting position, it can move forward two squares, we could say the pawn's valid move would be board[i+2][j].

So how do we code this in C?

There are a few ways of doing this, and they're all a variation of our board zero'ing code: we 1) iterate through every square in the board, 2) check if there's a pawn in that square, and 3) if there is a pawn in that square, mark the potential moves.

Cast your mind back to my last post. There was a nested for loop which let us iterate through every position on the board to mark it empty. Here it is below.



Let's modify it a little. We'll start by getting rid of that board zero'ing code and...*pulls out chainsaw*...done! Let's look.


The if statement checks whether the current square contains a pawn. If the if statement evaluates to true (ie. there is a pawn in the current square), then we will mark the square below it as a potential pawn move. Let's run it and see what happens.

Two pawns in their starting position.

Looks good! We can add a second if statement to determine the potential move if the pawn is in its starting position (row 1 - remember, in C we start counting from 0!) and allowed to move forward two squares (to board [i+2][j]).


Looks good? Let's see what happens.

That's two pawns and their potential moves, not a
game of Minesweeper.

If you've made it this far, that's great! You've made a simple chess board and calculated the position of a few pieces. You've also unintentionally created one of the most common bugs in the history of programming: an out of bounds errors. Don't feel bad: I intentionally led you down this path. You've got to experience the problem before you can know how to prevent it.

So what is a out of bounds error? Well, it makes demons fly out of your nose. Let me explain.

Our pawn move calculator doesn't take into account what happens if the pawn is on the final row. What if the pawn was on the final row? According to rules of chess, the pawn can be promoted to a Queen, which is helpful. But ignore that for now. If our pawn is on the final row of the board (i == 7), then the next line of code (board[i+1][j] = POTENTIAL_MOVE_PAWN) will modify a board position that doesn't exist: board[8][j]. Look at the aid: there is no row 8! If your program modified row 8, I kid you not: you would be modifying THE MATRIX. This is an out of bounds error.


The people you'll annoy if you don't bounds check your arrays.


C is an unsafe language. In a smarter language like Java, Java would pick up an invalid statement like board[8][j] = POTENTIAL_MOVE_PAWN and say "NO YUO! That doesn't exist! Go back to programming school" then crash your program. But C will happily let you make your mistake. The catch is, your bad statement won't modify the board. You'll modify the variables whose memory is stored after the board, which causes undefined behaviour. Undefined behaviour could be anything: if you're lucky, the undefined behaviour will cause your program to crash and you'll find your mistake. If you're unlucky, the undefined behaviour won't do anything...for now. This well written post by jalf (someone smarter than me) on stackoverflow.com describes undefined behaviour well:

Welcome to every C/C++ programmers bestest friend: Undefined Behavior. 
There is a lot that is not specified by the language standard, for a variety of reasons. This is one of them.
In general, whenever you encounter undefined behavior, anything might happen. The application may crash, it may freeze, it may eject your CD-ROM drive or make demons come out of your nose. It may format your harddrive or email all your porn to your grandmother.
It may even, if you are really unlucky, appear to work correctly.
The language simply says what should happen if you access the elements within the bounds of an array. It is left undefined what happens if you go out of bounds. It might seem to work today, on your compiler, but it is not legal C or C++, and there is no guarantee that it'll still work the next time you run the program. Or that it hasn't overwritten essential data even now, and you just haven't encountered the problems that is going to cause yet.

So let's modify our code and do a simple bounds check. All we need to do is write an if statement that prevents the code from being executed if the row (i) is the final row (7).


There we go. All fixed! If the row is 7 (the final row), there's no way the code modifying the contents of the next row (which doesn't exist) which prevents undefined behaviour from occurring (demons flying out of your nose).

That's it for today! I thought I'd get to some more interesting parts (like calculating potential moves of bishops and horses), but we gotta nail the simple stuff down first.

Thanks for reading so far. Here's a full copy of the code so you can play around with it. Remember kids, always bounds check your arrays!

Other posts in this series

Chess in C (Part 1)
Chess in C (Part 2) - Insert Pawn Pun Here
Chess in C (Part 3) - Rook, Rooks, Rookies, Wookies, same thing
Chess in C (Part 4) - I'm asking for input
Chess in C (Part 5) - Potential moves of a bishop: up-left, cardinal, pope

Thursday, May 31, 2012

Feather duster PowerCLI scripts!

I've been cleaning out script repository and found a file full of PowerCLI scripts I found useful. Hopefully they'll be of use to you too.

What is my consolidation ratio? (number of VMs divided by number of hosts)
(Get-VM | Measure-Object | Measure-Object -Sum Count).sum/(Get-VMHost | Measure-Object | Measure-Object -Sum Count).sum
38.278925790328472

What is my consolidation ratio rounded to two decimal places?
[Math]::Round((Get-VM | Measure-Object | Measure-Object -Sum Count).sum/(Get-VMHost | Measure-Object | Measure-Object -Sum Count).sum,2)
38.27

How many hosts in my cluster aren't ESX 5.0?
Get-Cluster myCluster | Get-VMHost | Where-Object {$_.Version -ne '5.0.0'} | Select-Object Name

What's versions of ESX do I have in my cluster, and how many?
Get-Cluster myCluster | Get-VMHost | Group-Object Version

Count Name     Group
----- ----     -----
    2 5.0.0    {esx01.test.lab, esx02.test.lab....
    1 4.1.0    {esx03.test.lab....

Which VMs in this cluster have SCSI bus sharing set to physical, and what hosts are they on?
Get-Cluster myCluster | Get-VMHost | Get-VM | Get-ScsiController | Where-Object {$_.BusSharingMode -eq 'Physical'} | Select {$_.Parent.Name}, {$_.Parent.Host}, BusSharingMode | Sort {$_.Parent.Host}

$_.Parent.Name  $_.Parent.Host  BusSharingMode
--------------  --------------  --------------
mySQLServer     esx01.test.lab  Physical


How many VMs are on each of my ESX hosts?
Get-VMHost | ForEach-Object {$_.Name; Get-VM -Location $_ | Measure-Object | Select-Object count}

Create a new VMFS datastore on a SAN LUN given a disk's NAA
New-Datastore -Vmfs -VMHost (Get-VMHost esx01.test.lab) -Name myNewDatastore -Path "naa.10000038275027693935893472859354"

Rename a datastore
Get-Datastore BurgerHut | Set-Datastore -Name HungryBurger

Total space consumed by VMs in TB
((Get-VM | Get-HardDisk | Measure-Object -Property CapacityKB -Sum).sum/(1024*1024*1024)).ToString() + " terabytes consumed"
519128.167283058 gigabytes consumed


Total number of datastores that are X KB in size
Get-Datastore | Where-Object {$_.CapacityMB -eq 500} | Measure-Object | Select-Object Count

Total number of VMs
Get-VM | Measure-Object | Select-Object Count

Monday, May 7, 2012

Chess in C (Part 1)

I recently finished writing a chess application in C. I've been trying to spend a greater percentage of my day programming: with all the cool social websites and iPhone apps out there, I've felt a little left out in these past years working in the infrastructure space. Sure, cloud is the coolest thing to happen to infrastructure, but I've always envied the people who write the awesome applications on top of the cloud. zCloud is an amazing piece of infrastructure, but the Zynga games programmed on top of it are much more fun!


The chicken in this picture is happier than your average infrastructure architect.

The best way to write a chess application (or any application) is to split it into several smaller discrete parts. In this blog post, I'll describe how to setup a chess board, put some pieces on the board and print the board. My next blog post will deal with the algorithms used to calculate possible moves.

Setting up the board


I may not be a chess grandmaster, but if I recall correctly, boards have 8 rows and 8 columns. Each square on the board can have a piece. The obvious data structure to represent this would be a two-dimensional array of integers which we can declare as follows.




That was easy. One line of code and we have a chess board! Done! Here's a diagram of what we've created.

A visual representation of int array [8][8]. It ain't pretty, and neither is C.

The first square on the board is 0,0. The last square on the last row is 7,7. Remember, in C, array elements start counting at 0 and not 1, even though the statement we used to create the board was [8][8]. Confusing, I know. Remember this lesson when it comes to writing for loops.

This chess board is neat, but it's not much use without any pieces on it This chess board is an array of integers, which means each array element can hold a number between 0 and 65536. This is more than enough: there are only six types of pieces in chess (assuming a single player for now). Let's define these pieces upfront.




By defining (or should I say, #define'ing) these pieces, we can refer to them freely through our program as BISHOP or KING, instead of having to remember obscure numbers. This will come as a relief to the dyslexics reading this blog post, and the dyslexic writing it.
Now, we'll need a function to print the chess board.



This code might look long, but it's fairly simple. Let's go through it line by line.



We have two for loops that iterate through each element of the board[][] array. Notice how the for loops begin at 0 and stop at 7? This is because in C, we begin counting from 0. Remember this: if you tried to view the contents of array[0][8] (column 9 when the array only 8 columns), you'll get an array out of bounds error. If you're lucky, you'll get garbage, your program will crash, and you'll only have to bang your head against a wall once or twice. If you're unlucky, it'll introduce subtle bad behaviour to your program and you'll die never understanding why your code behaved that way.



If any given element matches a piece, we print the piece. Unfortunately, you can't do a switch() on an array value, which is why I've made a new variable called boardValue and performed a switch() on that. Ignore the BREADCRUMB: I'll explain that later. Let's run the code so far and see what we get.

This is not the chess board I grew up with.

That doesn't look too good. It looks more like a chess board designed by an alcoholic. Where's our chess board?! What happened to our 8x8 one-line wonder?! When an array is instantiated in C, all array elements are filled with garbage. You'll need to write code to "zero out" the board.



This code will iterate through each square in the array and set the value to 0. Let's try that again.
Now THAT'S a chess board!

Fantastic! If you ever get strange array results, make sure you've zeroed out your array. Now let's place two bishops on the board in their starting positions and see what happens.



Two lonely bishops.

Amazing! Two bishops have arrived! Let's go one step further and make an ARMY



Let's look at the chess board now.
An army looking for a fight.

We can even put one hapless opposing pawn on the board with board[6][4] = PAWN;
Advice for pawn in (6,4): RUN

Here's the code if you want to compile it for yourself.



Other posts in this series

Chess in C (Part 1)
Chess in C (Part 2) - Insert Pawn Pun Here
Chess in C (Part 3) - Rook, Rooks, Rookies, Wookies, same thing
Chess in C (Part 4) - I'm asking for input
Chess in C (Part 5) - Potential moves of a bishop: up-left, cardinal, pope

Thursday, March 29, 2012

VMware ESXi 5.0 installer doesn't always show LUN 0

If you have ESXi hosts which have hit or are close to hitting the VMware path limit maximum (2048 paths per host), it is possible that the LUN (Logical Unit Number) you want to use for boot (LUN 0) will not be listed by the ESXi installer. This affected me because I incorrectly assumed that LUN 0 had to be enumerated.

In reality, LUNs will enumerate in any order the storage system feels like responding in. From my experience, this is non-deterministic. LUN 0 may be enumerated first, or last, or in the middle. And just because a subset of LUNs is enumerated once, does not mean that the same subset will be enumerated next time!

This issue is more likely to impact you if you have many paths per LUN. The solution is to either:

  1. Reduce the amount of LUNs you have through LUN consolidation. Have fewer, larger LUNs. Take advantage of increased LUN size maximums.
  2. Change to an internal boot device. SD card boot, or internal disks.
  3. Start splitting clusters. Redistribute which LUNs get presented to which hosts.

Monday, March 26, 2012

How to find where a function is defined in Eclipse

To find where a function is defined in Eclipse, right-click on your function then click Declarations > Workspace.

Tuesday, March 13, 2012

How to upgrade VMware vCenter from 4.1 to 5.0

Upgrading VMware vCenter from 4.1 to 5.0 is a breeze. I’m writing this documentation because some of you out there will be given the tedious task of documenting the upgrade process. Don’t bother: just copy and paste the contents of this post into your internal documentation and spend the time you would have spent doing something you enjoy, like walking a dog or eating a cake or whatever it is that people do when they’re not working with VMware (I wouldn’t know!)

I’m assuming you know how to download VMware vCenter. If not, I don’t blame you: the VMware Download Center is confusing. I’ll have another post detailing how to download vCenter if you’ve got a license, and how to download a 60 day evaluation.

Okay! Start by extracting the contents of the vCenter download to a folder on your vCenter server. Once you’ve done this, run autorun.exe.

Windows Explorer viewing vCenter source media

The installer appears! Wow, look at all the wonderful VMware products you can install! You can install core vSphere components including

  • vCenter Server
  • vSphere Client
  • VMware vSphere Web Client (Server)
  • VMware vSphere Update Manager

You can also install the Support Tools like

  • VMware ESXi Dump Collector
  • VMware Syslog Collector
  • VMware Auto Deploy
  • VMware vSphere Authentication Proxy
  • vCenter Host Agent Pre-Upgrade Checker

Why am I listing these out? Because these are optional components and won’t be installed automatically. Why did I tell you that? Because every VMware Certified Professional should know *hint hint*.

Anyway, let’s install vCenter Server. That’s what we’re here for.

VMware vSphere 5.0 installer

Select your language. English (United States) is good, but you only get the real power of ESX if you select German.

VMware vCenter Server - InstallShield Wizard

Wow, a splash screen! VMware products are covered by one or more patents. Maybe two or three. Or four.

VMware vCenter Server 5.0 splash screen

The InstallShield Wizard is loading the Windows Installer, because nobody outside of Microsoft can package an application correctly.

VMware vCenter Server - InstallShield - Configuring Windows Installer

The vCenter installer welcomes you. Please remove your passports from your passport holders and open them to the first page.

VMware vCenter Server Installer - Welcome screen

If the message “An earlier version of vCenter Server is already installed on this computer and will be upgraded to vCenter Server 5.0” appears, the installer will perform an upgrade. If this message does not appear, you’re probably logged into your company’s file server and installing vCenter on it will get you fired.

VMware vCenter Server Installer - Welcome screen

If you’re really bored, you can look up the patents that VMware holds on the US Patent and Trademark Office website. Some of them are quite interesting and were ground breaking at the time. Check out patent 6,397,242 (Virtualization system including a virtual machine monitor for a computer with a segmented architecture). What ideas were you trying to understand in 1998? Devine, Buginon and Rosenblum were ahead of their time.

If you’re not bored, click Next to continue.

VMware vCenter Server Installer - End-User Patent Agreement

License agreement. If you look closely, there’s a clause in there about having to drink any paint within a three metre radius of you. It will be a very painful experience and you won’t want to install vCenter again for another three months.

If this is okay with you, click I agree to the terms in the license agreement then click Next to continue.

VMware vCenter Server Installer - License Agreement

Please enter your information and enter a license key. If you don’t have a license key, that’s ok: you’ll install vCenter in evaluation mode. Evaluation mode is 60 days. That’s something you might need to know.

VMware vCenter Server Installer - Customer Information

If you’re performing an upgrade, you’ve already got a System DSN created. If you use Windows Authentication, the database username and database password boxes will be greyed out. If you use native SQL authentication, please e-mail your DBA so they can tell you why you shouldn’t use native SQL authentication.

Click Next to continue.

VMware vCenter Server Installer - Database Options

if you use VMware Update Manager (VUM), you’ll be warned that it won’t work after vCenter is upgraded. Keep this in mind.

VMware vCenter Server Installer - VUM warning

You’ve got two options: upgrading your existing vCenter database or making a new one.

If you’re going to upgrade and haven’t taken a backup of your vCenter database and SSL certificates, you have rocks in your head. You need both items backed up to rollback from an unsuccessful installation.

If you want to start again with a brand new vCenter database, that’s fine too.

VMware vCenter Server Installer - Database Upgrade Warning

Each ESX host has a vCenter agent installed. This agent allows vCenter to communicate with the ESX host. If this agent is not installed, not started, or is a version older than your vCenter server, the ESX host will appear as disconnected.

The installer is asking you whether you want vCenter to automatically upgrade the vCenter agent on all the hosts it manages. If you select this option, you’ll see a bunch of ‘Upgrading vCenter agent’ tasks when you first log into vCenter. If you don’t upgrade the agent, all your ESX hosts will appear as disconnected and you’ll need to reconnect them again.

I recommend picking Automatic.

VMware vCenter Server Installer - vCenter Agent Upgrade

Enter the account name that vCenter will use to run. If you’re lazy and don’t use service accounts, you can use the SYSTEM account (by checking the Use SYSTEM account checkbox). Come on, use service accounts! They’re more secure and only take a minute to create!

If you want to use a service account, I hope you logged in to the server with it! If you have, the account name field is prepopulated and you can’t change it. Enter the account password and the Fully Qualified Domain Name (FQDN) of your server then click Next.

VMware vCenter Server Installer - vCenter Server Service

If you get the error message “Failed to verify the Windows account, either username or password is incorrect.”, you probably made a typo and need to practice using a keyboard more.

VMware vCenter Server Installer - Failed to verify the Windows account, either username or password is incorrect

If vCenter cannot resolve your FQDN, you’ll get the error message “The Fully Qualified Domain Name cannot be resolved. If you continue the installation, some features may not work correctly. For detailed requirements, see the vSphere Installation and Setup guide.” This error message also appears if you have multiple network interfaces on your server (you can safely ignore it).

VMware vCenter Server Installer - The Fully Qualified Domain Name cannot be resolved. If you continue the installation, some features might not work correctly. For detailed requirements, see the vSphere Installation and Setup guide.

You can install VMware anywhere you like. The default folder is C:\Program Files\VMware\Infrastructure\, but you can change the folder to any other drive without fear of strange side effects (I’m looking at you, Eclipse!)

VMware vCenter Server Installer - Destination Folder

Ports ports ports. Don’t change these unless you like introducing unneeded complexity into the environment (maybe you’re some sort of consultant). If you’re sitting a VMware exam, you should probably know these! Click Next…

VMware vCenter Server Installer - Configure Ports

…for more ports! Seriously, don’t change these. Just click Next.

VMware vCenter Server Installer - Configure Ports for Inventory Service

vCenter Server is a piece of crap written in Java. Don’t give me dirty looks, I’m just saying what every VCP is thinking. Sometimes it’s hard to believe the same company that made ESX also made vCenter.

Pick the inventory size most suited to your environment so vCenter won’t perform worse than it already does, then click Next.

VMware vCenter Server Installer - vCenter Server JVM Memory

Wow, you’re ready to install! WAIT! There’s one more question! Do you want to increase the amount of ephemeral ports you have? (Hint: You do, and I recommend it. Even if you use a Cisco Nexus 1000V).

Every switch (physical and virtual) has a fixed number of ports. Take a look at the $9 Netgear switch underneath your desk that smells like feet: it will probably have four ports on it labelled 1 to 4. vSwitches are similar: even though they’re virtual, they have a fixed amount of ports too (a lot more than physical switches though!) This option increases the amount of ports you have. There’s no reason you shouldn’t select this option.

Once you’ve digested this, click Install to upgrade vCenter.

VMware vCenter Server Installer - Ready to Install the Program

The first step of upgrading vCenter is upgrading the database! There’s no turning back now!

If you have a reasonably sized database, upgrading can take up to 15 minutes. If your database is 60gb in size, it can take several hours. Don’t press Cancel unless you feel like doing a database restore.

VMware vCenter Server Installer - Installing VMware vCenter Server

The vCenter Server installer will open this command window to take you out of your comfort zone. Nothing actually appears in it.

VMware vCenter Server Installer - vCenter-Server\dbuupgrade\bin\dbuHelper.exe empty command window

If you’ve been good, the installation will have completed successfully.

VMware vCenter Server Installer - Installation Completed

Good work! Now you can update your resume detailing your extensive VMware 4 to VMware 5 upgrade experience.

Wednesday, March 7, 2012

Using PowerCLI to find total space consumed by a VM

Say you have a VM named burger and you want to know the total disk space used by a VM in PowerCLI.

Get-VM burger | Get-HardDisk | Measure-Object -Property CapacityKB -Sum


Count    : 2
Average  :
Sum      : 157286400
Maximum  :
Minimum  :
Property : CapacityKB

The Sum value contains the total amount of kilobytes consumed by all disks connected to the VM. But what if you just want the value of Sum?

Get-VM burger | Get-HardDisk | Measure-Object -Property CapacityKB -Sum | Select-Object Sum
Sum
---
157286400
Still good, but what if you want just the number?

(Get-VM burger | Get-HardDisk | Measure-Object -Property CapacityKB -Sum).sum
157286400

That's the correct amount of kilobytes, but how can I convert that into gigabytes? Easy! Divide it by 1048576 (1024 multiplied by 1024)

(Get-VM burger | Get-HardDisk | Measure-Object -Property CapacityKB -Sum).sum/(1024*1024)
150


What if you want to add some text after the string?
((Get-VM burger | Get-HardDisk | Measure-Object -Property CapacityKB -Sum).sum/(1024*1024)).ToString() + " gigabytes consumed"
150 gigabytes consumed

That was easy! Now, let's see all the errors you could have made along the way.

((Get-VM burger | Get-HardDisk | Measure-Object -Property
CapacityKB -Sum).sum/(1024*1024)) + " gigabytes consumed"
Cannot convert value "gigabytes consumed" to type "System.Double". Error: "Input string was not in a correct format."
At line:1 char:102
+ ((Get-VM burger | Get-HardDisk | Measure-Object -Property CapacityKB
-Sum).sum/(1024*1024)) + <<<<  "gigabytes consumed"
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
    + FullyQualifiedErrorId : RuntimeException

This error is caused by trying to add two incompatible values. Let's separate this command into a blue and green segments.

((Get-VM burger | Get-HardDisk | Measure-Object -Property
CapacityKB -Sum).sum/(1024*1024)) + " gigabytes consumed"


This blue code produces a number of type System.Double. We can verify this by using the Get-Members cmdlet.

((Get-VM burger | Get-HardDisk | Measure-Object -Property CapacityKB -Sum).sum/(1024*1024)) | Get-Member


   TypeName: System.Double


Name        MemberType Definition
----        ---------- ----------
CompareTo   Method     int CompareTo(System.Object value), int CompareTo(dou...
Equals      Method     bool Equals(System.Object obj), bool Equals(double obj)
GetHashCode Method     int GetHashCode()
GetType     Method     type GetType()
GetTypeCode Method     System.TypeCode GetTypeCode()
ToString    Method     string ToString(), string ToString(string format), st...


Now let's evaluate the second part of the command. +"gigabytes consumed" is a System.String object. This is obvious (it's in inverted commas), but you can pipe it into the Get-Member cmdlet if you want to check.

The reason why you received the error message Cannot convert value "gigabytes consumed" to type "System.Double is because PowerShell tries to cast (convert) the second operand (a string) in to the type of the first operand (a double). You can't convert the string "gigabytes consumed" into a bunch of numbers, but you can do the reverse! Let's pick up the +"gigabytes consumed: " bit of code and drop it at the beginning.


"gigabytes consumed: " + ((Get-VM burger | Get-HardDisk | Measure-Object -Property CapacityKB -Sum).sum/(1024*1024))
gigabytes consumed: 150

Awesome, it works! PowerShell casted the results of the double into a string. But what if we don't want the string before the value? We can use the .ToString() function to cast the double into a string.


(Get-VM burger | Get-HardDisk | Measure-Object -Property C
apacityKB -Sum).sum/(1024*1024).ToString() + " gigabytes consumed"
Cannot convert value "gigabytes consumed" to type "System.Double". Error: "Input string was not in a correct format."
At line:1 char:111
+ (Get-VM burger | Get-HardDisk | Measure-Object -Property CapacityKB -Sum).sum/(1024*1024).ToString() + <<<<  "gigabytes consumed"
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
    + FullyQualifiedErrorId : RuntimeException

WHAT?! We used ToString()! Why did it throw a casting error? Oh, wait, I only casted the (1024*1024) part. I need to evaluate the entire blue code block then cast to a string.

((Get-VM burger | Get-HardDisk | Measure-Object -Property
CapacityKB -Sum).sum/(1024*1024)).ToString() + " gigabytes consumed"
150 gigabytes consumed

That's better. And that's it!