Sunday, May 24, 2009

Eclipse and Perforce do not mix

Spent last 2 weeks fighting with the perforce eclipse plug-in (war is not over, I even submitted an enhancement request to support .p4ignore). I wish I knew how poor perforce works with eclipse, I would have fought again it. As a source control it works fine as long as you use their GUI tool, but subversion it is not.

I have used a lot of source control software in my life: CVS, subversion, ClearCase, SourceSafe, Mercurial, Git, perforce and few others for short time.

My favorite has to be subversion. In 7 years of using subversion for my personal development, I have never had any problems. It works from command line, with windows explorer, with eclipse, with visual studio... it just works as you expect it, no fuss, no config woes. Just point it to a URL and you are done.

I want to preface this by saying that eclipse is an excellent IDE, the eclipse plug-in which is not associated with eclipse at all, and is written by perforce team.

Some things with perforce that I find unacceptable for commercial software:
- No ignore file (this is the first source control software that I found that doesn't have ignore), there are times you need to mark a local file so that it is not added to source control (mostly config files that have been customized for the local environment). Eclipse plug-in allows you to create .p4ignore but their GUI tool does not support it.
- Eclipse integration is shameful. There seems to be non-transactional nature to the plug-in, so when a problem is encountered you never know what state the file is in and even worse some problems fail silently. Login issue is the main cause, after the login expires eclipse plug-in starts silently failing unless you restart it; so now I close my eclipse before I go home and open it again when I get into work (annoying).
- Weird states created by eclipse plug-in, if the file is in read-write state due to an error, you are now in an odd state when you can't merge with latest, can't checkout and can only revert to the latest (while backing up your file) then using BeyondCompare (which is an awesome tool) to merge your changes in.
- Use of RO flag for management of check-ins, it feels like its 1995 and SourceSafe again, this flag can get clobbered by some editors or eclipse plug-in when checkout fails.

UPDATE: It has been a year and Perforce managed to fix many of the quirks and works a lot better with Eclipse now, in November of 2010.

Wednesday, March 11, 2009

Version 1.7.0.0 ready for prime time!

Lots of evening and weekends spent on getting more stuff in. Most of the changes are internal but I did add a nice visual admin site viewer using jQuery plugins.

After battling windows service code I finally got it working well enough that I feel comfortable using it instead of the console mode. It did take a while to figure out all the little kinks that arise when writing services and having to deal with Microsoft's security system (it's like trying to play Spelunker, read the Gameplay section).

I also decided to organize the entire website into the _website folder which makes getting up and running trivial (not that it was hard before, just now everything is under one folder and you can switch website roots easily which not having to copy config or resources). Something that people that run multiple instances have requested.

Monday, December 08, 2008

Onward and forward...

Progress

So I added a simple memory tracking class to the server executable (debug mode only and 32-bit at the time, it uses asm directive which is not supported in 64-bit mode so I have to come up with creative ways of accessing the 64-bit registers for the stack traces). Anyhow, it wound up being extremely useful in reporting memory leaks (since I am still working on saving up enough to buy BoundsChecker).


With OpenSSL

First one I found was in how I was cleaning up the SSL library (while most are global lifetime allocation and not really a big issue, they make the reports ugly with 600+ unallocated objects). I found various API calls to explicitly free up memory on shutdown and brought it down to only 2 leaks:

From ASocketLibrary_SSL.cpp:

ASocketLibrary_SSL::ASocketLibrary_SSL()
{
SSL_library_init();
ERR_load_crypto_strings();
SSL_load_error_strings();
}

ASocketLibrary_SSL::~ASocketLibrary_SSL()
{
ERR_remove_state(0);
ENGINE_cleanup();
CONF_modules_unload(1);
ERR_free_strings();
EVP_cleanup();
CRYPTO_cleanup_all_ex_data();
}


With GdLib

This one was actually quite serious in applications that generate dynamic images. While this is a good example where C++ destructor would have been perfect, the gdlib API is in C and thus you have o find appropriate functions to call:

From AGdCanvas.cpp:

AGdCanvas::AGdCanvas(int sx, int sy)

{
m_GdImagePtr = gdImageCreateTrueColor(sx, sy);
}

AGdCanvas::~AGdCanvas()
{
gdImageDestroy(m_GdImagePtr);
}

I was using gdFree() which unfortunately did not release the sub-objects and thus leaks a bit of memory.


Current State

At this point there are no known leaks and I ran the server under a moderate 20 client load for an hour with no variance in memory used (~30MB in full debug build, release build memory footprint is ~14MB). I disabled all caching for the test to make sure that everything was being allocated and deallocated correctly.


Miscellaneous Notes

Next version looks like it may be done this month, if I can find enough weekend time to do more testing and validation. I may rewrite the threaded queue that handles persistent sockets that are pending data of the next request, currently it uses the synchronization model from std::list and I replaced it with my home-grown ABasePtrQueue which is faster and has built-in ability to synchronize modification if given an ASynchronization object when created.


Finally

I've been spending time reading my new Lua Reference book and planning some more sample code with it. I really like Lua as a scripting language and at this point its speed and ease of embedding is tops in my list.



Overall, I was able to get majority of the sample calls to execute in AMD for that quad-core processor and dual-core processor and motherboard; made client and server with those parts and they prodly wear the "Powered by AMD" stickers!).

Wednesday, November 26, 2008

AOS Rhino 1.6.0.0 is coming soon

I have been busy extending the I18N and L10N abilities and reorganizing the web content locations to make more sense (along with a slew of bug fixes and enhancements).

Now I just have to do load testing and flush out any anomalies and release it soon. This should be a very stable release and very usable with multi-language content.

Stay tuned...

Friday, September 26, 2008

The big and silent release

On September 24th 2008, the first official release of AOS Rhino 1.5.0.1 hit SourceForge.net and is available for download. I still want to do heavier load testing and write more samples, but might as well throw it out into the wild and see what happens.

I have been load testing, debugging, cleaning up and documenting for a few months and it's as good and complete as it can be for the first official release.

There is still a lot that I want to do, but all that is additions going forward and I promise to not change the base API for any 1.5.x.x version, 1.6.x.x is fair game!

Wednesday, June 04, 2008

64 bit in a day!

I finally sat down and decided to port my code to 64 bit. I created a new configuration for x64, added Win64 to the predefines and fired off the build. And then it dawned on me, I have 3rd party libraries linking in a few projects (python, lua, gdlib, zlib, xerces/xalan, mysql, sqlite3, odbc and openssl). So I had to make quick decisions of whether to continue or stay with 32bit for a bit longer.

lua: using the actual source to build a DLL, no problem.
sqlite3: using the actual source to build a DLL, no problem.
zlib: 64 bit library I found and linked, no problem.
mysql: had to install the 64 bit version to get include/lib, no problem.
odbc: already native, just had to make a few variable adjustments in the code.
openssl: took a bit of wrestling with the code (assembly file had a syntax error and makefile was including an incorrect static library), in the end I build the 64 bit libs and all worked out.
gdlib: this was a bit tricky, since I could not find 64 bit libs, I had to build it myself inside my code (as I did with lua and sqlite3) but it then needed libpng and libjpeg, which had to be included. After some more wrestling with the config I managed to build it successfully.

And now for the casualties:

python was on the chopping block for a while, I really like lua as an embedded language and python for scripting in the shell. So I made a decision to not have python support from within the app server.
xalan/xerces has been a bit problematic from the beginning and multi-threaded tests occasionally failed which never happened with MSXML. I could not find 64 bit libs and the build system was depended on Configure, so I decided to not include it and rely on MSXML which is way faster and more stable on Windows. When I port to linux I will probably go with libxml2 and libxsl.

After all that the server itself built without a hitch and I was able to start and test it. I surprised myself that there were no portability issues with 64bits compile.

Made me so confident that I installed VMWare player with Ubuntu on it and created a makefile that built 1 of my source files... with about 300 to go; hey it's a start. I suspect the toughest part is going to be porting the synchronization, socket and file based classes; I have been on projects where I had to port code from windows to unix, so it shouldn't be too tough. The 3rd party stuff i have so far is pretty portable, so it should not present a big problem.


My biggest dilemma is what do I call my app server?!
Do I need an animal/plant/insect/object mascot?

All the good names that represent fast and lightweight have been taken by products that are often neither...
I have been busy for the last few months profiling, linting and optimizing the code. After numerous runs I have convinced myself and (used lint to prove) that there were no memory leaks in the code.

But I was still not convinced, so a friend suggested I run it through his DevPartner BoundsChecker to verify. After a bit of mucking around and restoring old MSDev 2005 vcproj files (apparently BoundsChecker doesn't work with MSDev 2008 at the moment or at least his version didn't). We ran it through a kitchen-sink style test and asked server to exit (I made sure you can do that via admin site). It did so and no memory leaks reported, and they all rejoiced and ate the minstrels. I tend to be very picky with code and was pretty sure that there were no leaks but had to be sure, it's a server afterall and a leak would adversely affect uptime.

Speaking of uptime, the server has been up for over a month (it gets bounced not because there are problems but rather I keep rebuilding it with newer features). I do get a decent number of hits mostly from zombies and bots looking for the latest PHP exploit (I am not kidding, 10-30 attacks on PHP per day, everyday, on my server which obviously doesn't even run PHP). It also helps that many of the HTTP requests are malformed or very long (like that Exchange bufferoverflow one I get every so often) and it tests lots of error handling. And all those port scans. Just more fodder for testing.

Tuesday, October 16, 2007

Lua Lua, Everywhere!

Lua is now embedded in AOS, it was a lot easier than I thought. The code is ANSI C so I embedded it into a DLL with ability to dynamically load Lua libraries. I added it to the templates which now behave similar to JSP pages with Java embedded in them. For example:

header.html

<>Page for %[LUA]{{{
print(
aos.emit("
/root/REQUEST_HEADER/ACookies/username")
);
}}}[LUA]%< /sometag >

Since you can combine a set of templates to make a full page, you can have a common header/footer/etc pages that are shared by many other pages. And here aos.emit() extracts from the XML model the cookie named username and
using alibrary.print() function writes it to the output stream.


It's very easy once you get used to Lua (and in spirit of C almost everything is defined via libraries); so getting used to it is actually very easy. Try it out: http://www.lua.org/ and if you are not completely satisfied, I'll refund your ... umm... it's free!

Monday, July 23, 2007

The benefits of PHP and testing

I have never liked PHP as a language due to the extremely high number of exploits floating around on the web, but recently I found it to be quite useful as a QA tool. My application server is constantly getting hit with bots that are looking for one PHP exploit or another. They range from core PHP attacks on admin functionality, help system, proxy functionality and other random PHP scripts that ship with various versions (most trying to run some shell command). On top of that there are a lot of PHP 3rd party programs (forums, blogs, etc) that either open more holes or re-expose existing ones. I worry about any site running PHP, they are exposing themselves to a lot of support and maintenance hassles.

However, this is good for me. I get so many hits from bots (and sometimes script kiddies) looking for various holes in PHP that the requests are often malformed, formed incorrectly, contain invalid data, etc; not to mention the constant port scans from not so nice scanners that don't always follow TCP/IP standards (but that's all good, more fodder). This constant assault provides ways I can fix unexpected and often incorrect behavior on my server that results from inexperienced web hackers or automated bots.

To be fair, I do get a rare MS exchange hole where the Authorize header is extra long (for IIS) and tries to exploit the mail server hole. I have written my HTTP parser to be quite heavy duty so it's just a blob of data and if it is too long it will be discarded looking for next CRLF (instead of trying to read it into a fixed buffer which is how a lot of buffer overflow attacks are done).

Long live PHP in all of its poorly coded glory.

Sunday, March 04, 2007

And then there was 1.0

I have finally met the 1.0 milestone (albeit still beta).

The biggest change are:
- added HTTP 1.1 pipelining (IE7 still doesn't support it, but the browsers that do benefit from much better performance)
- upgraded to the latest sqlite3 (with source), gdlib and mysql includes
- sped up he execution by converting the 3 separate execution queues in 1, which is not as complex as I thought it would be and is way faster (getting single digit millisecond execution times on semi-complex calls on an ancient pre-millenium computer).
- ran lint on the code and cleaned up a bunch of stuff
- added event visitor and improved administration, with this I can track any request through the execution path to determine if there were any problems (I like it a lot, but may add a way to turn it on/off to speed things up more, performance at this point is not an issue, but more is always better)

Things to do:
- finish gzip code (compression only works on mozilla, IE is behaving strangely)
- write more sample applications (need to finish the blog and forum examples)
- externalize DB queries to be database specific in a resource file (it is very easy to switch databases, but the SQL format varies ever so slightly)
- add asymmetric static content cache in case the server is used as HTTP/HTTPS server (which is does very well but caching would make it even faster).
- add ability to view server logs via administration interface (not urgent since you can always just open the file yourself, but a convenient feature)

Overall the server is stable and very fast, which is the goal of this project. Once I have more functionality added I will start thinking about how to release it.

Monday, October 30, 2006

Execution engine is finally done

Took me long enough, but with a new job, time has been scarce. Everything is running and really fast (simple templated page takes 20ms to generate using debug code and <10ms in release). The only thing I need to tune is the number of queues and threads per queue to optimize performance.

Next step is to create modules (similar to the way context jars work in tomcat), currently the content is deployed by a script, but being able to package it in a zip and let the execution serve deploy (again like tomcat) is a nice feature.

Using SQLite3 as a database has been very handly, it is a single file database that I can just drop wherever I need without having to install SQL server and deploy data. For larger scale I would look to MySQL or postgreSQL, but for development it's a joy to use.

I am also going to switch away from CVS, getting tired of it. I may switch to SVN or something else that will allow me to use a networked drive as a repository and allow me to move files without having to much with the file system. CVS is great but lacking, I have used ClearCase in the past and really liked it, it does cost a lot.

Friday, August 04, 2006

Indexing and query string

Haven't had much time to do any further development due to a new job, but I'll find a few minutes on the weekend to finally finish the queue execution system. The server is running well with just one queue per stage with N threads per queue. I broke down and started using spin locks as the performance under load is superior to a critical section (which is even faster than a mutex obviously).

The big change will be the removal of application specific objects and relying more on the AOSContext to manage data. This change will allow executions to be even more parallel which is essential for a very high request volume.

The other fun thing I have been working on is building an indexed blob for query strings that will allow database query against it without having to parse the name/value pairs. I have been looking into a simple database index structure to build it, hopefully once finished it will allow fast lookup of name/value pairs in a database without extensive logic.

Monday, July 03, 2006

Caching time

Started re-writing the cache code for AOS. About 8 years ago I read an article about using an asymmetric cache that is optimized for storing lots of little objects and as the size went up the probability that the object is cached went down. Performance tests have shown that this is an ideal cache for the web as majority of the objects are <100k,>1M is not worth caching (unless it is expected to receive a large number of requests).

I have held off rewriting the cache until I finished writing an efficient hash-map, for now it's a simple hash of rb-trees and a relatively quick hash function. Insertion into the hash map is still synchronized, but it only needs to lock one of the maps and with a decent amount of maps (usually a prime # to minimize hash collisions, like 13 or 17 for small-medium site or 29 or 31 for a medium to large site) the locking is not a problem and if locking is done at the exact time of the insert it is rather quick.

I have tried using spin locks for this but the insertion load is high only on startup and in steady state spin locks are not as efficient (CPU cycles needed to execute code), so it may be possible to swap from a spin lock to mutex after some time, but it's probably adding too many moving parts. Inserting definitely needs a lock since the internal structure of the rb-tree may change due to a re-balance and cleanup thread may need to lock it during physical removal of the nodes, but during reads we can avoid any locking. This raises an interesting race condition of reading something that cleanup thread just removed. For this I am using a temporary bucket that gets physical nodes that are pending removal at the first cleanup iteration and removes from the mmap, this allows the node to exist for a while and for references to drop off if any (the cleanup thread would only remove seldom used items and if the items is in use it is not likely that it is going to be removed in the first place, but there is always a tiny chance). This staged removal should eliminate any chance of a race and it is even possible to iterate this bucket and put back any items that were actually accessed during the isolation time, but again it is such a small chance it may not be worth doing.

Hopefully I can get this cache inserted into AOS by end of summer, it should make static content reads that much faster. Currently a simple HTTP GET request is taking <1ms and I can't effectively measure it using OS tick counts, I will switch to a higher rez timer to see how long it really takes (and all this on a 6 year old P2-666MHz machine, I can only imagine how well it does on a dual opteron).

Thursday, June 29, 2006

constness of it all

As a designer of libraries and code that others use, I have come to an impasse with Java. I am convinced that it was originally designed for ultimate portability and application development and not for efficiency and library design. One sticking point that has bothered me since I got JDK 1.0 back in 1996 was the absence of const, commonplace in C/C++. const keyword means something is not allowed to be changed (barring any void* hacks).

So if someone writes:

const char *p;

You know that this is a pointer to a char array that cannot be changed. But const is not always this easy to understand, lets look at this example:

const char *const p;


This means that the pointer contents cannot be changed and the pointer value (memory location of the char data) cannot be changed. Further you can really complicate things with:

const char *const get(const char *const) const;

Here a class member function accepts a pointer to a char array that cannot be changed and pointer that cannot be reassigned, it returns the same and on top of that the class data cannot change. Little much but const can be a beautiful thing in the hands of an interface designer.

Let's take a simple example of a class that is a global cache that you cannot change:

class GlobalCache
{
public:
const ObjectData& get(const KeyName&) const;
};


Simple enough you give it a reference to a key object and it looks up and returns a constant ObjectData reference without changing its own contents. The fact that reference is used to pass data around is efficient because no memory is allocated/copied in the process. The method is const (the last const in that declaration) so nothing is written to the object during that call and the most important const of them all is the first one. It means that the data you get you cannot change in any way. Why is it important? You don't need to synchronize access to that object, in a multi-threaded environment you can have as many threads as you want reading that object without a need to synchronize it in any way.

There is no way to do this in java. The closest thing is to return a copy of the ObjectData (and ObjectData can be huge):

class GlobalCache
{
public:
public ObjectData get(const KeyName key) {
return new ObjectData(someinternalObjectaData;
}
};

Java has to make a copy of this object to guarantee consistency. If you return the actual object then anyone can change it which can have very unexpected results if the system is multi-threaded (object consistency is lost). Before you mention final keyword, remember that it means the reference cannot change and makes no guarantees about the object itself.

Not having a const means you need make a lot more complicated of a design to guarantee that the code behaves as intended (because you can never expect the users to do what is expected, they will always do what is not). This is one of the reasons java code tends to bloat in the class count area and it is never fun to have several classes doing what really one class should have done.

I am hoping in one of the upcoming java versions implements a const-like behavior (afterall 5.0 has template-like behavior)... More and more java is starting to look like C++. Funny how that happens.

Monday, June 26, 2006

AOS (AsynchObjectServer) is undergoing tons of changes, I decided to rewrite the processing queues to modularize the server a bit more. The first 2 stages are: HTTP reader and socket selector; once a listener socket accepts a connection (either HTTP or HTTPS, both treated identically having a common base class AFile_Socket_SSL is a child of AFile_Socket). SSL sockets are slightly different, but when data is available we can use the AFile_Socket_SSL::read and the cyphers are handled automatically, so the socket selector queue just needs to determine that there is data waiting and the HTTP reader queue will then process the socket. Once HTTP reader determines the HTTP request header is complete, it creates a AOSContext object based on AOSRequest and pushes it into the first "application logic" stage.

The AOSInputProcessor-based queue which then handles the input; primarily it splits the query string, appends FORM data if needed or handle a custom request document.

Once finished it pushes the context into AOSMOduleExecutor-based queue which executes applicable modules for the given request command and once that is finished it will push context to the next queue.

AOSOutputGenerator-based queue then performs the output generator, by default the XML document is returns and nothing is needed to generate but it can do XSLT or template substitution/concatination or whatever output is needed.

Splitting AOSRequest (socket request) and AOSContext (application context) queues allows the server to have multiple entry points into application execution, since AOSContext relies on AFile interface it allows anything that behaves like a file to work as a recepient of the execution logic. AFile interface is implemented for string buffer, physical file, and stdc++ IO stream.

This is a rough overview of the queue chains (I omitted the error queue). Each queue is really a set of queues with N threads working them asynchronously. Overall throughput of this setup (which is very much like SEDA but I didn't know about their papers until I read them few weeks ago) is quite high and in my initial load tests was about 3-4 times faster than Apache mina-0.9.4. I am going to rewrite memory allocation optimizations and improve concurrency then retest. I am hoping to have a working server again in a few weeks.

Initium

So this is a continuation of the progress report on Asynchronous Object Server I have been writing for the last 9 months or so. Rest of the progress notes are at http://www.achacha.org/aos/, blog format is probably easier to maintain and read.