I believe I'm a MySQL Certified Developer Now

June 8th, 2009

I just passed the 2nd test over the weekend for the MySQL developer certification. It was definitely harder than the Zend Certified developer test. There is no way I could have passed without some serious studying. The test covered tons of topics such as Client/Server Concepts, Joins,The mysql Client Program,,Subqueries,Connectors ,Views,Data Types ,Importing and Exporting Data,Identifiers,User Variables,Databases,Prepared Statements,Tables and Indexes,Stored Routines,Querying for Data,Triggers,SQL expressions,Obtaining Database Metadata,Updating Data,Debugging MySQL Applications,Basic Optimizations.

It's a two part, 70 questions per part test. I would definitely suggest getting the study guide as well as reading the online manual.






The Right MySQL Engine for High Capacity Servers

April 22nd, 2009

As you may know there are many storage engines in MySQL MyISAM, InnoDB, Falcon, CSV, Blackhole, Archive, etc...There is a storage engine that comes with the MySQL Max Download called the "Blackhole Engine". According to the documentation it basically dumps it's storage to /dev/null. A storage engine that doesn't store anything? What good could that be?

Well if you run in a high volume production system where you may have one or more master databases for writes/updates/deletes and a whole farm of slaves reading the log from that master than this may be of interest to you. The concept is pretty simple. You have a Master database that is in charge of all your inserts, deletes, updates which in turn has connections to all those slaves. That means network traffic, disk I/O, CPU power all taking up resources that you really want for the Master's primary goal of collecting and maintaining data.

This is where the Blackhole Engine comes in. The actual process of logging the SQL statements that hit the Master database that the slaves consume lives above the storage engine level in the main MySQL server level. So with the Blackhole Engine piping data to /dev/null you can actually use it as a proxy to your slaved databases without the need to duplicate the data on that machine (it could very well be on the same machine!). See below for an example image...



What you then have is the Master only replicating to one database, increasing the Master's capacity to process transactions. The slaves consume the log file from the Blackhole server. It acts as a proxy at this point, with the benefit of freeing up resources on the Master's server. This could also benefit multi continent replication set ups where you can have farms of blackhole servers farming data to farms of slaves around the global for faster local access times. The possibilities are endless!

All this just for some MySQL training?

April 16th, 2009

So I had a little wiggle room in the budget and one of the things I wanted to do was to improve the team's knowledge level. I contracted out training and consulting with several firms the first of which is MySQL(sun microsystems). I wanted an onsite developer training course for a week. Seemed simple enough at the time, how hard could getting training be I already had the approval from the higher ups to go ahead. Here is the process I had to go through.......


1. Contact MySQL to put together a training package, work out costs, requirements, etc...
2. Get Statement of Work from MySQL to start the process on our side... ok everything is fine so far
3. SOW has to go through procurement (2 weeks), they start looking over all those "terms & conditions" pages that we all usually ignore, they make tweaks to justify salaries
4. Legal gets involved to help justify their salaries as well, giving blessing to Sun's terms and conditions.
5. SOW goes back to originating department for approval of new terms
6. SOW goes back to procurement to issue a PO number
7. Now with a PO number we can finally schedule the training session
8. Now with the date booked, email goes out to management for approval on lunches for the week for the devs and training
9. Need to find out who is in charge of the training room bookings, found the person, booked the training room for the week
10. Lunches OK'd now need to find the person who will be ordering/paying/managing the lunches for the week
11. Found the person, worked out where we can order from locally, assign the task of working with this person to one of the developers cause I don't have time for all this crap :)
12. Need to get trainer access for the week, have to start NDA and Badge process
13. Work with several different departments, first department sets up the NDA that the training will have to sign on arrival, had to fill out paperwork
14. Second department deals with badge access, need to fill out paper work for trainer's visit and define when and where trainer should have building access
15. Building access needs to be approved by higher ups
16. Third department deals with the laptop that the trainer will bring. Their laptop will need to be kept track of since it's not a Panasonic issued laptop.

that's about as far as I've gotten so far. Hopefully those are the last hoops I have to jump through. The sad thing is I have to go through all this for 5 more vendors in the next two months :(

**UPDATE**
A week later I was informed by legal that Sun/MySql's badge access was not approved. *SIGH* I had to be the one to tell them that MySql was here and gone and thanks for the timely response.


Why Your PHP app NEEDS a Circuit Breaker

April 8th, 2009

More and more websites these days are relying on external resources for data and functionality. Each one of these services introduces a stability hole in your application. You're now relying on the uptime of an external resource. Yahoo, Google, etc.. ALL have downtime at some point. No one has a 100% SLA. This means that more than ever you need to code defensively to prevent external resources from tarnishing the user experience of your site. This is where the Circuit Breaker Stability Pattern comes into play (From the book "Release It").

The Circuit Breaker Pattern is a simple concept. If too many connections fail while accessing a resource the circuit is "opened" or stopped at that point. After a certain period of time we let one connection go through, if that one works the circuit is re-closed and operations resume as normal. Let's break this down further.

Your site connects to Google to get a list of widgets. The Google service goes down and now your customer is stuck in a timeout waiting for the connection to fail. You have no idea this is happening. You think everything is fine, until people get tired of waiting, your connections pool up and you run out of resources on your machines while 10,000 people are waiting 30 seconds to timeout. This makes your site look horrible to the user and they find somewhere else to query for these widgets. The goal is that if something is constantly failing you stop calling it and notify administrators and users.

The Circuit Breaker pattern defines a max number of failures (threshold) that can occur before the circuit is tripped. So let's say we want to stop connecting to Google after 5 people's connections have failed in a row. Now we can immediately return responses back to our users letting them know the service is down or they're query has been stored for processing at a later time. An informed user is a happy user, even if something does work they like to know about it immediately. After 10 minutes or so we want to open up ONE connection to test the waters to see if Google is still down so we open the circuit "halfway". If that connections fails we reopen the circuit and await the next timeout. Once a connection is successful again we re-close the circuit and operations can resume as normal. When a circuit does open we want to alert our operations group or the site admin so they know there is a problem with this service.

This allows you to automatically shut off and re-instate services if failures occur. It's a very powerful concept in increasing the stability of your system.

I've created a very simple, sample Circuit Breaker class in PHP that can be used for this purpose. It currently assumes a mysql database to store this information but you can replace it with a memcached or other in-memory caching option for increased performance. You can find all the code and samples here: http://code.google.com/p/plushcode/source/browse/#svn/trunk/stability_patterns/circuit_breaker

The schema is listed out below for the table

CREATE TABLE IF NOT EXISTS `circuit_breaker` (
`id` int(5) NOT NULL auto_increment,
`app_id` varchar(255) NOT NULL,
`failure_count` int(5) NOT NULL,
`threshold` int(5) NOT NULL,
`state` enum('open','closed','half') NOT NULL,
`timeout` int(5) NOT NULL COMMENT 'timeout in seconds',
`last_open_time` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


Let's start going through the fields....
app_id - Each external resource you have (including databases!) should get it's own application id that is unique. Something such as "google_widgets" works fine.

failure_count - Each time a failure occurs this is incremented by 1. Once a successful call has been made it is reset to 0

threshold - The number of times a service can fail before we open the circuit and stop all processing

state - The current state of the service. It's either closed (normal), open(failure occurred) or half(we're trying one more time)

timeout - The number of seconds to wait before attempting a connection again

last_open_time - A timestamp when the circuit was last opened which would indicate a failure


One of the nice aspects to having this in the database is that you can easily monitor all of your external services from one site. All you have to do is query the table and you can see exactly what the health of your system is. Here is a quick and dirty sample report http://www.litfuel.net/tutorials/cb_report.htm

To use this class you simply call it as seen below:
  1.  
  2.  
  3. require_once('CircuitBreaker.php');
  4.  
  5.  
  6. $cb = new CircuitBreaker('myapp');
  7. $cb->logging = true;
  8.  
  9. if($cb->isClosed()) {
  10. if(!$res = @file_get_contents("http://litfuel.net/tutorials/testserver.php")) {
  11. $cb->fail();
  12. } else {
  13. $cb->success();
  14. }
  15. var_dump($res);
  16. } else {
  17. // notify the user, send them to a different service or anything!
  18. echo 'CIRCUIT TRIPPED! NO CALLS MADE';
  19. return false;
  20. }
  21.  


What we're doing is including the CircuitBreaker class, then we're making sure the circuit is closed which means everything is A-OK. We make a web services call over to my test server page. If that connection fails then we call $cb->fail which then tests to see if our failure count is over our threshold and if not, increases it by one. If we are over the threshold it will open the circuit and all future calls will return false when isClosed() is called. If the connection is successful then we call $cb->success() which resets the failures back to 0.

To test this out:
1.create a test database
2.import the schema into the new database
3.enter in one record called "myapp" as the app_id, put in 5 as the threshold and 10 as the timeout value
4.paste the Test.php code into your own file
5.When you run the code you should see a var dump of some xml data which indicates success
6.Now change the url in the file_get_contents line to a url that does not exist
7.Start to refresh your page and you start to see the connections fail and then the circuit trips, after 10 seconds it opens up halfway, does one test then reopens for another 10 seconds



Yet ANOTHER opening for Zend Framework Developers here at Panasonic

April 7th, 2009

We now have yet another opening for Zend Framework php developers here at Panasonic. To be clear this is the Avionics division of Panasonic, there have been ZERO layoffs in our division. We're meeting all our numbers. So lets get some decent resumes over here :)
jiminoc @AT@ gmail.com

Rebrand your web app just like AIG

April 6th, 2009

By now we've all seen that AIG has removed their logo from their main corporate headquarters in New York. The name is tarnished and they will be forced to re brand themselves to attempt to gain trust from investors and clients again. Phillip Morris just recently made the same move. So how does this help you with your application? We've most likely all had to maintain someone else's code base at some point. You're the new guy and you get stuck on the project no one else wants to do. Sometimes this project has high integrity and has a good reputation within the organization, then there are times where you are tasked with re-tooling or re-implementing an existing tool.

I find myself in a situation here where there is an existing tool that was contracted out to be built without supervision, not in a standard framework of any sort. It's a huge tool at this point over 200,000 lines of php code, javascript mixed in with php, no separation of code, functions declared in individual pages, Numerous security holes, really just an unmaintainable mess at this point. Let's say the application is called "X123". X123 has a horrible reputation here. Customer complains, internal complaints, etc... no one has faith in this tool. As we start the requirements gathering process for an internal rewrite the first order of business I wanted to get done was re-brand the new application. You don't want people mentioning X123 anymore. It's name is tainted, you want your new application to instill confidence. Now we can call it "A987" (names changed to protect the innocent).

No one knows "A987" it has a clean slate with our user base. It's up to us to keep that name untarnished. Re branding has already enabled us to work with stakeholders without the negative feelings X123 brings, people get exited knowing there is a new project to replace it. Sometimes you're in a position to re-brand these legacy internal applications, but what if you can't? What if the name is set in stone but is a tarnished name? The best thing you can do is let the user base know there is a new sheriff in town and you want to work with them to address existing issues they have. Create a bug reporting link on your application, treat each customer complaint like a stage 1 missle alert. Give constant feedback to users on the status of their bug reports, make sure you track all changes and send out release notes to show progress. Make sure you show people the app is moving in the right direction. Everyone has a customer, even for internal applications your co-workers are your customer, make sure you treat them as such.

Remember you and your team control how you are viewed to the outside organization or world. Professional programmers value that reputation and want to see it stay solid. Scripters are there for a paycheck and aren't overly concerned with customer satisfaction. Be a pro.



Fix for Zend_Session output headers issue and Phing

April 1st, 2009

Came across this issue while writing a Phing build script to run my Unit Test Fixtures

"BUILD FAILED
exception 'Zend_Session_Exception' with message 'Session must be started before any output has been sent to the browser; output started in /usr/local/php5/lib/php/phing/tasks/system/PropertyPromptTask.php/92' in /home/plushj/Code/unity/library/Zend/Session.php:419
"

The issue that solved it was adding this before I used Zend_Session in my testing bootstrap.php file

Zend_Session::$_unitTestEnabled = true;




Why I chose Zend Framework for Enterprise

March 26th, 2009

Why I went with Zend Framework for Enterprise

At Panasonic like most large companies we have a plethora of websites ranging from little one off reporting sites to full scale applications. A major problem arrises when these sites are left up to the discretion of the developers to choose their own styles, languages and frameworks(mostly custom to themselves). Site 1 could be in perl, Site 2 in ruby, Site 3 using CakePHP, Site 4 using a user built framework, etc.. When the developer of Site 1 leaves or moves on to another project now we have a maintenance nightmare. Who takes that over? Who really wants to maintain someone else's perl project when they are primarily a PHP developer? I'd rather see that person develop deeper PHP skills.

This was where we were 7 months ago. During that time I've been developing a Zend Framework based application that will house all these sub-apps as "modules" underneath the main Zend umbrella. Management has seen the light as to having a clear, concise codebase that all developers can be trained on and move in between applications with ease, eliminating ramp up time learning different code bases.

After a few weeks of evaluations I settled on Zend for a few reasons. #1 It has a company behind it. It means a lot to me to be able to pay out some budget money to get proper training for developers or have people on the ready for support issues. #2 It's flexible, I can adapt it to the way we work as opposed to being religiously stuck in a coding paradigm. I've been able to leverage the Framework for supporting CLI scripts that have made development insanely fast. #3 stability that there are paid developers actively maintaining, testing and releasing new features. #4 small footprint in the fact I can plug and play different pieces of the framework with ease. #5 there is plenty of documentation and reference book material out there to ramp up quickly which means I don't have to document as much. Some would argue that Zend is slow, however when you have money to budget for load balancers, clusters of servers, slaved DB servers, etc, opcode caching, memcached memory caching, etc... you can tune Zend for acceptable speed.

Since then I've borrowed the SQL migrations concept from rails for more elegant DB updates for all modules. Modules can now be dropped on the server and a "Migrate.php up" script can be run to patch the DB to the proper level. A custom ACL was built on top of Zend ACL to allow fine grained page and ad-hoc permissions. Consistent UI css structures that will allow users to reuse existing UI components and not have to worry about look and feel. Module discovery code for navigation building, as well as general module initializations as well as a host of other features.

I've had my ups and downs with Zend over the years (google: jim plush zend ) but I believe they're on the right track with the framework and we're dedicating all in house development to Zend Framework. If it's a web app it's either built in our Zend Framework infrastructure or it doesn't get built. We've also just contracted with Zend training to do some onsite framework training for all our developers to make the transition as smooth as possible. Upsides to this for developers is the fact you're getting trained for free on the most popular php framework out there and no longer will you have to spend your weekends learning someone's code who just quit.

Some things that will help us keep on the straight and narrow...

1. Code reviews.
NO new modules or releases can go to the test cluster without being approved by a module maintainer. This allows us to spot issues with consistency and security issues

2. Code inspector
I wrote a module code inspector that will check modules code for non-escaped view variables, not using prepared DB statements, leaving debug code in, not registering ACL resources properly, etc.. This helps spot issues before they hit a server

3. Unit tests
Mandating at least all business logic in the models directory have unit tests that hit all public methods.

We've invested heavily in Zend Code Audits, outside Penetration tests for security holes on the web app side as well as the network infrastructure side, scalability and disaster recovery. We'll chat more about those at a later time.

So far Zend Framework and jQuery on the front end are smooth sailing in my book.




Panasonic looking for PHP/Zend Framework Developers

March 18th, 2009

hey all!
We're looking for one or two solid Zend Framework developers to work onsite in our Orange County offices for a 3-6 month contract, possibly leading to full time work.

Skills required: Zend Framework, jQuery, MySQL

Drop me a line at jiminoc AT gmail DOT com
for more details!

(Must be legally allowed to work in the U.S.)

How to manage web projects successfully

February 19th, 2009

In a previous posting I discussed what separates a professional php developer from a scripter. This post goes more into how to successfully manage web projects. I've been in software for almost 15 years as of this post date and I've seen my share of successful and failed projects. These are some tips I've learned...

The lifecycle of a project:

1. High level discussions on what the project is
2. Flush out requirements
3. Prototype
4. Create tasks / assign tasks based on requirement
5. Create source control repository
6. Code requirements
7. Test
8. Deliver

Now we'll start to break these down into individual components. In an agile process steps 1-8 could be done every 2-4 weeks which is my preferred method of delivery.

STEP 1: High level discussions on what the project is

I've rarely had the luxury of a real, solid project manager so most of the time I've been the one taking projects from ground zero to complete.

Find the key stakeholders or the person who is assigning you the project and form a small tiger team. There is a saying that goes "one too many cooks in the kitchen" and no place is that more true than in software development. There is a defining metric between how many people are on a project and how long that project takes to start. I always try to find the key people with the most business knowledge for the project and start to flush out what roles those people may be involved in. For example you may need one person for only half of the discussions and the other half they may offer completely irrelevant opinions. If you tell someone you value their opinion for 50% of the project, they'll assume their opinion is right for 100% of the project which is usually never the case.

During these high level overviews I try to jot down things such as "system should dos" and bullet points on requirements. The key for a software developer to complete a project successfully is to understand the business need. These aren't your personal pet projects. Someone is paying you to do something that helps them make or save money. Take the time to understand their business needs. Your goal is to deliver something that meets THEIR needs, whether that be one person contracting you or a department in your organization. The end game is customer satisfaction. This is the number one thing that takes you from junior to senior.

Once I have a good understanding of the project and the business needs I start a wiki site for the project. Word docs are sooooo 1994 when it comes to managing requirements and projects. Once you have free and open online collaboration there is no going back. Over the years I've had opposition to wiki based projects. Project managers sometimes fear change. They get very comfortable in spreadsheets and word docs. One trick I do is to tell them little white lies if I meet opposition. I would tell them the wiki has a MS WORD export feature so we can always print out a word doc for them. Of course by the time we're in the project they usually can appreciate the wiki so much that MS WORD never comes up again. On that project's wiki site I create a few sections:
1. Overview
2. Requirements
3. Documents
4. Whiteboard

The overview section is meant to give a reader a 5 minute or less human readable summary of what the goal of the project is. It should be something measurable and have substance. I have the stakeholder sign off on the overview which then gives them peace of mind that you understand their needs. The requirements section will obviously hold the requirements. The Documents section contains any relevant documents you'll create such as API docs, App documentation, etc... The Whiteboard section contains random free thoughts or bits of information that may be put into a requirement in the future. A whiteboard is a free for all area. I document everything, meetings, thoughts on the project, tasks, docs, anything! A wise programmer once told me, it's not who knows the most, it's who can find the most information the fastest. It's easier to remember indexes to the information than the actual information. She went from programmer to president of a multi million dollar software company so I've heeded that advice.



STEP 2: Flush out requirements

Once you know where you're going it's time to define how you get there. Requirements are either something you hate or love. A requirement should be something measurable that can be made into a test case. Something along the lines of "A user shall be able to place an item in a shopping cart", "A user shall be able to call a web service to get a list of orders". These are more along the lines of user stories. For these requirements I attach a few pieces of info. Tasks, Description, Owner. Requirements are features the system should have, Tasks are what it actually takes to do those features. So a task for our shopping cart requirement could be "create DB schema for cart".

Start to go through what the system needs to do, make use cases for how the system will actually be used. Start to really thing about the workflow that someone will go through on the site. What are all the tasks a user needs to do with your system. Get everything down on the wiki, no matter how big or small or how pie in the sky. Never say something is too big or too small. Once you have a good backlog of things the system should do then you can start prioritizing. I always like to start with the smallest thing that works. What is the bare minimum this system needs to do to meet the goal in our overview section? Package those items up and you have Release 1. Within release 1 you then want to create mini milestones. Being able to deliver working, testable pieces every 2-4 weeks is imperative. NEVER EVER attempt to build the entire system then show your stakeholders at the end. It just doesn't work. Being able to deliver testable sections of the site does a couple things. One it shows progress and management loves progress, two it allows for rapid changes. "Ohhh I don't like style, change it to this instead". Changes are easy when things are fresh in your head. There is nothing worse than having to go back to things you did a year ago.

So once you have your release 1 requirements and your milestones defined you're ready to get to work.


STEP 3. Prototyping
It would be sad if you just did the same projects over and over. The nice thing about software is there are always new challenges. There will almost always be something you don't know how to estimate or a new technique or widget you want to try. This is the time to do some initial screen designs, play around with some frameworks or libraries, write some experimental quick piece of code to get the hang of something.

If your projects is UI based then you'll want to come up with some initial screen designs or layouts to present to the stakeholders. I try to keep people in the loop every step of the way so changes and adjustments can be factored in immediately.


STEP 4. Tasks
After you have your initial set of requirements you'll want to start breaking them out into tasks. If you have a lot of requirements I would suggest breaking the requirements out into smaller milestones that can be achieved and testable in 2-4 week periods. Each task should be a 5 day or less piece of work you or someone has to do. Keep these close with your requirements. Tasks would be things like "Create DB Schema", "Import jQuery library into source", etc... Once you have a month or two's worth of tasks that's enough to start coding. Make sure you factor in estimates on how much time you think you'll spend. This is akin to the way scrum works. If you work 8 hours a day you're not really working 8 hours. You have to answer emails, take calls, work with peers, research, vacation time. Take whatever total number you get and add 10-20% at least to that number for realistic hiccups, or that project you worked on last year that needs support for a few days again.

Step 5. Source Control
This will be short, you should always start out with a repository for your source control that is on at least a nightly backup schedule. Even if you're working on it by yourself it's a required piece of the puzzle. Tag your codebase after every release or milestone.

Step 6. Code Requirements
Start going through the tasks and requirements assigned to you. Usually I prefer to take the low hanging fruit first which are the fastest tasks I know how to complete. If something takes thought I like to think through it as I'm doing mundane tasks or on off time. By the time I'm ready to code it I've usually come up with something better than my first ideas. If you're working on a team try to do code reviews in your spare time to make sure everyone is following the company standards or the team standards.

Step 7. Testing
There is no doubt in my mind the value a good tester or test group can bring to a project. Even if you have a tester unit testing your code should be a requirement and be factored into your time estimates. Unfortunately full unit testing is sometimes somewhat of a luxury. The idea that you should have 100% code coverage may be a stretch for most real world jobs. I've gotten to the point where I at least mandate that the business logic have unity tests behind them. This allows you to run your test suite prior to releases to make sure nothing has been accidently broken. A good test team will have automation for the front end that will exercise your view/controller logic. Of course I'm joking because I've never had a QA department realize the importance of automated testing groups. Your unit test suite should be developed at the beginning of the project and not smuggled in a month down the line.

Test for failure! You're software really won't work perfect all the time, there are always unforeseen variables, network outages, down servers, etc... My previous project was a touch screen application for in flight entertainment systems. My code is 30,000 feet in the air, if something goes wrong I can't just ssh into the box :)
So testing for failure of all points is critical.

Step 8. Deliver
Every 2-4 weeks deliver or demo your testable code or the finished product. Ensure sign off from the stakeholders, if there are questions or concerns point them to the signed off requirements that you worked with them on. If they still need changes, you can roll those into future milestones.


Parting thoughts...
1. Don't be the buggy guy! Don't be the guy who checks in code that is not tested. If you work on a team create a dev server you can all test committed changes on. You checkin, get latest to the dev box and make sure it works on the dev box as well. No one likes the guy who breaks the builds.

2. Take your time, do things right. Hacks are things of last resort. If you're stuck, ask a coworker for advice. It shows maturity and team mentality.

3. Communication. Nothing ruins a project more than poor communication skills, why do you think that's on every job rec there is. It's important! Keep people in the loop. If you make a new widget in your framework, write up a sample and email it to the team. Keep your stakeholders informed of your progress and roadblocks. In software there is NO guessing. It either is or it is not. Make sure you're not guessing and what your stakeholders want. If there is a question, ask them. Make sure you set this open line of communication, they'll be happier in the end.














Cnt: