Wednesday, February 17, 2010

Day 31

I am just going to title this post because I know the connotation it will inevitably invoke.
How the SocketServer services the Client's Socket
I apologize if you find this unnecessary or inappropriate, but I can only imagine what is going through Kichu's head while he reads this.

Creating a multi-threaded system is always interesting. It is extremely difficult to be certain none of your threads will collide. It is virtually impossible to be certain if you have no tests. There are always a multitude of unexpected errors, race conditions, and concurrent modification issues (yes yes, I know this is a java error name) that can pop out and surprise you... or worse, lurk around until your not paying attention and then bite you in the a**. This is why it is important to be consistently coding in a thread safe manner, using locks and semaphores when you can, testing lots of possible variations of how the code can be run, and running your tests several times in a row each time you make a threading change.

For my Socket Server I had to spawn up a flurry of threads to run many simultaneous actions. So first, a brief over view of how the Socket Server worked, and then I will explain how I remained thread safe.

Some application would start up the Socket Server, which would create a Server Socket to watch a specific port. Then presumably this application would like to be able to accomplish others tasks while the Server Socket is simultaneously monitoring its specific port, thus the Server Socket needs to sit in its own thread called the ServerSocketThread.

The Server Socket is in a constant loop, checking to see if any Client Sockets have tried to talk on the specified port, for as long as the Server Socket is let to be open. If a Client Socket attempts to connect on this port, the Server Socket needs to accept the client's request. To accept, the Server Socket must create a server side socket to pair with the Client Socket, and then instruct this server side socket, called the SocketServicer, to serve the Client Socket. The SocketServicer has to serve the Client Socket while the Server Socket is still monitoring the port, thus a new thread, called a nobleServiceThread, must be created for every single Client Socket- SocketServicer pair.

Once the SocketServicer has finished serving the Client Socket, the nobleServiceThread will automatically close itself and end the connection as well as terminate itself.

If the Server wants to close one of it's Server Sockets, the Server Socket will have to make sure all of it's SocketServicers and nobleServiceThreads are closed and terminated before it can be closed. There must, therefore, be a list of all of the nobleServiceThreads. The Server Socket must loop through this nobleServiceThreads list and terminate each thread. To simply kill an active Socket, however, would mean you are suddenly cutting a client off in the middle of an interaction, and that is bad practice. Thus the nobleServiceThreads must first be given a chance for the Socket to finish and close up before they are cut off, and as such must be given a TimeOut Period before they are automatically cut off regardless of status. Once cut off, the deactive thread must be removed from the list.

Ok, now down to business.

There are a few smaller and somewhat trivial threading issues, some of which involving testing, but I am just going to go over the biggest and most interesting one I encountered.

So we have this list of nobleServiceThreads that each are running a Socket which can finish at any time. We also have a Server Socket which might want to close at any time, thus having to close all of the nobleServiceThreads. Thus, right away we can see the race condition. Can you guess what it is?
If, while looping through and closing the list of nobleServiceThreads, a Socket finishes it's interactions and decides to close, it could potentially remove itself from the list we are iterating through. This means we could be trying to remove a thread that is at the same time removing itself. Lets look at some code:

First, here is the Server Socket's thread/loop which watches a port and accepts incoming Client Sockets:
private Thread makeSocketThread()
{
return new Thread(new Runnable()
{

public void run()
{
while (serverSocketOpen)
{
runServerSocket();
}
}
});
}

private void runServerSocket()
{
try
{
Socket clientSocket = serverSocket.accept();

Thread servicerThread = new Thread(new ServiceRunner(clientSocket));
nobleServiceThreads.add(servicerThread);
servicerThread.start();

}
catch (IOException e)
{
}
}


We can see that as long as the Server Socket is open, it will continue to make new threads for incoming Clients.

Here is what the nobleServiceThread does:

private class ServiceRunner implements Runnable
{
Socket clientSocket;

public ServiceRunner(Socket clientSocket)
{
this.clientSocket = clientSocket;
}

public void run()
{
try
{

applicationServer.serve(clientSocket);
clientSocket.close();

}
catch (IOException e)
{
e.printStackTrace();
}
finally{
lastBreath();
}
}

private void lastBreath()
{
nobleServiceThreads.remove(Thread.currentThread());
}
}


I call them nobleServiceThreads because if they are about to be killed, their very last wish is to remove themselves from the list such that they don't burden the ServerSocket with dead weight. How kind.

The first step to preventing the thread from removing itself from the list while it is being removed elsewhere, is to make the nobleServiceThreads list a Synchronized list:

private List<Thread> nobleServiceThreads = Collections.synchronizedList(new ArrayList<Thread>());


Next, since we don't want a thread to be potentially modifying our list while we are iterating through it, we don't use an iterator to go through the list. Instead we just loop while the list isn't empty:

public void close() throws IOException, InterruptedException
{
if (serverSocketOpen)
{
serverSocketOpen = false;
while (nobleServiceThreads.size() > 0)
{
nobleServiceThreads.get(0).join();
nobleServiceThreads.remove(0);
}
serverSocket.close();
}
else
serverSocket.close();
}


Now this is pretty good, but we still have an issue. This one is a little tougher to guess. If, and this actually happened about 1/5 times when I ran the tests, a nobleServiceThread is active right as the while (nobleServiceThreads.size() > 0) is checked, and then right before the very next line, the nobleServiceThread removes itself from the list - then the nobleServiceThreads.get(0) could return null (if this was the very last thread).

This is a tough issue. For awhile I was almost tempted to put in 100 if statements checking to see if the thread was still there before I removed it, but of course that wouldn't change much. So instead, with Micah's help, here is the solution I've got:

public void close() throws IOException, InterruptedException
{
if (serverSocketOpen)
{
serverSocketOpen = false;
serverSocket.close();
serverSocketThread.join();
while (nobleServiceThreads.size() > 0)
{
Thread thread = null;
synchronized (mutex)
{
if (nobleServiceThreads.size() > 0)
{
thread = nobleServiceThreads.get(0);
}
}

if (thread != null)
{
thread.join(TIMEOUT_PERIOD);

synchronized (mutex)
{
if (nobleServiceThreads.contains(thread))
{
nobleServiceThreads.remove(0);
}
}
}
}
}
else
serverSocket.close();
}


The mutex is just a regular object that the synchronized block can hold onto, thus preventing anything else, trying to use the same mutex in a different synchronized block, from acting. Here is how the nobleServiceThread changed:

private void lastBreath()
{
synchronized (mutex)
{
nobleServiceThreads.remove(Thread.currentThread());
}
}


This prevents the nobleServiceThread from removing itself from the list if the ServerSocket is looking at this same nobleServiceThread to remove it.


Now you might ask " Since the nobleServiceThread's lastBreath is used in the finally{ ... } clause (which will execute in the end, no matter what, when you try to kill the thread), why not just call interrupt on the thread as soon as you've got it?"

This is because the applicationServer.serve() method might be talking to a client. If it is waiting on a response from the client, and thus is in a reading block, than the interrupt wont reach the thread until the reading block is finished. Thus, the interrupt could potentially wait forever while the thread waits for a response.

The interrupt signal actually only reaches the thread in 3 instances. When the thread is in a wait(), join(), or sleep() method. So a thread can only be interrupted when it isn't doing anything. (In case you didn't know, a thread is in wait() while it is waiting for its chance to use the processor, and in a join() when the application is telling it to finish its last task and then terminate). So if you send an interrupt signal to a thread while it is performing some task, a flag will be marked and next time the thread is waiting, the JVM will check the flag and terminate the thread.

I must give credit to the Software Craftsmanship Articles 8-11 written by Uncle Bob, since they walked through many of the same steps I listen here.

Tuesday, February 16, 2010

Day 30

I am sorry, but I had just a very unpleasant Git rebasing experience, where there was a conflict in just about every line of every file, but of course it only showed me one or two conflicted files at a time. Thus I would remove a flurry of retarded conflicts, add the files and then rebase --continue, and once gain there would be more stupidly conflicted files. I was trying to rebase about 20 commits at once, probably not a good idea in the first place, but either way I failed to pick a good commit to rebase onto I guess, and thus my rebase failed. Now for whatever reason a few of the tests aren't passing and I don't know why.

A URL, or Uniform Resource Locator, is the standard addresser used for most http interaction; however it is not limited to http.
A URL is composed of two main parts, the protocol identifier and the resource name.
http:// www.starcraft2.com
|____| | ___________________|
protocol resource name

There are several different types of protocols, other than http, like FTP (File Transfer Protocol) or one we all see quite often, File. The File protocol is the one used locally on your computer to navigate your system.

The resource name has 4 different components, 2 of which are optional and often implied.
There is the:
Host Name - the name of the machine where the resource lives - for the starcraft2 URL this is the full www.starcraft2.com

File Name - path name to the file on the machine - if you went to www.starcraft2.com/features, the /features portion is both the file name, and what is called a 'relative URL' (meaning it is a locator relative to the base URL)

Port Number - this is typically implied, but can also be specified. For most sites you will ever go to, the port number is 80

Reference - a reference to an anchor in a specified location in a file. This is optional, and you typically wont notice this.

I will expand the resource name to its full form so you can see the components:

www.yahoo.com:80/index.html
|______________| |__| |_________| Host name - Port - File name
For most browsers, when the site ends with .com/ this implies a /index.html This isn't universally true, but for most websites that is the case. For example, this doesn't work for www.starcraft2.com because, I believe, their site is so pro and Flash based, that they find these norms irrelevant (try typing it, the error page is funny).


Connecting to a page, without a browser, is actually pretty easy. One easy way is to go to your terminal and type:

curl www.starcraft2.com this wont actually give you a connection, but will just print out the source of the page. If you want to save the source using curl, you can type:

curl www.starcraft2.com >> ~/Desktop/starcraftSource.txt

Most languages have built in methods to connect to a URL, and I know you are all gonna hate it, but I will show you the JAVA way since I am making a Java Socket Server.

import java.net.*;
import java.io.*;

public class URLReader {
public static void main(String[] args) throws Exception {
URL sc2 = new URL("www.starcraft2.com");
URLConnection sc2connection = sc2.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(
sc2connection.openStream()));

String inputLine;

while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);

in.close();
}
}


This will open a connection, grab all the html, and print it out. There are other things you can do with the connection, like write to the server.

Most html pages have 'forms' - GUI objects that allow interaction with the site. User to HTML page interaction is written into the URL by your browser, and then sent to the server. Once the server receives the new URL, it process it, builds a response, and sends back a bunch more HTML for the browser to view.
Lots of HTML forms use HTML POST METHOD to send data to the server. This is called 'posting to a URL'. The server recognizes a post, and then responds.

If you know what objects are meant for interaction, or the form the URL takes after an interaction, then you can just write that URL directly to your connection, and see the response.


Later today I will go over a lot of the interesting Threading issues involved with making a Socket Server.

Monday, February 15, 2010

Day 29

Programming a java HTTP Socket Server is proving to be quite interesting. I spent several hours today just reading and taking notes of the Hypertext Transfer Protocols and all the complexity of moving information around the internet. Then I actually got some help from the Craftsmanship Articles written by Uncle Bob, which I had read last year. It turns out that Alphonse and Jerry created their own Socket Server in java, which is quite similar to a part of what I need to do. I also just got done reading a rather interesting article about what it means to program an AI, and it turned the idea of human intelligence on its head, if i may.

There is a plethora of detail in HTTP, and the RFC documents are very dense and a tough read. I found the only way I can really absorb much from it is by taking notes and trying to spit back the knowledge I acquired from these documents.

HTTP has gone through a few versions now, starting with HTTP/0.9 which was extremely basic, and evolving into HTTP/1.1 which seems to be the standard these days. In its most basic form, all the HTTP is, is a standard way to ask for or send to a program some packets of data.

All HTTP interactions happen through a Request - Response form. First a client (a program connected to a server) sends a request to a server. Once the server receives this request, it processes it, and builds and sends the appropriate response. If the client wants any further information, it must package up and send another request. Often there are several intermediaries as well, such as Proxies or Gateways, which will receive a message from the client and then perhaps perform some manipulation before forwarding the message to the server.

Most programs using HTTP to interact will also have a cache. This is some local memory used to store different requests and responses, already packaged and ready to be sent. Using a cache can save a server or client a lot of processing time, so that the only real limitation they face will be the time it takes to get back a response.
Caches can also be particularly useful if there several proxies, gateways, or intermediate servers sitting between the Client and the Origin Server. If, for example, a client needs to send a request through proxy A and B before reaching the server, then both proxy A and proxy B can build up a cache to save time. Proxy A could save the Client's request, and the response coming back from the Origin Server. This way, the next time Proxy A gets that same request, it can just send the stored response right away without having to wait to hear back from the server.

When I say 'package' a request or response, I mean forming a proper HTTP message. The desired data in any message is called the entity of that message. The entity can't be sent on its own because it might not be in a familiar form for many different programs on the web, so it must be packaged into a formated HTTP message. These typically consist of a few header-fields which define certain basics about the entity, like its length or perhaps encryption type, and then the message-body which will contain the entity.

Typically if an HTTP formated message wants to send complicated data structures it will use MIME types. A MIME, Multi-purpose Internet Mail Extension, is just a standard way or form to send complicated data in HTTP messages. There are a variety of MIMEs, and I have much more to learn about them in order to understand how they actually vary.

A Socket Server is a type of server that uses Sockets to handle multiple requests. Say you have a server hosting your website which provides some service to clients. The most basic of servers will be able to talk to just one client at a time, and will focus all of its attention at that one client (spending far far too much time just waiting for the next request); but say you want your website talking to multiple clients at the same time. You might use a Socket Server to create a Server Socket for each port you wish to talk on, and then generate a Socket for each new client it wishes to talk to. So a Socket Server will make Server Sockets. A Server Socket is a place holder that is watching for any communication on a port, like port 80 (the standard port for communication on the internet). Once the Server Socket sees a client trying to talk to your server on its specified port, it will create a Socket for the client to talk to. The Socket will then handle any requests from that one client, and send responses back once it is able to get some processor time to use the program sitting on your website.

Its been pretty cool learning how to get programs talking over the web, and I am excited to make my own socket server and see it talk with my browser!

Friday, February 12, 2010

Day 28

So I first must apologize for not blogging on Thursday. I know day 26 says Thursday, but that was actually done Wednesday night, and then I fell asleep before I submitted, so I submitted it right when I woke up. Thursday I was still trapped in Philadelphia, and Micah spent the whole morning trying to find a flight home. I was feeling under weather, and we were riding a roller coaster, trying time and time again to get on a flight. Finally after a few attempts, we made it to the airport for a flight that had not yet been canceled. We then had a very anti climatic sprint to get to our gate, only to find out that we had to wait another hour and a half for the airline to find another flight attendant. I didn't get home until around 6:00 and we had lost an hour from the flight, so the day was quite unproductive, other than the fact that we made it home.

Today, I had hoped to make up for the lack of work completed on Thursday, unfortunately today was manual labor day. There were several tasks that needed to be done at the office, and being the apprentice - I was put to work. I literally got about 5 lines of code down today. On a more lightening note, one side of the office looks radically different now!
First I had to assemble 4 new chairs, which was actually a fairly painless process.
Then came a broken toilet that needed fixing. A relatively quick trip to ACE and a little tweaking to get the flush mechanism operating at its full potential. And let me tell you, there are under par flush handles and there are excellent flush handles. My first go at it, Micah was disappointed at the give of the handle and that it required so much motion before the flushing actually began. On my second go at it, I successfully measured the exact give to action ratio to create a handle that is both satisfyingly smooth in its motion as well as efficient in its reaction to the toilet's depositor.

After the toilet came the real task. This was actually after I had ordered lunch for everyone, though I might add that I failed in this endeavor because I forgot we had a vegetarian in the office. Fortunately, the pizza place had failed to deliver on my failed request, and thus two wrong made a right and there was no meat on the pizza. Unfortunately, this was discovered after Colin (he who prefers the veggies over the remains of a carcass) had already compensated for my thoughtlessness and created a delightful Peanut Butter, Pretzel, Banana, and Jelly sandwich on Rye bread.

So my real task came after this lunch, just as I thought I might be able to get some coding done, when some guys brought in 4 brand new tables that needed assembly. Not just the IKEA - stick some pre-made pegs in pre-drilled holes. No, these were big, heavy, and highly demanding tables which give you no assistance on assembly. As if tables can give you assistance... but either way, these were beastly projects. Each had four legs with a base that had 8 screws which had to be positioned after first measuring the proper distances from each side. Before the screws could be placed, I had to drill little holes to guide the screws in properly. So in total, each table required about 12 measurements, 16 pencil markings, 32 holes drilled, 32 screws screwed in the guided holes, and then finally 4 legs to be screwed onto their respective base paltes. I tried making a measurement template after the first table (as Doug suggested), but we had no paper large enough to span the table and the cardboard template I tried was too small and too inaccurate.

What made it all far... far worse, was the electric drill ran out of battery before even the first table was completed. As a result, the majority of the screws were placed in by hand through a variety of combinations of unintended uses for tools. If you never have screwed in thick screws into fairly hardwood... it isn't an easy task. I am a fairly strong fellow, and even using my full body weight, sometimes I couldn't get the screws to budge. Thank goodness for mechanical advantage!

I am happy to say, that even though I was sweating at the job for a very long time, I defeated Doug's expectations that I would still be there when he returned on Monday! Take that Mr. IOnlyUsePoweredDrills ( go java CamelCase) !! No offense intended of course, its actually a reflection of frustration for 8th Light owning a battery powered drill with no backup battery.

This weekend I will makeup for all the lost time these last two days, and then start on my new assignment of creating an HTTP Server from scratch.

Thursday, February 11, 2010

Day 26

"Do not try to bend the spoon. That's impossible. Instead... only try to realize the truth. There is no spoon. Then you'll see, that it is not the spoon that bends, it is only yourself."

I wanted to place that quote at the end, but it seemed like such a fitting introduction that it belonged at the start.

Making massive changes to your code, without changing a single line.

Often you will find yourself working on a project, when an unexpected requirement pops up and seems to demand that you perform a complete redesign or restructuring of your code. You might then find you have no idea where to start or how to proceed. You look around for awhile, testing out small changes in various places, but never getting the feel that you are going in the right direction. Finally, you stumble across an area that looks important, so you make a change that seems logical, watch as your tests fail in the way you expect, and then proceed to change your tests to fit a new criterion. However, once you get to your tests you realize that they are actually testing exactly what you had wanted them to! These tests, which are at the center of your massive overhaul, are properly testing both your old system and your new system... but you know that this is supposed to be a big change! What's going on?

This exact thing happened to me the other day. I had developed a system for weeks, carefully designing each facet, and it was almost just the way I wanted it. Then I suddenly discovered there was a fundamental change that was needed to fulfill a requirement. Not knowing where to start, I began to fiddle around in a variety of places trying to get a foothold on what I needed to do. Finally, I made a change to the code, saw a test fail, then changed the test... but the change didn't feel right. I made the change anyway, and observed the green flash before me once again. It was at that point that I realized this was all wrong. I realized that I wasn't trying to change the code at all, I was just trying to change what it meant. The massive overhaul and fundamental change that needed to occur was in my mind.

After the fact, it seemed rather obvious, but I got trapped into thinking- since my code only did one thing, it could only mean one thing. This, of course, was not the case. I was making a change that would affect every part of my system, but would change none of the functionality, just the interpretation.

I found a few signals that indicate when the change is in the theme and not in the scheme.
The biggest is that you have no idea where to make a change. You designed this system from the start and you know it inside and out, yet you can't seem to find what you need to tweak to get started on this big change.
Another is that the tests are yelling at you for trying to change them. You seem to think you know what to change, but when you make the according change to the tests it feels completely wrong. The tests seem to fight the change.
The last big one I can think of is you can't completely understand what this change means in terms of your code. You know what it should allow you to do, but you don't quite understand the new mind set you are supposed to settle into.

These three things likely indicate that either your system is already the way it is meant to be and you just need to figure out why, or that your system sucks and you should rewrite it all. It could also mean that your original problem is far more complicated that you first anticipated, but if thats the case your tests are probably screaming at you because they unsatisfied or just plain wrong.

Basically, try to remember to 'Free your mind'

Tuesday, February 9, 2010

Day 25

It appears I will be trapped in Philadelphia until Friday because of severe weather conditions! It is supposed to snow 10-15 inches tonight, so tonight we all went and stocked up on groceries and supplies.

Anyway, today I was got to sit in on a very engaging and enlightening meeting with a new client of 8th Light's. Micah, Paul, Craig, and I were introduced to this companies exec board, who then sat down with us and described their dilemma. They had a huge amount of data, but they had to use other companies to access it. Some of the data was collected through one of their websites, which was created and hosted by a company they hired, and as such they had to go through this company to get any of their data. There is also a huge data bank which they do not own, but have a license to use; yet they still had been going through a third party to gain access to this data.

The gist of it is that they wanted all this data under one roof. Our client knew the power of this knowledge, and they wanted to hold it and completely own it. So 8th Light's job would be to create a system that could store and interact with this data, after merging a huge amount of data in from several sources.

From an apprentice stand point, this was a gold mine to observe. I got to meet some very ambitious and driven people, who couldn't help but think big. I got to see the manner in which a Craftsman might respond to the requests and dreams of enthusiastic clients, and it was always in the affirmative. And I also got to see the outlining of a project from nothing to something very achievable.

First the client described their debacle, and then we would ask chains of questions to get a deeper understanding so that we could formulate possible solutions. Then the client explained what they were looking for, and what they imagined their system would do, and once again we asked questions to contemplate how we might implement this system. Next, Micah and Paul began outlining what it meant to use the Agile process, or to work in short iterations with rigorous customer interaction and frequent releases. We proceeded to define several Epics, or big chunks of functionality that the client thought were crucial. Once these Epic had been ordered, or at least once we knew which one had to be first, we then broke the Epic into Stories and estimated. Finally, we showed them the stories with the estimates, and gave them an idea of how soon we could get them the functionality they desired.

All in all a very educational experience. I now have an understanding of how to began a project from scratch, and how to lead the customer along your chain of thought. I am also remarkably exhausted from waking up extremely early and getting a mere hour of sleep. must collapse... arrrgggghhh... ZZzzzz

Monday, February 8, 2010

Day 24

So while driving home from work today, I drove by a house which left their garage door open. They had left their car out in the snow because their garage was so overwhelmingly packed with stuff that they no longer had room for their car. When I saw this, the two things came to mind. The first was my Grandma, who is the type of person who could never throw anything away, and as a result has no room in her garage. The second was what a program would look like if she had written it.

Often I, and many other developers I know, have the temptation to comment out some code and keep it around just in case it might come in handy later. This happens quite often when you are spiking, or when (and god knows why) you are not using version control. You write a tid-bit of code, find a better way to rewrite the code, but save the old code just in case your new idea fails. Do this over and over, and things can get pretty ugly.

I recently wrote some C and X86 assembly to write an operating system for one of my classes. My group and I really had no idea how to start going about writing our OS, so quite frequently we would save old code we had written so that we wouldn't have to reinvent the wheel. As a result, in some files we had to doing some hunting just to find the real production code through the haze of the comments. This is a Dirty Garage.

Uncle Bob uses the metaphor of a Dirty Kitchen for poorly written code. If you are a chef working at a restaurant on a very busy night, and rather than cleaning up pans or knives after every use, you instead just toss the dirty ones aside and grab the nearest clean on. At first, you will be able to get a bunch of dinners out quite rapidly, since you waste no time cleaning anything; however, as the night progresses you will find it more and more difficult to get any clean pans and eventually you virtually stop cooking all together and spend most of your time hunting down clean tools. The same thing is true with software. If you rush to get a lot done really quickly, and you push off keeping your code clean, then eventually you will hit a point where you are spending more time trying to figure out what is going on instead of developing.

If my Grandma were to write a program, I imagine that it would be so densely packed with commented and saved code, that unveiling any functionality would be quite a challenge. This is a Dirty Garage. Where you have so much saved junk in your files that you no longer have any room for that which is meant to occupy your production files, your functioning code. Where you fear deleting code because you think it might be useful again in the future. Sometimes this can be true, and if you are just messing around and trying to refactor, often commenting out code for later or for reference can be valuable. Often though, you will comment out a block, forget about it, and it will linger and rot your code. Perhaps you hand your project off to another developer who is too afraid to delete the commented code because he/she thinks it might have some unspoken value.

Although a Dirty Kitchen can be more harmful than a Dirty Garage... no one wants to park their car in a garage full of junk.