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!




Monday, February 27, 2012

printf and types

This blog started as a notepad for lessons learnt. My career requires me to live in fluffy architect land (it's like real life except there's lots of whiteboards and clouds) and sometimes I struggle to remember how to solve hands-on problems. I started by keeping a notepad. Several lost notepads later, I upgraded to the  Evernote online notepad service. I like to keep a unique password for each online service. Having a unique password means that if a single site is compromised, your credentials on other sites remain secure. To make a long story short, I started blogging my problems so I wouldn't have to recall a password to access the knowledge that should have been in my head in the first place.

This blog post is about a basic printf problem in C which is different from the usual virtualization/architecture/licensing content on this blog. Hey, this is my blog, I can write about anything I want: next blog post is all cake recipes! I'm learning C because I want a challenge and I'm sick of Java. I'm blogging about it so I can remember my mistakes and serve as a warning to others not to learn C. If several months have passed and this is the only blog post on C, you can assume I've given up and that you shouldn't learn C either.

Anyway, now it's time to spot the error in my code. The following code stores records the temperature of three bagels and stores them in array bagelTemperature.

bagelTemperature[0] = 15;
bagelTemperature[1] = 17;
bagelTemperature[2] = 12;


printf("The bagel temperatures are\n");
printf("%d\n", bagelTemperature[0]);
printf("%d\n", bagelTemperature[1]);
printf("%d\n", bagelTemperature[2]);


printf("The bagel temperatures are\n");
printf("%x\n", *(bagelTemperature));
printf("%x\n", *(bagelTemperature+1));
printf("%x\n", *(bagelTemperature+2));

will output

The bagel temperatures are
15
17
12
The bagel temperatures are
17
22
41

Why are the two bagel temperatures different?

Simple mistake: the type field in the second set of printf statements is incorrect. Replace the %x and %d and the bagel temperatures will be good. %d is for signed decimal integers and %x is for unsigned integers written with hexadecimal. If you don't select the correct type, your output might be different to what you expect. Until I realised the problem was with the type, I was scratching my head wondering if there was a problem with my pointer arithmetic.

VMware 5 Host Profiles prompts for MAC address

The good news is, host profiles in VMware 5 have been improved significantly. The bad news is, they still suck.

When trying to apply a host profile to a server, you may be prompted for a MAC address.

image

Wow, a bug in VMware host profiles! Who’d thought! At least it isn’t a crippling like the vSphere 4 “swap the vmkernel IP addresses around” bug.

Anyway, you should need to enter a MAC address every time you want to apply a host profile. That’s ludicrous. To get around this, go to the Host Profiles console (Home > Host Profiles).

image

Right-click on your Host Profile and click Edit Profile.

image

Navigate to the Determine how MAC address for vmknic should be decided setting

image

Select User must explicitly choose the policy option, then click OK.

image

If you have a separate port for VMotion, Fault Tolerance, management traffic, iSCSI, you will have to repeat this step for each of those port groups.

Done! Now remember to do this every time you create a host profile.

Sunday, February 12, 2012

Basic ISO-Schematron functions

Every blogger loves Google Analytics: oh, the voyeuristic joy of knowing what search terms people misspelled for Google to return your blog as a 'top' result is irresistible! My blog isn't popular because it's about VMware, it's because I keep misspelling VMware as WMware. Did you know my blog is the most popular WMware blog in the world?! Actually, that's not true. My blog isn't popular at all. But I'm hoping today's post about ISO-Schematron will turn more fortunes around. I'll be grabbing some search terms out of Google Analytics and answering the questions you never asked me, which is not dissimilar to hosting an unpopular talk back radio show.

I seem to get a lot of ISO-Schematron-related hits, so if you're uninterested in this topic, close your browser window now and throw your computer into a fountain. If you're interested in the XML validating magic of ISO-Schematron, feel free to read on or throw your computer into a fountain as well.

What is ISO-Schematron?

ISO-Schematron is an XML schema language. Schema languages are ways of making sure your XML is valid. Take a look at the following XML code

<dog id="500">
     <name>Chop Chop</name>
     <breed>Silky Terrier</breed>
     <dob>2012-01-05</dob>
</dog>

It's well formed XML. Without knowing too much about the XML, you can tell it describes a dog named Chop Chop. The dog has the breed Silky Terrier and a date of birth sometime in 2012. This reminds me, I better change my password reset questions now. Let's look at the same snipplet of XML code except with some creativity.


<dogPASTA
     <name>Chop Chop</name
     <breed>Silky Terrier
     <dob>2012-01-05</date fo birth y'all>
<dog> PASTAPASTASPTA


This is definitely not well formed! Not every opening tag has a closing tag, there are slashes missing and there's pasta everywhere! You don't use an XML schema language to determine whether this XML is well formed or not well formed: you use an XML syntax checker and common sense. Let's look at yet another snipplet of XML.


<dog id="500">
     <name>Chop Chop</name>
     <name>Choppy</name>
     <breed>Silky Terrier</breed>
     <dob>2012-01-05</dob>
</dog>


It's easy to tell that this XML is well formed (there's no pasta lying around, for starters). But is the XML valid? Is a dog allowed to have two names? Whether or not a dog is allowed to have two names is the decision of the owner. I, for one, welcome our multi-named dog overlords! But what if you don't? What if you believe that a dog can have one name only?! We'd be in disagreement! We'd both agree that the XML is well formed, but we would disagree on whether the XML was valid.

What is ISO-Schematron? (no really, answer my question this time).

I need to test XML code to see whether it meets some rules.

  • A dog has an ID attribute
  • A dog can have multiple names, but has to have at least one name.
  • A dog definitely has a date of birth
  • A dog must have a breed
  • A dog's date of birth cannot be in the future
With ISO-Schematron, I can write rules. Each rule will contain one or more assertions. Writing these assertions gets tricky.

Alright! Let's write assertions!

Let's start by ripping search terms out of analytics like uncreative Law & Order writers rip stories out of headlines and back episodes.

Google search term: count elements schematron children must have
Translation: Señor Paul, what ISO-Schematron could check whether an element has the correct amount of child elements?

What you're looking for is the count() function. The following snipplet will make sure you have 5 child elements.

<iso:rule context="dog">
<iso:assert test="count(breed) = 1">The dog element must have one breed element only!</iso:assert>
</iso:rule>

With a simple and, you can check for the correct amount of multiple types of child elements.

<iso:rule context="dog">
<iso:assert test="count(breed) = 1 and count(dob) = 5">The dog element must have 1 breed element and 1 dob element</iso:assert>
</iso:rule>

Easy, next!

Google search term: check schematron first element
Translation: Señor Paul, I too use ISO-Schematron to verify the validity of my XML files, possibly because I'm a student trying to cheat on my homework! Please assist me by explaining how to check if the first child element within an element is of a certain type.

Try this buster. This will check if the first element in a DiskSection element is Info.

<iso:rule context="dog">
<iso:assert test="*[1][self::name]">The first element within dog must be name</iso:assert>
</iso:rule>

Google search term: check existance of attribute schematron
Translation: do my homework for me please

First of all, you spelled existence incorrectly. I'm guessing you want to check if an element had an attribute. This snipplet checks whether the dog element has a name attribute

<iso:rule context="dog">
<iso:assert test="@id">The dog element doesn't have an ID attribute!</iso:assert>
</iso:rule>


Easy! If you have any other tricky ISO-Schematron questions, put them in the comments and I'll try to help you and then make fun of you.

Thursday, February 9, 2012

FlexLM and Furious: setting up a license server

FlexNet is a licensing framework used to control access to software. Negative people like to call it the worst piece of software ever made by human kind, but I like to think of it as the best piece of software ever made by lobotomised parakeets. This blog post demonstrates the tedious process of setting up a FlexNet license server. Although I've only described how to install a single license server, you can repeat steps 2 to 8 to serve license for as many FlexEnabled products as you like. Lucky you!

If you're unfamiliar with any of the terms in this blog post (license server, license file, vendor daemon, grand royal with cheese), read my previous blog post on the topic.

Scenario
You work for Contoso. Contoso has purchased licenses for Autodesk AutoCAD and MATLAB. You have been asked to set up a license server so the products work and your boss doesn't fire you.

Before you begin…
Software vendors usually package FlexNet with their products. Unfortunately, vendors almost universally package FlexNet in a way that prevents you from using the license server to serve other products. So don't install the FlexNet from the vendor's installer. Use my instructions instead! All your wildest dreams will come true!

Step 1 - Install the FlexNet License Manager

FlexNet is a stand-alone application that does not require installation process. This step involves downloading the latest versions of the FlexNet binaries and placing them in a folder on your server. All you need to do is
  1. Download the latest versions of the following files from the Flexera website
    1. lmtools.exe
    2. lmutil.exe
    3. lmgrd.exe
  2. Create the folder C:\Program Files\FlexNet
  3. Copy lmtools.exe and lmutil.exe to C:\Program Files\FlexNet
While I suggest using C:\Program Files\FlexNet, tossing all the files into C:\Program Files\StarCraft is okay too.

Step 2 - Identify the vendor daemon name

For this step, you’ll need to open your license file in Notepad. The license file is provided to you by the vendor in exchange for money.

The vendor daemon name is specified on the VENDOR line of the license file. This is illustrated in the following tiny screenshot. In this example, the vendor daemon name is MLM.

image

The vendor daemon is an executable file. If you look in your license file, the vendor name will be located after the DAEMON keyword. Now that you know what the vendor daemon name is, you can…


Step 3 – Create a subfolder under FlexNet for the vendor daemon
In this case, you’d create a folder called C:\Program Files\FlexNet\mlm


Step 4 – Find the vendor daemon
If the vendor name is MLM, the vendor daemon will be mlm.exe. If the vendor daemon name is ADSKFLEX, the vendor daemon will be adskflex.exe. Vendors typically publish the latest version of their vendor daemon in their website. If you can’t find it, try looking on your source media.


Step 5 – Assemble license server files in folder
Now copy the following files into your folder
  • the vendor daemon (which you downloaded from the vendor website)
  • lmgrd.exe (which you downloaded)
  • the license file (provided to you by the vendor)
Once you’ve done that, create the following blank files
  • vendorDaemon.debuglog
  • vendorDaemon.log
  • vendorDaemon.opt
where vendorDaemon is the vendor daemon name. Once you’ve done all this, your folder should have 6 files.



Step 6 – Register the license server as a Windows service
If you don’t register the license server as a Windows service, it won’t start when your server starts. To register a license server as a service, you’ll need to use the LMtools (lmtools.exe) utility you downloaded in step 1.


Caution: follow these instructions carefully! The LMtools application is the Ralph Wiggum of management consoles. If you click Save Service at the wrong time you'll end up with a useless Windows service called Flexlm Service 1.
  1. Open the LMtools utility (lmtools.exe)

    image

    The picture of the world symbolizes the world of pain you will be in.
  2. Select the Config Services tab.
  3. Delete the contents of the Service Name field and enter whatever Windows service name you like. If your license server is for Autodesk, you might want to use Autodesk License Server

    image
  4. In the Path to the lmgrd.exe file text field, click the Browse button and select the lmgrd.exe file you copied into the vendor daemon subfolder in step 5.
  5. In the Path to the license file text field, click the Browse button and select the license file you copied into the vendor daemon subfolder in step 5.
  6. In the Path to the debug log file text field, click the Browse button and select the lmgrd.exe file you copied into the vendor daemon subfolder in step 5.
  7. Click the Use Services checkbox.
  8. Enable the Start Server at Power Up checkbox.
  9. Click the Save Service button.
This will create a Windows service. You can verify the service has been created by using the Computer Management console.

Step 7 – Set the service to automatically restart
In the unlikely event of a license server failure, you’ll want the license service to automatically restart so you won’t be pestered by users. To do this,
  1. Open the Computer Management console
    (Start > Run > compmgmt.msc)
  2. Click on the Services node
  3. Right-click on the license server service and edit the Properties of the service.

    image
  4. On the Recovery tab, set the first failure, second failure and subsequent failure action to Restart the service.

    image
  5. Start the service
  6. Close the Computer Management console.
Step 8 – Prevent users from shutting down license server
By default, any user has the ability to stop a license server remotely. I’m not sure why this functionality exists, but it can (and should) be disabled with a registry setting.
  1. Open the Registry Editor
    (Start > Run > regedit.exe)
  2. Navigate to the key
    HKEY_LOCAL_MACHINE\SOFTWARE\FLEXlm License Manager
  3. Click on the application license manager
  4. Change the value of the cmdlineparams entry to

    -local
    Important note:
    there is a space before the dash
  5. Close the Registry Editor.
Done! You’ve set up a license server manually! How boring. If you want your license server to serve licenses for multiple products, simply repeat steps 2 to 8. Just wait, didn't I write that in the introductory paragraph?

Wednesday, February 1, 2012

Eternally entering Maintenance Mode

I was rebuilding my lab and found a host that had been entering maintenance mode for 4 hours!

image

If this happens, the first step is to restart the management agent on the server. You can do this via the console (ESX Console > Troubleshooting Options > Restart Management Agents)

image

Did it work? If it did, count yourself lucky! If the task still exists, you’ll need to restart your vCenter service.

Tuesday, January 17, 2012

VMware voucher: 50% off VCP5 and VCAP5 exam! (expires 12 March 2012)

Want 50% off your VMware VCP5 or VCAP5 exam? When registering for the exam, use the following promotion codes

VMware VCP5 50% off
VMWCQVCP50

VMware VCAP5 50% off
VMWCQVCAP50

You'll have to complete the exams before the 12th of March 2012, so get those home labs cranking!