Showing posts with label S3. Show all posts
Showing posts with label S3. Show all posts

Tuesday, January 10, 2012

Since when has consistency not been eventual?

Database isn't really my area.

But you don't have to be a database expert to understand what those folks mean when they use the acronym ACID (Reuter and Härder, 1983) that states for every database transaction:

Atomicity: either all or none of its changes are made;
Consistency: before and after, the database is in a consistent state;
Isolation: it either succeeds or fails regardless of concurrent transactions;
Durability: once it succeeds, its changes are persistent.

These requirements of database transactions are necessary to make sure, for example, that when you make a withdrawal from your bank account, the money you had yesterday is still there. Real-time guys like me get this because underneath the hood the database systems uses the same or similar synchronization primitives as those on which we depend on a daily basis to make sure planes keep flying and telephones keep ringing. For those readers not into this stuff, a lot of the synchronization mechanisms amount to a bank teller saying to the next guy in line "I'll be with you in a moment once I'm finished with this customer", except it has to be implemented all the way down to the lowest level of the hardware.

This was challenging enough when databases were hosted on single servers so large they frequently needed multiple processors to keep up with the workload. But when databases got so huge that they had to be distributed across multiple servers on a network, satisfying ACID suddenly got really hard. Brewer's Theorem (Brewer, 2000) and its more narrowly but formally defined cousin the CAP Theorem (Gilbert and Lynch, 2002), states that a distributed system can deliver at most two of the following three qualities:

Consistency: each server sees the same data at the same time;
Availability: each request gets a response, success or failure;
Partition tolerance: the system continues to run even when the network fails.

The need for availability and partition tolerance is especially compelling given that the network is basically unreliable. In fact, this assumption is at the very core of the initial design of what today we think of as the Internet, which started life out as a network for military communication in the face of a nuclear war. Network traffic would be briefly interrupted as cities were vaporized by megaton Soviet warheads and packets were routed around the flaming craters. Armageddon turns out to have been a good model for other catastrophic failures too, like someone accidentally powering down an equipment rack or inadvertently cutting a fiber optic cable with a back hoe.

Designers of software for distributed systems have to take this basic assumption of unreliability into account. It is in fact the first of the eight Fallacies of Distributed Computing (Deutsch 1994, Gosling 1997, et al.):

1. The network is reliable.
2. Latency is zero.
3. Bandwidth is infinite.
4. The network is secure.
5. Topology doesn't change.
6. There is one administrator.
7. Transport cost is zero.
8. The network is homogeneous.

For e-commerce giants like Amazon.com, it became a lot more important to tolerate some inconsistency issues than it was to have a system that didn't respond when I hit the Buy now with 1-Click button. (Which I do. All too often. 1-Click ordering is the bane of my credit card.) Sure, sometimes you can order something that is actually out of stock. Or order something twice. But those kinds of consistency errors are infrequent, and when they do occur, they can be detected and cleaned up after the fact. The same approach has been adopted by many cloud computing architectures for the same reason: it's the only way to build scalable systems, because scalability requires distribution.

Amazon.com coined their architectural willingness to incur some inconsistency as eventual consistency (Vogels, 2008), but the database folks adopted as the alternative to ACID the punnish acronym BASE (Pritchett, 2008):

Basically: more or less
Available: reliable
Soft state: with some inconsistencies here and there
Eventual consistency: that we'll fix later.

This approach allows, for example, Amazon.com to spread their Amazon Web Services (AWS) infrastructure across thousands of individual servers in a network that is distributed internationally. I've mentioned before that in testing Hayloft, my C++ interface to Amazon Simple Storage Service (S3), I not only could see the effects on my subsequent transactions of S3 updating its bicoastal server farm in the United States to take into account my prior transactions, but I could see the increase in latency of those updates on Black Friday, the day after Thanksgiving in the U.S., which is typically the biggest day of the year for retail commerce here, e- or otherwise.

So here's the thing. Eventual consistency is not a new idea. Probably not to the database community, but certainly not to the community of developers I hang out with who write software for both small embedded and gigantic distributed systems. (Those are the same people.) Or at least it shouldn't be. Let me give you an example.

The biggest distributed system I ever worked on was a Private Branch eXchange (PBX). This system had several distributed redundant servers controlling up to sixty-four cabinets of hardware. Each cabinet had as many as five racks. Each rack had as many as a dozen or so boards. The most complex of these boards (which I happened to have worked on) had three microprocessor chips, twenty-four individual digital signal processor (DSP) chips, and several big field programmable gate array (FPGA) chips. At least one of the microprocessor chips had dozens of concurrent software threads running at all times. The main controlling server, which these days probably has multiple cores, also had dozens, if not hundreds, of parallel threads. A single PBX could (and did) span national boundaries. And each PBX typically communicated with other PBXes, with the public telephone network, and with other equally distributed systems.

All of this stuff routinely communicated via message passing, over a combination of backplane wiring, dedicated telecommunications circuits, and internet connections. Even the simplest board in this system had at least one chip on it capable of responding to a limited set of messages coming across the backplane. When you look at the big picture, that's a lot of processors all independently doing stuff, all at the same time.

So what the heck was all this stuff doing? For the most part, each element was doing what it was told to do, either by a message from the main controlling server, from another board in the system, or in the case of inter-PBX connections from another system entirely. But whatever it was doing, it took time to do it. A typical pattern was: take a message from the queue of incoming messages, inject the message into a state machine that determines what to do given the current circumstances, and execute the resulting action. Some of these actions might (and typically did) result in one or more messages being dispatched to other threads on the same board, or other boards in the same cabinet, or back to the controlling server, or even to a completely different PBX.

Remember those fallacies of distributed computing? Not only is the network not reliable, but latency is not zero, and bandwidth is not infinite. So it takes a while for those messages to arrive at their destinations. If they arrive at all. Only to be queued up at the receiving end, perhaps behind other messages. Maybe many other messages, all waiting for a thread to finish what it's currently doing and go back and receive them. Thanks to communications latency, queueing latency, and processing latency, it might be seconds between the time a state machine makes a decision, a message is dispatched, that message is received, and acted upon.

If you could somehow take an instantaneous snapshot of the entire, gigantic system, what you would see is dozens, hundreds, thousands of processors, each acting on a message that doesn't describe the current state of things at all, but instead the state of things a while ago. How long a while? It's different for every system, every processor, every application, every workload, every instant from one to the next. It's not just eventually consistent. It's more or less perpetually inconsistent. Why? Because it was the only way to build a scalable system.

Being slightly out of sync all the time can result in a kind of positive feedback loop, where two threads, each having a different idea of the current state of affairs, both of them possibly being wrong, keep telling one another to do the wrong thing. The good news is that if this isn't addressed, it frequently results in something fairly obvious, like a communications system serving thousands of people crashing. But it can also lead to much more subtle emergent behavior in which the system as a whole acts mysteriously non-deterministic.

Once you appreciate the magnitude of it, it's a little miracle anything works at all. I used the example of a PBX because that's the biggest distributed system I could think of that I've worked on. But a similar analysis applies to any large distributed architecture: Amazon Web Services, traffic light systems, air traffic control systems, automated stock exchanges, Strategic Air Command. All of these systems have always had their own mechanisms for dealing with their special brand of eventual consistency. Here's some mechanisms I've seen used.

Audits. An audit simply means fixing a consistency issue when you encounter it, either in real-time (what the distributed database people call read repair and write repair), or by having software specifically tasked to go and look for it (asynchronous repair). More than once I've received email from Amazon.com telling me that something I ordered was actually out of stock, or asking me to verify that I meant to order two of an item. These are all the results of audits. Big distributed systems like PBXes routinely have dozens of audits running, all the time, just to apply corrective action to achieve eventual consistency.

Out of Band Messaging, Priority Messaging. Not all messages are created equal. Some messages get to take the equivalent of the passing lane and jump ahead of all the other queued messages. This is either done by using a different communications path or by jumping the message ahead of all the others in the queue. Once a thread receives such a message, it still has to decide what to do with each of the stale messages behind it: throw it away, reply to it with failure, or even reply with success under the assumption of what the sender doesn't know won't hurt it. Sometimes the result of such a high priority message is for the receiver to exit, reset, or reboot.

Hysteresis, Feedback. For a lot of real-time processes, it makes sense to take your time when you are changing something visible to others. When you receive a message telling you that you can increase your bandwidth, don't jack up your bandwidth all at once. Instead, turn that tap slowly, injecting some hysteresis or delay into the process. This gives everyone downstream more time to adjust to your changes, and to complain about it if it doesn't work for them. If you get active feedback, if for example you are monitoring real-time error rates or you start getting flow control messages from your downstream neighbors, you can stop turning the tap.

Traffic Shaping, Traffic Policing, Flow Control. All of these are mechanisms for controlling the rate at which a thread may send or receive messages. For a lot of applications, real-time data has an expiration date, and it is better to just throw it away than to process it late. If a thread is told that a message it is about to send will arrive with an unusual amount of delay (we might say that the message exceeds the traffic contract between the sender and the receiver), the sender might choose to implement a different strategy or take corrective action.

This article is in some ways my love letter to real-time systems. I have known the joy of analyzing a post mortem hemorrhage of thousands of lines of log messages late at night so that I could tell a customer why their multi-million dollar system crashed. Of watching LEDs flash on a board from across a data center equipment room and suddenly wondering "WHAT THE F...!?!?!?!" Of staring at a diagnostic laptop as I watched a system servicing an entire building increment error counters towards MAXINT. When I first starting reading about eventual consistency I knew that it was something with which I was already familiar.

Even though database isn't really my area.

Monday, January 09, 2012

Managing Actions in Simple Storage Service with Hayloft

Hayloft provides a object oriented interface to the Amazon Web Services (AWS) Simple Storage Service (S3) in C++. When I started working on Hayloft, I had several goals. I'm wanted to learn something about cloud computing in general because I believe that's the direction everything is going and as someone else once said, "Amazon.com is the Coke of cloud computing, and there is no Pepsi". I wanted to learn something about S3 in particular because I have a background in mass storage systems and S3 might be the biggest one in the world. I wanted to write some software because I'm one of those people who can only learn by doing. I wanted to write it in C++ because I wanted to be able to use that software in small embedded systems and honking big distributed systems (turns out the skill sets are the same) where I've spent most of my career as a developer.

I didn't want to just slam out some code to talk to S3. I was interested in learning how to manage the individual operations, or what Hayloft refers to as an Action, with S3 using some of the patterns I've exploited in the past in the kinds of systems I've made a good living developing. I will show you some real, running code right from the Hayloft tarball (specifically in example.cpp) that will illustrate some of the different ways applications can use buckets and objects in S3 by integrating Hayloft. In S3 parlance, a bucket can be thought of as a web site with unique domain name, and an object is a flat file that a web browser can retrieve from that web site. Each of these examples will perform exactly the same sequence of S3 actions:

  • create BUCKET1 and BUCKET2 in S3;
  • put a local file unittest.txt into BUCKET1/OBJECT1 in S3;
  • copy BUCKET1/OBJECT1 to BUCKET2/OBJECT2 in S3;
  • get BUCKET2/OBJECT2 from S3 into a second temporary local file;
  • delete BUCKET1/OBJECT1 and BUCKET2/OBJECT2 in S3;
  • delete BUCKET1 and BUCKET2 in S3;
  • diff the first and second local files to verify they are the same.

Other than some surround to include some header files and set the some environmental variables so that Hayloft knows parameters like my access key ID and secret access key that Hayloft uses to authenticate my application to AWS, in the examples below I'm showing you all the running code that is in example.cpp.

The first example executes all actions synchronously. There is no need to start actions or wait for actions to complete. Each action is started in its C++ constructor, and the constructor blocks until that action completes. All processing is done in the calling thread.

const char * PATH = "unittest.txt";
Bucket BUCKET1("Synchronicity1");
Bucket BUCKET2("Synchronicity2");
Object OBJECT1("Synchronicity1.txt", BUCKET1);
Object OBJECT2("Synchronicity2.txt", BUCKET2);
PathInput input(PATH);
Octets length = size(PATH);
PathOutput output(OBJECT2.getKey());

BucketCreate bucketcreate1(BUCKET1);
BucketCreate bucketcreate2(BUCKET2);
if (!bucketcreate1.isSuccessful()) { break; }
if (!bucketcreate2.isSuccessful()) { break; }

ObjectPut objectput1(OBJECT1, input, length);
if (!objectput1.isSuccessful()) { break; }

ObjectCopy objectcopy(OBJECT1, OBJECT2);
if (!objectcopy.isSuccessful()) { break; }

ObjectGet objectget2(OBJECT2, output);
if (!objectget2.isSuccessful()) { break; }

ObjectDelete objectdelete1(OBJECT1);
ObjectDelete objectdelete2(OBJECT2);
if (!objectdelete1.isSuccessful()) { break; }
if (!objectdelete2.isSuccessful()) { break; }

BucketDelete bucketdelete1(BUCKET1);
BucketDelete bucketdelete2(BUCKET2);
if (!bucketdelete1.isSuccessful()) { break; }
if (!bucketdelete2.isSuccessful()) { break; }

std::string command = "diff ";
command += PATH;
command += " ";
command += OBJECT2.getKey();
if (std::system(command.c_str()) < 0) { break; }
if (::unlink(OBJECT2.getKey()) < 0) { break; }

There is no code here to recover from errors, although the extensive unit test suite for Hayloft, based on Google Test, includes examples of doing that using this paradigm. If you want to get started playing with S3 in C++ using Hayloft, this is the absolutely simplest way to do so. As with all the examples, local files are handled using Desperado input and output functors. The PathInput and PathOutput functors provide an abstract mechanism to read and write data from the local file system.

S3 actions can be managed by using a different C++ constructor that specifies a manager or what Hayloft generically refers to as a Plex. The simplest manager is Simplex, which is a bit of a cheat: it still uses the synchronous interface, but actions are not automatically started in the constructor. You must start each action explicitly, but when the start method returns, the action has completed. All actions are executed in the calling thread. I'll embolden the important differences between this and the prior example.

const char * PATH = "unittest.txt";
Bucket BUCKET1("Simplexity1");
Bucket BUCKET2("Simplexity2");
Object OBJECT1("Simplexity1.txt", BUCKET1);
Object OBJECT2("Simplexity2.txt", BUCKET2);
PathInput input(PATH);
Octets length = size(PATH);
PathOutput output(OBJECT2.getKey());
Simplex simplex;

BucketCreate bucketcreate1(BUCKET1, simplex);
BucketCreate bucketcreate2(BUCKET2, simplex);
bucketcreate1.start();
bucketcreate2.start();
if (!bucketcreate1.isSuccessful()) { break; }
if (!bucketcreate2.isSuccessful()) { break; }

ObjectPut objectput1(OBJECT1, simplex, input, length);
objectput1.start();
if (!objectput1.isSuccessful()) { break; }

ObjectCopy objectcopy(OBJECT1, OBJECT2, simplex);
objectcopy.start();
if (!objectcopy.isSuccessful()) { break; }

ObjectGet objectget2(OBJECT2, simplex, output);
objectget2.start();
if (!objectget2.isSuccessful()) { break; }

ObjectDelete objectdelete1(OBJECT1, simplex);
ObjectDelete objectdelete2(OBJECT2, simplex);
objectdelete1.start();
objectdelete2.start();
if (!objectdelete1.isSuccessful()) { break; }
if (!objectdelete2.isSuccessful()) { break; }

BucketDelete bucketdelete1(BUCKET1, simplex);
bucketdelete1.start();
BucketDelete bucketdelete2(BUCKET2, simplex);
bucketdelete2.start();
if (!bucketdelete1.isSuccessful()) { break; }
if (!bucketdelete2.isSuccessful()) { break; }

std::string command = "diff ";
command += PATH;
command += " ";
command += OBJECT2.getKey();
if (std::system(command.c_str()) < 0) { break; }
if (::unlink(OBJECT2.getKey()) < 0) { break; }

As before, there is no error recovery, although such recovery is important when using S3 or any other web or even internet based service. The most common errors will be failure to connect to the service. This can be due to connectivity problems at either end of the internet connection or indeed anywhere in between.

This next example uses a Multiplex to manage the actions. This will be the first example that uses the asynchronous interface. Because actions are executed asynchronously, multiple actions can use the same Multiplex and will be executed in parallel. Each action must be started, and the processing of each action must be explicitly driven. In this example, I'll use the Multiplex complete method that automatically drives any pending actions to completion. I'll show other approaches in subsequent examples.

const char * PATH = "unittest.txt";
Bucket BUCKET1("MultiplexityComplete1");
Bucket BUCKET2("MultiplexityComplete2");
Object OBJECT1("MultiplexityComplete1.txt", BUCKET1);
Object OBJECT2("MultiplexityComplete2.txt", BUCKET2);
PathInput input(PATH);
Octets length = size(PATH);
PathOutput output(OBJECT2.getKey());
Multiplex multiplex;

BucketCreate bucketcreate1(BUCKET1, multiplex);
BucketCreate bucketcreate2(BUCKET2, multiplex);
bucketcreate1.start();
bucketcreate2.start();
multiplex.complete();
if (!bucketcreate1.isSuccessful()) { break; }
if (!bucketcreate2.isSuccessful()) { break; }

ObjectPut objectput1(OBJECT1, multiplex, input, length);
objectput1.start();
multiplex.complete();
if (!objectput1.isSuccessful()) { break; }

ObjectCopy objectcopy(OBJECT1, OBJECT2, multiplex);
objectcopy.start();
multiplex.complete();
if (!objectcopy.isSuccessful()) { break; }

ObjectGet objectget2(OBJECT2, multiplex, output);
objectget2.start();
multiplex.complete();
if (!objectget2.isSuccessful()) { break; }

ObjectDelete objectdelete1(OBJECT1, multiplex);
ObjectDelete objectdelete2(OBJECT2, multiplex);
objectdelete1.start();
objectdelete2.start();
multiplex.complete();
if (!objectdelete1.isSuccessful()) { break; }
if (!objectdelete2.isSuccessful()) { break; }

BucketDelete bucketdelete1(BUCKET1, multiplex);
bucketdelete1.start();
BucketDelete bucketdelete2(BUCKET2, multiplex);
bucketdelete2.start();
multiplex.complete();
if (!bucketdelete1.isSuccessful()) { break; }
if (!bucketdelete2.isSuccessful()) { break; }

std::string command = "diff ";
command += PATH;
command += " ";
command += OBJECT2.getKey();
if (std::system(command.c_str()) < 0) { break; }
if (::unlink(OBJECT2.getKey()) < 0) { break; }

This approach is useful for testing, but in practice there isn't a huge advantage between it and the prior example other than the ability to run some actions in parallel, which this example does.

This next example uses Multiplex, but uses its service method to incrementally drive the underlying state machines to completion.

const char * PATH = "unittest.txt";
Bucket BUCKET1("MultiplexityService1");
Bucket BUCKET2("MultiplexityService2");
Object OBJECT1("MultiplexityService1.txt", BUCKET1);
Object OBJECT2("MultiplexityService2.txt", BUCKET2);
PathInput input(PATH);
Octets length = size(PATH);
PathOutput output(OBJECT2.getKey());
Multiplex multiplex;

BucketCreate bucketcreate1(BUCKET1, multiplex);
BucketCreate bucketcreate2(BUCKET2, multiplex);
bucketcreate1.start();
bucketcreate2.start();
while (multiplex.service() > 0) { }
if (!bucketcreate1.isSuccessful()) { break; }
if (!bucketcreate2.isSuccessful()) { break; }

ObjectPut objectput1(OBJECT1, multiplex, input, length);
objectput1.start();
while (multiplex.service() > 0) { }
if (!objectput1.isSuccessful()) { break; }

ObjectCopy objectcopy(OBJECT1, OBJECT2, multiplex);
objectcopy.start();
while (multiplex.service() > 0) { }
if (!objectcopy.isSuccessful()) { break; }

ObjectGet objectget2(OBJECT2, multiplex, output);
objectget2.start();
while (multiplex.service() > 0) { }
if (!objectget2.isSuccessful()) { break; }

ObjectDelete objectdelete1(OBJECT1, multiplex);
ObjectDelete objectdelete2(OBJECT2, multiplex);
objectdelete1.start();
objectdelete2.start();
while (multiplex.service() > 0) { }
if (!objectdelete1.isSuccessful()) { break; }
if (!objectdelete2.isSuccessful()) { break; }

BucketDelete bucketdelete1(BUCKET1, multiplex);
bucketdelete1.start();
BucketDelete bucketdelete2(BUCKET2, multiplex);
bucketdelete2.start();
while (multiplex.service() > 0) { }
if (!bucketdelete1.isSuccessful()) { break; }
if (!bucketdelete2.isSuccessful()) { break; }

std::string command = "diff ";
command += PATH;
command += " ";
command += OBJECT2.getKey();
if (std::system(command.c_str()) < 0) { break; }
if (::unlink(OBJECT2.getKey()) < 0) { break; }

I've just basically implemented the complete method by calling the service method iteratively until it reports that there is no more work to be done. But an application could instead time slice the calling of the service method with other work. The service method has embedded in it a timed select system call so that it relinquishes the processor while waiting for the sockets to S3 to become ready.

The next example is the first one in which you'll see multi-threading. The Complex manager has a service thread that runs in the background and executes all pending actions. Instead of starting actions itself, the application instead submits each action to Complex and then waits on a POSIX thread condition variable specific to that action. All action processing is done in the Complex thread. No matter how many Complex objects you create, there is just one Complex thread doing all the work, and many actions may be executed in parallel in the background by that one thread.

const char * PATH = "unittest.txt";
Bucket BUCKET1("ComplexityWait1");
Bucket BUCKET2("ComplexityWait2");
Object OBJECT1("ComplexityWait1.txt", BUCKET1);
Object OBJECT2("ComplexityWait2.txt", BUCKET2);
PathInput input(PATH);
Octets length = size(PATH);
PathOutput output(OBJECT2.getKey());
Complex complex;

BucketCreate bucketcreate1(BUCKET1, complex);
complex.start(bucketcreate1);
BucketCreate bucketcreate2(BUCKET2, complex);
complex.start(bucketcreate2);
complex.wait(bucketcreate1);
complex.wait(bucketcreate2);
if (!bucketcreate1.isSuccessful()) { break; }
if (!bucketcreate2.isSuccessful()) { break; }

ObjectPut objectput1(OBJECT1, complex, input, length);
complex.start(objectput1);
complex.wait(objectput1);
if (!objectput1.isSuccessful()) { break; }

ObjectCopy objectcopy(OBJECT1, OBJECT2, complex);
complex.start(objectcopy);
complex.wait(objectcopy);
if (!objectcopy.isSuccessful()) { break; }

ObjectGet objectget2(OBJECT2, complex, output);
complex.start(objectget2);
complex.wait(objectget2);
if (!objectget2.isSuccessful()) { break; }

ObjectDelete objectdelete1(OBJECT1, complex);
complex.start(objectdelete1);
ObjectDelete objectdelete2(OBJECT2, complex);
complex.start(objectdelete2);
complex.wait(objectdelete1);
complex.wait(objectdelete2);
if (!objectdelete1.isSuccessful()) { break; }
if (!objectdelete2.isSuccessful()) { break; }

BucketDelete bucketdelete1(BUCKET1, complex);
complex.start(bucketdelete1);
BucketDelete bucketdelete2(BUCKET2, complex);
complex.start(bucketdelete2);
complex.wait(bucketdelete1);
complex.wait(bucketdelete2);
if (!bucketdelete1.isSuccessful()) { break; }
if (!bucketdelete2.isSuccessful()) { break; }

std::string command = "diff ";
command += PATH;
command += " ";
command += OBJECT2.getKey();
if (std::system(command.c_str()) < 0) { break; }
if (::unlink(OBJECT2.getKey()) < 0) { break; }

Unless you have some strenuous objection to multi-threading, this is the approach you should use in a real application. The background service thread does a lot more than just execute the actions. If the actions fail for any reason deemed to be recoverable, like a network connection failure, the background service thread attempts to automatically retry the action. It does so after an appropriate back off interval to prevent the application from overloading the network, S3, or the local processor. The number of retries for any one action is limited so that execution of each action is guaranteed to eventually terminate. Once the application thread wakes up from its wait, the action will have either completed (either successfully or because of an unrecoverable error) or exceeded its retry limit.

One thing the background service thread cannot do by itself is know how to rewind the input or output functors if, for example, the network connection fails in the middle of the ObjectPut or ObjectGet. Hayloft has a way around that that involves overriding the reset method in ObjectPut or ObjectGet to handle the rewinding of the underlying data source or sink. In the case of PathInput and PathOutput, this just means closing and reopening the underlying local file. Although I don't show this example here, you can find it in example.cpp. It's trivial to implement in an application.

Hayloft currently doesn't offer a timed wait. I just haven't convinced myself it's either necessary or a good idea. But you can poll actions to see if the background service thread has completed them. In fact, if you don't mind burning a lot of processor cycles, you can dispense with the wait on the condition variable completely and just poll the actions until they complete.

const char * PATH = "unittest.txt";
Bucket BUCKET1("ComplexityPoll1");
Bucket BUCKET2("ComplexityPoll2");
Object OBJECT1("ComplexityPoll1.txt", BUCKET1);
Object OBJECT2("ComplexityPoll2.txt", BUCKET2);
PathInput input(PATH);
Octets length = size(PATH);
PathOutput output(OBJECT2.getKey());
Complex complex;

BucketCreate bucketcreate1(BUCKET1, complex);
complex.start(bucketcreate1);
BucketCreate bucketcreate2(BUCKET2, complex);
complex.start(bucketcreate2);
while (bucketcreate1 != true) { Thread::yield(); }
while (bucketcreate2 != true) { Thread::yield(); }
if (!bucketcreate1.isSuccessful()) { break; }
if (!bucketcreate2.isSuccessful()) { break; }

ObjectPut objectput1(OBJECT1, complex, input, length);
complex.start(objectput1);
while (objectput1 != true) { Thread::yield(); }
if (!objectput1.isSuccessful()) { break; }

ObjectCopy objectcopy(OBJECT1, OBJECT2, complex);
complex.start(objectcopy);
while (objectcopy != true) { Thread::yield(); }
if (!objectcopy.isSuccessful()) { break; }

ObjectGet objectget2(OBJECT2, complex, output);
complex.start(objectget2);
while (objectget2 != true) { Thread::yield(); }
if (!objectget2.isSuccessful()) { break; }

ObjectDelete objectdelete1(OBJECT1, complex);
complex.start(objectdelete1);
ObjectDelete objectdelete2(OBJECT2, complex);
complex.start(objectdelete2);
while (objectdelete1 != true) { Thread::yield(); }
while (objectdelete2 != true) { Thread::yield(); }
if (!objectdelete1.isSuccessful()) { break; }
if (!objectdelete2.isSuccessful()) { break; }

BucketDelete bucketdelete1(BUCKET1, complex);
complex.start(bucketdelete1);
BucketDelete bucketdelete2(BUCKET2, complex);
complex.start(bucketdelete2);
while (bucketdelete1 != true) { Thread::yield(); }
while (bucketdelete2 != true) { Thread::yield(); }
if (!bucketdelete1.isSuccessful()) { break; }
if (!bucketdelete2.isSuccessful()) { break; }

std::string command = "diff ";
command += PATH;
command += " ";
command += OBJECT2.getKey();
if (std::system(command.c_str()) < 0) { break; }
if (::unlink(OBJECT2.getKey()) < 0) { break; }

The polling queries a state variable inside every action that is protected by a mutex and is accessed using an overloaded C++ boolean cast operator.

It took me the better part of two solid months to slam out the code for Hayloft, including its extensive unit test suite. But once I did, writing these examples and getting them all running took just a morning, with occasional breaks to check out the latest LOLcats.

Even if you don't want to use Hayloft, or C++, there are many other libraries around for using S3 in other languages, or indeed for using other cloud-based services. I believe information technology is rapidly evolving into a model in which mobile wireless devices and their applications (driven by consumer-side economies of scale) act as front ends to very large distributed cloud based services (driven by information technology-side economies of scale). If you have a background in developing for embedded or distributed systems, I suspect that you are going to find your skills map well to those required for this kind of work.

Friday, December 16, 2011

The Cost of Experimenting with the Cloud

So after two months of my part-time experimentation with the Simple Storage Service (S3) from Amazon Web Services (AWS) using Hayloft, my company finally got charged for its usage. Three cents. It will be interesting to see if it actually shows up on my company credit card bill, or if Amazon.com defers it until the amount gets a little larger.

It's going to take a while. Typically I run the automated test suite many times a day, and each execution issues dozens of transactions to S3, but each transaction involves a tiny amount of data. Still, considering all I've learned while working on this project, this is a bargain.

Update 2011-12-18

I just counted: 198 individual S3 operations in the Hayloft test suite as of today, each one involving at least one request and response with S3.

Friday, December 09, 2011

Fibonacci Scaling

Circa 1996 I found myself in an ideal situation: spending long hours working on a very technically challenging project with a multi-disciplinary bunch of engineers who were all smarter than I was. Good times.

During that project one of my esteemed colleagues, John Meiners, needed a way to scale up the bandwidth on communications channels allocated in real-time on an as-needed basis. We were using Asynchronous Transfer Mode (ATM), a technology in which endpoints have to negotiate with the network for the amount of bandwidth they needed. Asking for more bandwidth than we needed meant more cost for our customers. Asking for less meant data loss. Tearing down an existing channel to allocate a bigger one would be viewed as a catastrophic failure. Due to the hard real-time nature of the application, doing everything via best effort was not even on the table.

So we started small, then as load increased we allocated additional channels. But some back of the envelope calculations suggested that if we chose a fixed bandwidth increment, things could get out of hand quickly with the number of channels we had to manage. We needed to start small, but allocate larger channels as the need arose. What algorithm should we use?

John looked at various exponential algorithms, like doubling the bandwidth request of each subsequent channel. But that got really big (and hence really expensive) really quickly, and the scaling didn't match our expected use cases. What he finally settled on was Fibonacci numbers:

Fn = Fn-1 + Fn-2

where

F0 = 0
F1 = 1

Starting with F1 just as Fibonacci himself did in 1202 (since using zero as a bandwidth multiplier doesn't make much sense) produces a sequence that looks like this:

1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...

This turned out to be pretty much ideal. It starts small and conservative, expands but not too quickly, and is trivially computed since you just have to keep track of the last two numbers in the sequence and merely do an addition.

Fibonacci numbers have been around a long time. Although Leonardo of Pisa (a.k.a. Fibonacci) gets the credit, the sequence was written down earlier by Indian mathematicians. It occurs frequently in nature, most noticeably in spirals such as those found in pine cones and shells. John's idea seems pretty innovative in 1996, but lots of high-technology applications of the Fibonacci sequence exist today, including network back off algorithms, lossy data compression, pseudo-random number generators, and tree and heap data structures.

I'm thinking about this because I am once again using this sequence as a way to scale up back off time delays when recovering from network errors in Hayloft, my little C++ research project using Amazon Web Services Simple Storage Service (S3). I have no doubt that Fibonacci's simple little recursive algorithm will continue to serve me well.

Tuesday, December 06, 2011

Eventual Consistency and Hayloft

Given my thirty plus years of experience in distributed computing, it's a given that I've had to more or less continuously grapple with the Fallacies of Distributed Computing as laid out by L Peter Deutsch, James Gosling, and others:

  1. The network is reliable.
  2. Latency is zero.
  3. Bandwidth is infinite.
  4. The network is secure.
  5. Topology doesn't change.
  6. There is one administrator.
  7. Transport cost is zero.
  8. The network is homogeneous.

The implications of these myths led Eric Brewer to make Brewer's Conjecture, which became the CAP Theorem once it was proven by Seth Gilbert and Nancy Lynch.

A distributed system can guarantee at most two of the three following qualities:

  1. all nodes can see the same data at the same time (consistency);
  2. every request receives a response as to whether it succeeded or failed (availability);
  3. the system continues to operate despite message loss (partition tolerance).

I've been thinking a lot about the implications of this for storage systems ever since attending the 27th IEEE Symposium on Massive Storage Systems and Technologies, a.k.a. MSST 2011. One of the big take aways I had from that conference was that distributed storage systems cannot reliably support POSIX semantics, in particular the POSIX features of file locking and consistency in file modification. Thanks to the CAP Theorem, POSIX semantics don't scale.

(I find that all of the really interesting problems are scalability problems, regardless of the problem domain. If solving a problem at scale n seems easy, trying applying the same solution at scale n x 1000. Not so much. That's why domains like cloud computing and exascale high performance systems have caught my interest. You can't just take current architectures and multiple by one thousand.)

This is one of the reasons that cloud storage has become popular: the various web-based mechanism for data transfer used by the cloud, like the RESTful HTTP GET and PUT, and XML-based SOAP, have semantics that have proven to be highly scalable. Hence they map well to large distributed system architectures.

It was this very issue that lead Amazon.com to adopt a strategy for its globally distributed Amazon Web Services (AWS), including S3, its non-POSIX-compliant Simple Storage Service, which its CTO Werner Vogels refers to as eventually consistent, choosing availability and partition tolerance over consistency:

Data inconsistency in large-scale reliable distributed systems has to be tolerated for two reasons: improving read and write performance under highly concurrent conditions; and handling partition cases where a majority model would render part of the system unavailable even though the nodes are up and running.

Indeed, the well publicized failures in AWS have been not in S3, but in its Elastic Block Store (EBS), which tries to support POSIX semantics on top of a globally distributed system.

I can see the Fallacies, and the eventual consistency architecture, at work when I play with Hayloft, my little C++ research project that uses S3. Any realistic application using S3 has to deal with network failures, where simply retrying the operation may be sufficient. But it also has to deal with the issues of consistency convergence: the fact that every S3 action may take place on a different AWS server that doesn't yet know what actions have taken place on other AWS servers, even though those actions may have been performed on the same storage objects.

Hayloft features both a synchronous and an asynchronous interface. The former makes it easy to play with. The latter is more likely to be what a production application would use. The asynchronous interface features a mechanism to block until an S3 action completes, or to execute multiple S3 actions incrementally and in parallel. Unlike my prior article on Hayloft, I'll use the asynchronous interface here, but use the blocking completion mechanism because it's simpler. (As before, all of this code is taken from working unit tests in the Hayloft distribution, but edited for readability. Apologies for any typos.)

Here is a code snippet that creates a bucket to hold objects. It starts the action and blocks until it completes.

Multiplex multiplex;
BucketCreate bucket("Bucket", multiplex);
bucket.start();
multiplex.complete();

But that's not sufficient. Sometimes (rarely), the action will return a status indicating a temporary failure, like "connection failed", "name lookup error", or "request timed out". The network isn't reliable, and the failure more likely to be on my end, or somewhere along the convoluted path between my system and S3, than in S3 itself. Simply retrying the action after a one second delay is usually sufficient unless the outage is severe. (Note that "success" is not a retryable condition.)

Multiplex multiplex;
BucketCreate bucket("Bucket", multiplex);
for (int ii = 0; ii < 10; ++ii) {
bucket.start();
multiplex.complete();
if (!bucket.isRetryable()) { break; }
platform.yield(platform.frequency());
}

Once the bucket is created, we can store an object in it. Here's a code snippet similar to the one above except it has to deal with rewinding the input data source if we need to retry the action. You can see that this might get a smidge complicated depending on where your data is coming from.

PathInput * source = new PathInput("./file.txt");
Size bytes = size(*input);
ObjectPut put("InputFile.txt", bucket, multiplex, source, bytes);
for (int ii = 0; ii < 10; ++ii) {
put.start();
multiplex.complete();
if (!put.isRetryable()) { break; }
platform.yield(platform.frequency());
source = new PathInput("./file.txt");
bytes = size(*input);
put.reset(source, bytes);
}

But network outages aren't the only failures we have to worry about. The following code snippet retrieves the metadata for the object we just created.

ObjectHead head(put, multiplex);
for (int ii = 0; ii < 10; ++ii) {
head.start();
multiplex.complete();
if (!head.isRetryable()) { break; }
platform.yield(platform.frequency());
}

This usually works. Except when it doesn't. Sometimes (and much more frequently than I see retries due to temporary network failures) the action will return a non-retryable status indicating the object wasn't found. WTF?

The object head action was serviced by a different AWS server than that of the object put action, one that hadn't yet been notified of the object put. This is eventual consistency in action. The unit test tries a code snippet like the following, treating the non-existence of the object as a retryable error, since it knows darn well the object put was successful.

ObjectHead head(put, multiplex);
for (int ii = 0; ii < 10; ++ii) {
head.start();
multiplex.complete();
if (head.isRetryable()) {
// Keep trying.
} else if (head.isNonexistent()) {
// Keep trying.
} else {
break;
}
platform.yield(platform.frequency());
}

Eventually this works. But it's even more complicated than that. If you ran this exact same code snippet again, it might still fail at first, because it was run on yet another server which had not yet been updated to be consistent with the others. In fact, its success on a subsequent attempt may be because it just happened to be executed on the original server, not because all the servers had been updated. Applications have to be designed around this. Amazon's S3 best practices document recommends not using code snippets like this to verify the successful put of an object.

The unit tests log a message every time they retry. I can actually watch how long it takes for the AWS servers to become consistent, and how this consistency convergence changes with the load on the system. Typically it converges so quickly that the unit test doesn't have to retry. Rarely, it takes a second or two. Or sometimes, not so rarely. I was testing a lot of this code on the day after the Thanksgiving holiday in the United States, also known as Black Friday, typically the busiest shopping day of the Christmas season. It frequently took two or three seconds for the system to converge to a consistent state. I haven't seen this kind of latency before or since. But, to its credit, S3 always converged and the unit tests all eventually ran successfully to completion.

Whether or not this is an issue for you depends on your S3 application. For a lot of applications, it won't matter. For applications where read-after-write consistency is important, AWS offers a higher (more expensive) tier of service where objects are co-located in one of their big data centers instead of possibly being spread out among multiple centers; this tier offers read-after-write consistency. If immediate consistency is an issue for you, S3 may not be right platform for your application. However, I would argue that distributed computing isn't the right paradigm for you.

The cloud is not the place for everyone.

Thursday, December 01, 2011

Amazon.com's Simple Storage Service and Hayloft

Information technology is like fashion: you live long enough, you see it change many times. And sometimes the new stuff looks kinda like the old stuff. But that doesn't mean you don't get excited about it. Change is inevitable; you might as well learn to enjoy it.

I'm watching the IT world evolve to a model that is handheld battery powered consumer devices, which these days we're calling smartphones and tablets, communicating wirelessly with enormous distributed computing systems, which we now call cloud computing. I'm all excited. For lots of reasons. Not the least of which is the fact that my professional career over the past thirty-five years as wobbled back and forth between developing software for small embedded systems and for high performance computers, gigantic distributed systems, and server farms. Turns out, the skill sets are the same. I am not the first person to have noticed this.

My most recent project is to develop Hayloft, a C++ object oriented interface to Amazon Web Services (AWS) Simple Storage Service (S3). My goal is for Hayloft to make it easy to use S3 from embedded devices. S3 is Amazon.com's web-based storage service that can (if you do it right) reliably and inexpensively store blobs of arbitrary data. How much data? A single blob, or object, can be up to five terabytes in size. And you can store a lot of objects. Objects are organized into buckets. Each bucket can be thought of as a web site with its own domain name, which means bucket names have to conform to the internet's Domain Name System (DNS) syntax. Each object is independently addressable via its own URL. To S3, these objects are simply opaque data files in the classic mass storage system reference model sense: they can range from HTML pages to scientific databases to virtual machine images to what have you.

(Indeed, I strongly suspect you could build a distributed mass storage system from S3 just as Cycle Computing built a 10,000 core distributed supercomputer from Amazon.com's Elastic Computing Cloud (EC2) for one of their customers. I'm pretty excited about that, too.)

Why would you you want to access S3 from an embedded device? Can you think of any applications for an infinitely large, internet-accessible, web-addressable, reliable, secure, storage system? Whether you are building clever consumer applications for the commercial space, developing sensor platforms for the defense and intelligence domain, or information processing applications for the industrial, financial, or medical markets, if the thought of this doesn't make your hands shake, you aren't thinking clearly. Seriously. Terabytes of storage are just a wireless connection away from your handheld and embedded applications.

Here's a little taste of what Hayloft is like. These examples are taken directly from the unit test suite included with Hayloft with all the EXPECT and ASSERT statements removed. I've also removed all of the error recovery and consistency convergence code which in any practical circumstances are very necessary; I'll talk more about that in later articles. Hayloft presents both a synchronous and an asynchronous interface. These examples use the simpler synchronous interface: when the C++ constructor completes, all the S3 work is done.

Here's a code snippet that creates a new bucket, and writes a local file into an object in it. The user key id and secret access key, which are sort of like your login and password for AWS, and which are provided by Amazon.com, are in environmental variables. Also in an environmental variable is a bucket suffix appended to all bucket names to make them globally unique; I use my internet domain name. All of the other S3 parameters, like location constraint, endpoint, access control list, and so forth can be omitted, because for experimenting, the defaults are reasonable. Input and output is handled using Desperado I/O functors.

BucketCreate create("bucket");
PathInput input("./oldfile.txt");
Size bytes = size(input);
ObjectPut put("Object.txt", create, input, bytes);

By default, buckets and objects are created by Hayloft with private access. With just a few more lines you can specify public read access so that you can (and I have) retrieve this object using your web browser.

AccessPublicRead access;
Context context;
context.setAccess(access);
BucketCreate create("bucket", context);
Properties properties;
properties.setAccess(access);
PathInput input("./oldfile.txt");
Size bytes = size(input);
ObjectPut put("Object.txt", create, input, bytes, properties);

This object can now be accessed using the following URL.

http://bucket.hayloft.diag.com.s3.amazonaws.com/Object.txt

This is a code snippet that reads the object into a local file, then deletes the object.

PathOutput output("./newfile.txt");
ObjectGet get("Object.txt", create, output);
ObjectDelete delete("Object.txt", create);

Other than some #include statements for header files, and some curly brackets and what not, that's about all there is to it, if you ignore (at your peril) error recovery. Here's a snippet that gets a table of contents from an existing bucket, then uses the C++ Standard Template Library (STL) to iterate through it and print the object names.

BucketManifest manifest("bucket");
BucketManifest::Manifest::const_iterator here = manifest.getManifest().begin();
BucketManifest::Manifest::const_iterator there = manifest.getManifest().end();
while (here != there) {
const char * key = here->first.c_str();
printf("%s\n", key);
++here;
}

While using Hayloft is easy, installing it may take a few minutes. Hayloft is built for GNU and Linux on top of Desperadito, my C++ systems programming library (a subset of the much larger Desperado), and libs3, Bryan Ischo's excellent C-based S3 library. libs3 is built on top of CURL, Open SSL, and XML2, all of which can be probably acquired through the standard package manager on your Linux system. The unit tests for Hayloft are built with Google Test (or Google Mock, which includes Google Test), Google's outstanding C++ unit testing framework, and Lariat, my thin layer over Google Test.

But once you get past the installation, starting to play with S3 in C++ applications is as simple as pulling out your credit card, signing up for an AWS account, and writing a few lines of code.

Monday, November 14, 2011

Abstraction in C++ using I/O Functors

In Abstraction in C Using Source and Sinks, I wrote about how useful I've found it to abstract out I/O interfaces so that I could write software that didn't have to know from where its input was coming or to where its output was going: sockets, standard I/O library FILE pointers, memory buffers, the system log, etc. That C-based project, Concha, was a clean room reimplementation of work I had done for a client back in 2007. What I didn't mention was that it was in turn inspired by work I had done in 2006 for a C++-based project, Desperado. Now that I'm building yet another project, Hayloft, on top of Desperado, I'm reminded how much I like the Desperado I/O abstraction.

The Desperado I/O abstraction defines two interfaces, Input and Output. These interfaces make use of the ability in C++ to overload the parentheses operators to create functors (a.k.a. function objects): objects that can be manipulated through a function call interface. Looking at code, you will think you are looking at function calls. What you are really seeing are instance method calls against an object that overrides the parentheses operators.

The Input interface defines the following four operations.

int operator() ();

This returns the next character as an integer, or EOF (end of file) to indicate that no more input is available.

int operator() (int ch);

This pushes a single character back into the input stream. (This vastly simplifies the implementation of many common parsing algorithms that require one-token look ahead.) The interface guarantees that at least one character can be pushed back. It need not be the most recent character read. How the push back is actually done is up to the underlying implementation; buffering it inside the object in the derived class implementation is acceptable. If the push back is successful, the character is returned, otherwise EOF is returned.

ssize_t operator() (char * buffer, size_t size);

This returns a line terminated by a newline character (/n) or EOF. The optional size parameter allows the caller to place a limit on the number of characters returned. The result is guaranteed to be NUL terminated as long as the buffer is at least one byte in length. The actual number of characters input is returned, or EOF if none.

ssize_t operator() (void * buffer, size_t minimum, size_t maximum);

This is typically used for unformatted data. The minimum parameter indicates the minimum number of characters to be returned. The implementation blocks until that many characters are available or EOF is reached. The maximum parameter indicates the maximum number of characters to be returned if it can be done without blocking. Specifying a minimum of zero is a common way to implement non-blocking I/O using polling. Specifying the same value for minimum and maximum simply blocks for a fixed amount of data. Using the value one for minimum results in something similar to the POSIX read system call. The actual number of characters input is returned, or EOF if none.

That's it. No open or close: those are the job of either the caller, or of the implementation's constructor and destructor. The Input base class isn't pure: it actually implements all of these operators, returning EOF for all operations. That makes the base class the equivalent of /dev/null.

Since all implementations derive from the Input base class, you can pass a pointer or reference to any implementation to a function expecting an Input pointer or reference and it will read its data from that object without having any idea what the actual underlying data source is. Desperado implements a variety of derived classes, such as DescriptorInput (its constructor takes a file descriptor as an argument), FileInput (a FILE pointer), BufferInput (a read/write memory buffer), DataInput (a read-only memory buffer), and PathInput (a path name in the file system). All of these derived classes implement the full Input interface.

The Hayloft project leverages this in its Parameter class. Parameter takes an Input reference or pointer, uses the line input functor, and reads a parameter value into a C++ std::string that is a instance variable named parameter. It has no idea where this value is coming from: a file, a socket, a memory location, what have you. Here's the complete implementation of the method in Parameter that does this.

(I apologize in advance for any violence done to this and other code snippets by the Blogger formatter - which truly sucks at code examples even when editing raw HTML - and for any typos I make when transcribing this from actual working source code.)

void Parameter::source(Input & input, size_t maximum) {
int ch;
while (maximum > 0) {
ch = input();
if ((ch == EOF) || (ch == '\0') || (ch == '\n')) { break; }
parameter += ch;
--maximum;
}
}

You can see the Input functor called on the fourth line: the input object reference is used just as if it were a function.

The Output interface defines the following five operations.

int operator() (int c);

A single character in an integer is emitted. The character is returned or EOF if unsuccessful.

ssize_t operator() (const char * s, size_t size);

A null terminated string is emitted. The optional size parameter places a limit on the number of characters emitted. The actual number of characters emitted is returned or EOF if none.

ssize_t operator() (const char * format, va_list ap);

A variable length argument list is emitted according to the printf-style format string. The actual number of characters emitted is returned or EOF if none.

ssize_t operator() (const void * buffer, size_t minimum, size_t maximum);

At least a minimum and no more than a maximum number of bytes are emitted. As before, more than the minimum is emitted if it can be done without blocking. The actual number of characters emitted is returned or EOF if none.

int operator() ();

Any data buffered in the underlying implementation are flushed to the output stream. A non-negative number is returned for success, EOF for failure.

Similar to the Input interface, the Output base class is not pure: it implements all of these functors, each of which throws the data away and returns success. The Output base class is also the equivalent of /dev/null.

As you might expect, Desperado implements a variety of derived classes: DescriptorOutput, FileOutput, BufferOutput, PathOutput, and SyslogOutput (which writes all of its output to the system log).

The Desperado Print class makes effective of Output functors. Its constructor takes a single Output reference as its only parameter.

Print:Print(Output & output);

Print defines its own functor which takes a variable length argument list. Here is its entire implementation.

ssize_t Print::operator() (const char * format ...) {
va_list ap;
ssize_t rc;
va_start(ap, format);
rc = output(format, ap);
va_end(ap);
return rc;
}

You can see the output constructor reference used just like a function call on the fifth line.

In an application, you can now write code like this, which I do all the time. (Warning: head explosion may be imminent.)

extern Output * myoutputp;
Print printf(*myoutputp);

printf("An error occurred!\n");
printf("errno=%d\n", errno);

This illustrates one of the greatest strengths and greatest weaknesses of C++: if you encountered this while reading code, you would likely to assume that the printf was the standard I/O statement you know and love. But it isn't at all; it's a Print object. And that Print object has no idea where it's output is going. Depending on actual type of its constructor argument, it could be a socket, a file, or even a memory buffer.

It is possible to have a class that offers both an Input and an Output interface. Hayloft does this for its Packet class. Packet implements an infinite (as long as memory holds out anyway) bi-directional memory buffer. Although it offers specialized methods to prepend and append data, it also exposes both an Input and Output interface so that a Packet can be used as a data sink (by passing its Output interface) or as a data source (through its Input interface). A Packet can be used in this manner as a ring buffer.

This pattern is so common that Desperado defines an InputOutput interface for such implementations. This interface defines two methods that each return a reference to the appropriate interface.

Input & input();

Output & output();

This allows you to do things like

extern Packet * mypacketp;
Print printf(mypacketp->output());

to collect printed output into a Packet.

I/O functors illustrate one of those capabilities that makes C++ both extremely powerful and often hard to understand, because it allows one to use C++ not just as a programming language but as a meta-language, effectively creating a new domain specific language with its own operations, one that just happens to look vaguely like C++. It also means that while reading C++ code, especially in large code bases, it can be very difficult to make any assumptions about what is going on without both a broad and a deep understanding of both C++ and the underlying code.