All posts by Marco Ceppi

Deploying the Minecraft Charm!

For the past three weeks I’ve been working with Charms, which are part of the Juju project. I love charms, I even went so far as to join the Charmers group on Launchpad. During the Ubuntu Developer Summit I was lucky enough to sit down with a few of the Juju hackers and get a first hand look at developing an deploying charms. There are lots of videos showing how quick and easy it is to deploy Hadoop, WordPress, and MySQL to the cloud but those demos always just kind of sailed over my head, because I didn’t really care about that kind of infrastructure.

Juju!

So, you want to run a Minecraft server in the cloud. First you’ll need to grab juju – if you’re running the latest and greatest Ubuntu release then installation is a pretty straight forward process execute the following lines to add the Juju PPA and install Juju along with the additional charm tools.

sudo add-apt-repository ppa:juju/pkgs
sudo apt-get update && sudo apt-get install juju charm-tools

Once Juju is downloaded you’ll want to setup a place to store all the awesome charms that are available including the totally sweet Minecraft charm that everyone is clamoring for. In the terminal make a directory by running the following command:

mkdir -p ~/Projects/charms/oneiric && cd $_
charm update ./

This will create a a charms folder inside of Projects which has an oneiric directory. Charms are organized by release, so all Oneiric (11.10) compatible charms will be placed in the oneiric folder, if a charm was designed for another version of Ubuntu it’d be in that respective code name’s folder.  Then executing charm update to build the database of available charms. At the writing of this post, all charms are developed for Oneiric. Remember this directory, going forward it’ll be known as your “Local Charm Repository”.

Finally, we need to setup an environment for which to deploy these charms to! Run juju once to have Juju create it’s environments file, which is placed in ~/.juju/environments.yaml Since I use Amazon’s Web Services (AWS) EC2, all I had to do was add two extra keys one for access-key and the other secret-key. These are the access and secret keys (respectively) from your Amazon Web Service account. All of this can be found in the documentation

Now you're ready for some charming!

There are a whole bunch of directions you can go in now. You can pull down all the charms in the Charm Browser, you can checkout the list of charms that are still in development/awaiting approval, or you can download the totally awesome Minecraft charm. Lets do that! You remember our Local Charm Repository? Well, all we need to do is use the charm tool to fetch the latest version of the Minecraft charm!

charm get minecraft ~/Projects/charms/oneiric/minecraft

Remember, that’s the absolute path to your Local Charm Repository, so if you changed it make sure use whatever it’s set to. Furthermore, all this does is pull down the charm and place it in a minecraft folder, under the Local Charm Repository. Now that you have the charm, you’ll need to setup the cloud for deployment. This is done via bootstrapping, which will create an instance on the cloud that acts as the gatekeeper and manager for all services and charms you deploy with Juju to the cloud.

juju bootstrap

Bootstrapping can take up to five minutes to complete and it runs in the background. So even though the command completed doesn’t always mean the environment is ready! You can check on the Juju environment anytime by issuing the juju status command. Output, when bootstrapping is completed, will look like this

2011-11-16 13:18:27,464 INFO Connecting to environment.
machines:
  0: {dns-name: ec2-50-19-58-136.compute-1.amazonaws.com, instance-id: i-45bdd926}
2011-11-16 13:18:28,408 INFO 'status' command finished successfully

So we’ve got one machine (our bootstrap!) and it’s all ready to rock and roll. So, lets deploy this badboy

juju deploy --repository ~/Projects/charms local:minecraft

When that command completes, it’ll send a request to the bootstrap machine to spin up a minecraft service (just so you know, charms that are deployed are called services). It’s almost ready to rock and roll! Check on the machine periodically using the juju status command, eventually you’ll end up with the following:

2011-11-16 13:28:14,584 INFO Connecting to environment.
machines:
  0: {dns-name: ec2-50-19-58-136.compute-1.amazonaws.com, instance-id: i-45bdd926}
  1: {dns-name: ec2-50-17-53-192.compute-1.amazonaws.com, instance-id: i-fdb8dc9e}
services:
  minecraft:
    charm: local:oneiric/minecraft-1
    exposed: false
    relations: {}
    units:
      minecraft/0:
        machine: 1
        open-ports:
        public-address: ec2-50-17-53-192.compute-1.amazonaws.com
        relations: {}
        state: started
2011-11-16 13:28:15,711 INFO 'status' command finished successfully

As is shown, there are two machines now, bootstrap and the newly created minecraft machine. We have one service running, minecraft, and a bunch of other information, most importantly the state and public-address. As is shown, the machine is started! So everything went A-OK! All that needs to happen now: Expose the server to the outside world. Exposing simply opens the appropriate ports for a service, if required. In this case we want our server to be available to the rest of the world so they can play! You can do this by running

juju expose minecraft

Running juju status one more time will show that the Minecraft service is now exposed and ready to rock and roll

2011-11-16 13:32:18,630 INFO Connecting to environment.
machines:
  0: {dns-name: ec2-50-19-58-136.compute-1.amazonaws.com, instance-id: i-45bdd926}
  1: {dns-name: ec2-50-17-53-192.compute-1.amazonaws.com, instance-id: i-fdb8dc9e}
services:
  minecraft:
    charm: local:oneiric/minecraft-1
    exposed: true
    relations: {}
    units:
      minecraft/0:
        machine: 1
        open-ports: [25565/tcp]
        public-address: ec2-50-17-53-192.compute-1.amazonaws.com
        relations: {}
        state: started
2011-11-16 13:32:19,558 INFO 'status' command finished successfully

Now, the machine is available on port 25565 (the default port!) Try to connect and this is what you get:

I would have written this post sooner, but I was too busy "testing"

Now, I know what you’re thinking. “But Marco, I want to configure the server, now I have to log in and configure it.” Nope! Juju Charms are configurable! To get a list of configuration options just run juju get minecraft which should produce the following list

2011-11-16 13:31:06,718 INFO Connecting to environment.
charm: local:oneiric/minecraft-1
service: minecraft
settings:
    allow-nether:
        description: Allow generation of the nether, true or false
        type: string
        value: 'True'
    difficulty:
        description: Level of complexity 1-5
        type: int
        value: 1
    level-name:
        description: Name of the level, will be generated if it doesn't exist
        type: string
        value: world
    max-players:
        description: Maximum players allowed on the server
        type: int
        value: 10
    motd:
        description: Message of the day displayed to users in the server list
        type: string
        value: Juju Powered Minecraft Server
    port:
        description: Port for which Minecraft runs upon
        type: int
        value: 25565
    spawn-animals:
        description: Generate animals, true or false
        type: string
        value: 'True'
    spawn-monsters:
        description: Generate monsters, true or false
        type: string
        value: 'True'
2011-11-16 13:31:07,473 INFO 'config_get' command finished successfully

At this point you can update the configuration at any time using juju set minecraft option=value option2=value [...] an example to change the maximum players and the MOTD would be

juju set minecraft motd="Juju I love you" max-players=5

And in no time flat you’ll see something like this

That about sums up getting started with launching Minecraft in Juju. It may seem like a lot but the majority of this was a one time setup. This is also just the tip of the iceburg when it comes to charms and Juju. I strongly recommend checking out their temporary site and asking questions in the #juju room on freenode.

40 hours later

I was disappointed that I missed the Ondina launch for the 6th, so I decided to channel that disappointment into coding power! Little did I know that would take me on a 40 hour binge of coding and internet frolicking. I feared the worst this morning after I awoke: “What disastrous code did I write?!” Surprisingly, aside from quite a few profane variable names, the logic was sound. In fact I produced a lot of code, but written in a different way that I would have normally produced. It’s like reading over code by another developer where you agree with how they wrote it, but would have written it differently yourself.

There were some things that needed fixing. When I reviewed the commit messages this morning I had a hard time figuring out exactly what I had written. I knew it was for the DNS administration section because I remember making the video for it at 3AM. However, the commit messages would have you think otherwise:

34tf000 DELETE DELETE DELETE
cfdae81 I'M A TIGER!!!
5a1f065 DUHHH YOU NEED MORE AJAX
895612f I'M HAVING A GOOD TIME!!!!
d851f46 DON'T STOP ME NOW!
45fe891 Integration of API shit
e4cda3b Moving forward to 0.5 as when DNS completes we'll be a 0.5 release
29e6061 No ID is required
3b58f33 Added updated styles for controls and dropdown
ee0677b Created DNS module and basis
77c08aa Merge branch 'dev' of code.ondina.co:ondina/cp into dev
620cf7e small comment
ac3fdc9 affects-me-button for the outstanding reports list in the feedback form?
9b3639f fixed the input class for width
7700967 Fixed weird submit buttons

These commits seem to correspond to, what Last.FM confirms, is an over hour long repeat of Queen – Don’t stop me now.

Not even I could stop me now.

After doing some rebase magic in Git these commit messages are actual useful. The last cleanup was with code comments. Interestingly enough I was compelled to write detailed descriptions of what I was doing on every other line – as if alert and awake self couldn’t figure it out!

 

Just one of the many multi-line comments

In all I had a lot of fun working with that much code in that amount of time. I don’t plan on doing this again for quite some time but I think it would be fun to do again. It’s amazing how energizing not sleeping can be.

Release delayed

After working diligently for the past three months the 6th has come and gone. We missed our target Private Preview Release day and it’s extremely disappointing. I first realized we weren’t going to make the release date on Saturday. While we have a lot of the infrastructure in place and systems working (in fact we’ve been hosting a select few sites – including my personal sites – for the past two months) the Control Panel really isn’t anywhere it needs to be in order to provide anything worth previewing. Originally I intended to have a near fully functional Control Panel, complete with awesomeness folded into every page. Instead I found myself contemplating which features to drop from the Private Preview Release on Saturday: “I guess we can do without SSH access right now”, “I suppose only offering PHP hosting would suffice, for now”, “I don’t think we’ll need 1-Click installs at the time of release”, “Maybe we can do without database access”, “Do people really need to modify DNS?”. Ultimately today came down to “Can we provide a functional service that will really showcase what we’re doing?”

In end we can’t, yet. A truly huge disappointment; however, when presented with the options to “release soon, release often” or “delay and build a solid product” I ultimately chose the latter. So where do we go from here? Is Ondina to become the next Duke Nukem Forever? I want to take a moment to explain who “we” are and why it’s taken this long to produce a glimpse into the system.

Ondina was born of an old idea which masqueraded as “SeaCrow”. SeaCrow was half-assed attempt at making a web design/web development company which would host it’s clients sites. I teamed up with a good friend of mine, Mason Shelby, to get this done. Ultimately it didn’t pan out as neither of us had the time to truly invest into the idea. What resulted from this was a tool-set and server infrastructure that eventually would be used to build Ondina on. After a lot of scraping and re-tooling a new server infrastructure was devised. Since May 4th I’ve been working on laying the ground work for Ondina based on the trials of SeaCrow bouncing the idea off anyone who would listen. As I gathered more feedback from people and understood more the business aspect of an idea like Ondina, I began to pursue it further.

Early August I asked Stefano Palazzo if he could help with some design aspects. Little did I know how much assistance he would provide. In the time he’s helped with Ondina, Stefano has really helped in creating a solid user experience, but also has helped in a large capacity with security and communications aspects. In a later post I’ll explain exactly how Private Preview Release is setup and our aim for future infrastructure, but his Python experience and insight has been indispensable in getting Ondina as far as it’s come. Without his assistance Ondina would be delayed by months, not days.

The real delay in the project can be traced to one single point of failure, time. When I started Ondina I had one goal in mind: Quality above all else. Because of this I’ve refused to allow investments or outside revenue sources that could lower any portion of quality for Ondina. As a result this project is being entirely financed from my pocket. This includes the servers, development time, everything. As such my current employment position is vital to Ondina’s success, without my job there wouldn’t be any money (though it seems with my job there’s never any time). However, Ondina is designed to reach self-sufficiency quickly after public launch to avoid issues like cash flow and time constraints.

So when does Ondina Private Preview Release start?

We’ll be sending out the first batch of invites sometime before this Saturday, September 10th. From there everyone who signed up prior to the 6th will receive their invitation before the following Saturday. While we expect to be finished within the next few days the remaining days of the week will give us time to make sure everything truly is ready for you and everyone to use!

We look forward to sending out those first invitations and are excited for the future of this project! Feel free to field any comments here or on Google Plus

It’s all about the users

Again, as we are drawing close to the start of the Ondina Private Preview Release, I begin to question certain design tactics and plans for the launch. What should be available for our private release? What features are most important to have? What should be functional?

One piece of functionality I know for certain needs to work flawlessly is the Feedback Form. Because of this I’ve spent quite some time scoping out how other popular services prod users and take feedback from them. Since the majority of web hosting providers don’t seem to have a way to submit feedback (As cPanel and other Web Control Panels don’t anticipate there being any feedback necessary for their product), I looked into how Google managed feedback from Google Plus users.

Google Plus Feedback

It’s simple: Describe the problem and give users the ability to “highlight” areas of the page to be included in the report while blacking out private details. It has a few drawbacks though. For starters, it’s slow. To even load the interface it takes approximately 45 seconds.  Before submission, there’s a preview step and, finally, the submission. Getting from one step to the other incurs a 30-45 second load time. Like so many other sites that sport a feedback button, this one is located outside of the realm of design: Bottom right of the window. Most sites seem to anchor theirs on the right or left of the page in an off-beat, annoying color.

 

Well, it's not that far away.

Being a developer, I know nothing about what the average user wants in an interface. If it were up to me, I would hand everyone SSH access and say, “Have at it!” Unfortunately, that really won’t work for everyone, and I know that. With Ondina, I know feedback is going to be the only way to bring Ondina from just another hosting provider to the hosting provider. So I’ve taken some time to build out something that will hopefully make your input and you, the user, the single most important entity to this whole operation! I care what you have to say. In fact, without your feedback I’d be stuck at the gates. As a result, I’ve placed a feedback panel in the control panel. On every page you’ll be able to not only report your good experiences with Ondina hosting, but also exactly how you think your experience can be improved. In addition to providing feedback, you can view all the outstanding issues reported on any page ordered by votes.

I look forward to the Private Preview Release and most importantly your feedback!

Design and Functionality

If you’ve ever seen any of the websites I’ve designed for personal use, first of all: I’m sorry. You’ll have noticed that I tend to do design in one of two ways: Gaudy or Non-existent. I like simple, elegant, and efficient, though it seems I’m incapable of designing what I envision. As a developer it really hurts to know that how I want a site to look will never translate properly to completion. It’s why I’m very envious of designers. Great ones always blow my mind with how well they can take an idea and make it something great.

When I started on Ondina, I knew the control panel couldn’t be some out-of-the-box solution like cPanel or ISP Config. While they served a purpose in the past, they’re either too expensive to be practical or seem to be stuck in a time warp to 1999. If I was going to do this right, I would need something new, fresh, and simple. This is why I’ve left the control panel as the last thing on my to do list.

 

Failed design attempt #9,001

Now that we’re coming to the home stretch and our Private Preview release is just around the corner, I’ve realized it’s time to take care of arguably the most important part of the whole project: the dreaded control panel design. I’ve tried several times during the project to design the control panel area. The best I could do is pictured above. I really don’t like this design, it’s too – guh. Impossible to describe and I’m not even sure where I would begin. It has the elements I want: simple overview screen, simple navigation options, fixed width design, etc. I just seem to fail in it’s overall execution. It just didn’t wasn’t sexy.

Luckily, I was able to get some much needed help! Stefano Palazzo, another moderator on Ask Ubuntu, was showcasing a personal project he’s currently working on: Python Fu. When I saw his design for the site, I knew he had what I lacked: The ability to translate a site design into something that is simple, elegant, and sexy while still being completely functional and cross-browser safe. He agreed to assist and was able to whip a mock-up together for me. Needless to say, I loved it. We’ve been tweaking the overall theme elements, but ever since then it’s been full steam ahead as I continue to design out and implement each page’s functionality.

Domain Management landing page

While the majority of the content is subject to change, this one is sure. The simplicity and elegance of this design will ripple throughout the Ondina Network.

The Virtual Host manager where you can configure each virtual host definition

The Virtual Host manager where you can configure each virtual host definition

There are a lot of the subtleties lost in screenshots (CSS transitions, Javascript interactions, etc.) that really enhance the impact of this theme.

As we get closer to Private Preview launch, a more in-depth tour of the control panel and its features will be released.

Ondina Web Hosting

As a lot of people know already, I’ve been working on a side-project for the past eight months; however, this is something I’ve been trying to do for almost four years. In that time there have been a lot of hard lessons learned, a lot of failed attempts, and a lot of fun learning and evolving. All of this materializes into Ondina.

Ondina is my response to how Web Hosting should be run: a company whose true focus is the customers and not the profits. This ideology should be applied to any type of business, but Hosting is where I see it at its worst. I’ve seen companies that are still charging extra for email accounts, falsely advertising “Unlimited” anything on their site, overcrowding their servers, blaming customers for the company’s shortcomings, and ignoring cries of change. In addition, they tend to attempt to suck every dollar they can from their customers: whether it be for “Premium” Support, for add-ons that should come standard, or for sub-par support. In addition to these short-comings, I’ve found a lot of hosts that run older, less secure software, rudimentary configurations, and offer generally crappy products.

Now, there are Hosting companies that are doing a lot of good things for customers; however, generally speaking the current state of Web Hosts and how they operate is still a two-way mirror. They can see everything you do, but there is no way for you to audit your host. How do you know you’re not sitting on an over-crowded server? How do you know that they monitor your machines for up-time and stability? How can you be certain that the downtime which occurred earlier was really because of faulty hardware? You have to take their word and trust everything they say.

I’ve been working on a company that operates differently . It operates on an Open Source mentality. If you’re going to pay me and trust me to host your website, whether it’s a personal blog or your company’s portfolio, you have the right to know how we operate, how the servers are maintained, and to have complete confidence that what we’re doing is the best possible way to present and maintain your presence on the web. That’s why Ondina is taking business practices and hosting to a new level: Good Guy status.

From a company perspective we plan to provide nearly 1:1 transparency on what we do regarding your account. From displaying account notes to breaking down where each penny goes from your monthly payment so you know exactly why your plan is priced where it is. We also plan to publish our entire infrastructure’s layout for review by the community and to show how we think all hosting companies should operate. We plan to spend more time and money on keeping existing customers happy and thrilled with our hosting instead of trying to hard sell new users and to always offer the highest quality with best practices in business and execution.

From a technical aspect, we will be providing that same 1:1 transparency with regards to your account. We will make our real-time monitoring systems available to you, provide live provisioning and population information for the server you’re on, and detail hardware information and your account’s resource utilization compared to the average account on your server. In addition, we plan to offer diverse hosting options such as PHP, Python, and Rails hosting all on the same account and provide a simple yet powerful control panel with which to control every aspect of how you host. Ultimately, we will be giving the power back to the user.

Ondina is more than just another hosting company. We’re here to push the limits of affordable shared hosting, offering things that the majority of hosts force you to upgrade to get. Ondina is here to set a new standard in Web Hosting.

Fork bombs, they still exist.

I’m amazed sometimes that modern Linux distributions don’t have the basic Fork Bomb prevention in place. Last night Sara started telling me how she was so furious with me a few weeks ago she considered fork bombing one of my servers. For fun Sara and I fork bombed my desktop as a “lets see how long it takes for 8GB of RAM to be exhausted” – 45 seconds if you’re curious. I had a similar experience when working for a web hosting company when some of the level 2 support personnel decided to see if our servers work protected from Fork Bombing. This resulted in my fork-bomb proofing every server in our network for the rest of the day. Since then I’ve always put appropriate ULIMITS on every production machine to prevent this from happening again. If you’re interested here is how you can do this:

Stack Overflow Meetup

Last night was the Stack Overflow Global Meetup at Fathom Creative and the weather was wonderful in DC! For those who don’t know Stack Overflow, Inc (Now StackExchange, Inc) planned a Worldwide Meetup Day which I helped organize for the DC Area. While on the subject of planning events – if you’re in DC and you need to plan an event, Fathom Creative has a gallery space that is simply beautiful and affordable. We lucked out with the weather and was able to enjoy the bulk of the meetup outside on their rooftop patio. I admit I was skeptical at first about how it would turn out – but without Sara’s help I think my skepticism would have come true. She help plan and acquire the food for the event as well as mingled and greeted everyone, helping me immensely! Meeting everyone from the various StackExchange family (Most notably: Stack Overflow, WordPress, Ask Ubuntu) was just awesome. I’m working on collecting all the photos from the evening for now you can view mine on Flickr. Getting a chance to chat with so many different and smart people is always a pleasure. Here are the photos I’ve collected so far from the meetup.

If you have any photos from the meetup, email them to me – I’d love to have them!

Standards of Development, you need them.

As I slowly make my way back into personal coding projects and releasing OpenSource again I’ve decided to publish my Standards of Development.

Why?

Standards help keep code clean and consistent while adhering and enforcing to best practices and high quality. For most languages there is no required layout for code so below is the one I employ for most projects and languages.

Code Structures

When I write code most of my code structures follow the Allman style indention scheme with some slight modifications. Tthis is probably going to be the biggest upset as a lot of people prefer the K&R style variant 1TBS. This is probably as fundamental an argument as Vi and Emacs (I use nano – so there) the only difference is no one else is affected if you use Vi or Emacs – in source code though, hard shifts between 1TBS and Allman will cause quite a few eye soars. So it’s important before you start a project to agree on a standard for writing the code.

Here’s a basic code example

<?php
/**
 * This is a test file
 * 
 * @author Marco Ceppi <marco@ceppi.net>
 * @package Example
 */
 
/**
 * Class Name
 * 
 * It does STUFF
 * 
 * @author Marco Ceppi <marco@ceppi.net>
 * @package Example
 * @subpackage if-required
 */
class Class_Name
{
	public $an_array = array();
	public $first_variable;
	public $second_variable;
 
	/**
	 * Class_Name Constructor
	 * 
	 * @param string $param1
	 * @param string $param2
	 * 
	 * @return void
	 */
	public function __construct( $param1, $param2 = 'default' )
	{
		$this->an_array = array('first' => 2, 'second');
	}
 
	/**
	 * Do Something
	 * 
	 * Additional details about what this actually does
	 * 
	 * @param string $param1
	 * 
	 * @return mixed Details about what is returned
	 */
	public function do_something( $param1 = NULL )
	{
		return $this->_processThat($param1, $this->first_variable);
	}
 
	/**
	 * Process That
	 * 
	 * Additional details about what this actually does
	 * 
	 * @param string $param1
	 * 
	 * @return mixed Details about what is returned
	 */
	private function _processThat( $param1, $param2 )
	{
		// Do something!
		if( $is_this )
		{
			// Do that
		}
		else if( !$is_other_thing )
		{
			// Doing this
		}
		else
		{
			// Gave up?
		}
 
		return $results;
	}
}

A quick break down.

Documentation

Each method, the file, and the class is documented using phpDoc format. If you’ve used Oracle’s javaDoc or any similar document templating system then most of the Syntax will be familiar. If you’ve never really documented code before consider this a wake up call.

Naming

Naming schemes are as equally important when writing code. Using a set standard continues readability of code. When creating names for methods, functions, classes, and variables the names should be as short while descriptive as possible. If a variable can not reasonably be named in less than ~15 characters it should be abbreviated as best as possible and a comment left above it’s first occurrence in the page detailing what it’s full name should be.

Formatting

While most projects typically go with either CamelCase, pascalCase, or under_score I’ve found a combination of the three to be effective in typecasting methods and variables. For starters class names are always first letter capitalized with underscores replacing spaces.

class User_Session {}
 
class User {}

Variables are all lowercase with _ replacing blank spaces

$username;
$post_id;
$multiple_worded_variable;

When naming functions and public class methods the same format for naming variables should take place.

function process_request( $req ) {}
 
class Generic
{
	public function start() {}
 
	/**
	 * Prepare Database Hook
	 */
	public function prepare_db_hook() {}
}

Finally the special cases which operate outside of the norm – Private and Protected scopes. I always treat these special when writing classes and objects. The shift from a normal naming scheme allows me to easily identify that they have a special ruleset applied to them – typically this naming scheme follows a _pascalCase format while adhering to the “15ish character” rule.

class Generic
{
	protected $_variableName;
 
	private function _secret() {}
 
	protected function _getDetails() {}
 
	private function _setUpdateRules() {}
}

Control Structures

Whether it’s an if, elseif, for, foreach, while, or switch the same general Allman style indentation applies. Parenthesis should be attached to the control structure and a blank white space should pad the open and close parenthesis at the first level. Further embedded parenthesis should hug their contents.

If, Else If, While, Foreach

These follow near the same formatting in regards to parameter acceptance.

if( !$is_active ) {}
 
if( ($user_id > 20 && $is_new) || !$is_active ) {}
 
while( $true === true ) {}
 
foreach( $array as $key => $val ) {}

Switch

With a switch each case starts and finishes on it’s own line on the same level. The default case should always be included regardless of use and should always be terminated with a break

switch( $mode )
{
	case 'first':
		// Contents
	break;
	default:
		// Fall back
	break;
}

For

The for loop should follow the same constraints as the above control structures, however I wanted to take a minute to highlight a best practice when creating loops.

Most for loops are iterating over an Array and performing various computations against it. What I see a lot, and want to stress is not best, is placement of the objects count in the evaluation portion of the loop. For loops are structured by for( LOOP START; EACH TIME; END OF EARCH RUN ) having a count executed each time the loop completes adds execution time to the script. Instead prepare everything in the loop start.

$roommate_names = array('Jim', 'Marco', 'Sara');
 
for( $i = 0, $total = count($roommate_names); $i < $total; $i++ ) {}

Or just perform the count outside of the loop. Typically I avoid for loops at all cost deferring to its cousin foreach unless there is no other possible solution.

This is a living document last updated 2011-04-05 4:00PM EDT

Automount – Making Remote Mounts, Easy!

As a part of the many tasks assigned for my new position of Administering and Managing a new and up-and-coming Linux Virtualized platforms are backups. I’ve have a good chance to see how not to run backups at my last position and it’s given me a lot of insight into the process – stale mounts are one of the many issues to overcome. Mounting a remote file-system on the local machine and maintaining stability is hard enough between two Linux machines – let alone having to mount a remote NTFS Windows File server.

Here comes Automount! I quite literally stumbled on to this while looking to solve another un-related problem (Mounting a remote linux file system with SSHFS). What is automount? It’s a daemon that runs on Linux systems and whenever a user attempts to access an “automount” monitored mount point it will ensure it is mounted (if not already) and when a mount is not in use will unmount it. This takes care of most situations where a stale mount (When the local system thinks it still is mounted, but the remote system is unavailable or has been restarted) – perfect for this application.

This was configured on a CentOS machine and here is how I did it. Make sure you have cifs (or smbfs if you are using an older distro) installed. Install autofs:

yum install autofs

First I needed to make a directory for which to mange my mount.

mkdir /media/auto

Though you can use any existing folder. Once you have done so we’ll need to setup automount to know about the mount point – open /etc/auto.master and add the following to the bottom:

/media/auto /etc/auto.media

Replace /media/auto with the directory and you can call the file which ever you like “auto.windows” “auto.servername” etc.

Next open the file you referenced. In this case: /etc/auto/media and add the following formatted string:

MOUNTNAME -fstype=, :

So for my example I want it mounted to /media/auto/windows1 using cifs and my username: halle password: swordfish and domain: berry on the windows share //10.10.0.2/travolta

windows1  -fstype=cifs,rw,noperm,user=halle,pass=swordfish,domain=berry ://10.10.0.2/travolta

Now in the above example can be customized for all sorts of mount types found in fstab – this is just an example for Linux to remote windows share.

Once you’ve completed that, restart autofs:

/etc/init.d/autofs restart

and navigate to the created folder:

cd /media/auto

If you do an ls you should see nothing. Because the mount is only accessed when needed. If you cd in to the mount name (defined above in the auto.media file) and do an ls you’ll now be on the Windows share.