12/05/2013

C++ Multithreading Support


C++11 Multithreading overview 


The C++11 standard provides multithreading support, including the following features: thread creation and management, mutexes, atomic objects, thread local storage and condition variables.
Thread creation and management is provided by the std::thread class which is defined in <thread>. The class works with regular functions, lambdas (functions written directly in your source code) or functors (classes with overloaded () operator).  Any number of parameters can be passed to the thread function.  To work with the thread you should create an instance of std::thread class and pass it the working function.  Let’s see the example:
#include <iostream>
#include <thread>

void testFunc()
{
       std::cout << "Hello from the thread!";
}

int main(int argc, char *argv [])
{
       std::thread my_thread(testFunc);
       my_thread.join();
       return 0;
} 
In this example a reference to the trivial function is being passed to the constructor of the thread class. After thread creation we call join() to ensure that it has finished executing before program exit. Technically you should check whether the thread is joinable by calling its joinable() method first. If you don’t want to wait for thread execution finish, you could call the detach() member function to separate thread execution from the thread object. After calling detach() this thread object is no longer joinable. Any number of arguments can be passed to a thread:
#include <iostream>
#include <thread>

void printEven(int printArray[], int size)
{
       for (int i = 0; i < size; ++i)
       {
             if (printArray[i] % 2 == 0)
                    std::cout << "Even number " << i << " is - " << printArray[i] << "\n";
       }
}

int main(int argc, char *argv [])
{
       const int SIZE = 7;
       int evenArray[SIZE] = { 0, 7, 8, 63, 81, 24, 369 };
       std::thread my_thread(printEven, evenArray, SIZE);

       if (my_thread.joinable())
             my_thread.join();

       return 0;
} 
If there is need to pass parameters by reference, they should be wrapped into std::ref or std::cref.
Each thread has its own id. std::thread class  has get_id() member function, which returns unique id for the thread. To get the id of the current thread std::this_thread::get_id() can be used.  Thread id's are stored in lightweight std::thread::id class.

Useful features 

There are several useful functions in this_thread namespace. yield() function is used to notify the thread scheduler that it should select another thread to run. Using yield() is rarely necessary. sleep_until() expects an instance of std::chrono::time_point class and stops execution till system clock reaches this point. sleep_for() expects an instance std::chrono:duration class and blocks thread execution for that certain time.
#include <iostream>
#include <thread>

const int MAX_DELAY = 10;
const int THREADS_NUMBER = 5;

void raceThread()
{
       int delay = rand() % MAX_DELAY;
       std::thread::id currentID = std::this_thread::get_id();
       std::cout << "Thread with id " << currentID << " started. Delay " << delay << " seconds\n";
       std::this_thread::sleep_for(std::chrono::seconds(delay));
       std::cout << "Finishing thread...\n";
}

int main(int argc, char *argv [])
{
      
       std::auto_ptr<std::thread> ThreadsArray[THREADS_NUMBER];
       for (int i = 0; i < THREADS_NUMBER; ++i)
       {
             ThreadsArray[i].reset(new std::thread(raceThread));
       }

       for (int i = 0; i < THREADS_NUMBER; ++i)
       {
             ThreadsArray[i]->join();
       }
       return 0;
} 
Please try to tun the listing above several times. As you can see the results are different every time. That's because each thread is printing information using stdout which is a shared resource. Because iutput is not synchronized between working threads, it's ownership could be easily "stolen" by another threads. The result of such unsynchronized access is undefined behaviour.
Mutex  is used to ensure that only one thread is working with the shared resource at the same time.  So lets talk a bit about how they are defined in C++ 11 standard. Class std::mutex is used for locking and unlocking shared resources.  Besides it, there are three different types of mutexes – std::timed_mutex – which difference from previous one only by having a possibility to lock some resource for a certain timeout, std::recursive_mutex – this kind of mutex allows a thread to recursivly lock a resource, by making additional calls to lock or try_lock The period of ownership ends when thread makes a matching number of calls to unlock. Attempting to recursively lock a regular mutex will cause a deadlock. std::recursive_timed_mutex– recursive mutex with timeout ability. Lets change previous example and make access to the shared resource managed as we want it to be.
#include <iostream>
#include <thread>
#include <mutex>

const int MAX_DELAY = 10;
const int THREADS_NUMBER = 5;

std::mutex g_mutex;

void raceThread()
{
       std::lock_guard<std::mutex> lock(g_mutex);
       int delay = rand() % 10;
       std::thread::id currerntId = std::this_thread::get_id();
       std::cout << "Thread with id " << currerntId << " started. Delay " << delay << " seconds\n";
       std::this_thread::sleep_for(std::chrono::seconds(delay));
       std::cout << "Finishing thread...\n";
} 
The main function is the same as in previous listing so we've just skipped it here.  
std::lock_guard  is a RAII-style wrapper for more convenient work with std::mutex, it locks on creation and releases the lock after destruction.Because of potential deadlock problems, it is strongly recommended to avoid locking several mutexes at one time. Unfortunately, sometimes more than one resource should be locked (e.g. you  are working with two distinct data items and each of them is protected by its own mutex). In that case std::unique_lock can be helpful. It has a similar functionality to lock_guard but besides that it has a mechanism for avoiding deadlocks in case each resource should be locked by different mutex. An additional argument is passed to its constructor which defines locking strategy. By passing std::defer_lock you can tell std::unique_lock not to acquire ownership of the mutex immediately, and then safely lock both resources by std::lock:
struct Account
{
    Account(float sum) : m_fValue(sum) {}

    float m_fValue;
    std::mutex m_Mutex;
};

void foo(Account &parentAcc, Account &childAcc, float amount)
{
    // don't actually take the locks yet
    std::unique_lock<std::mutex> lock1(childAcc.m_Mutex, std::defer_lock);
    std::unique_lock<std::mutex> lock2(parentAcc.m_Mutex, std::defer_lock);

    // lock both unique_locks without deadlock
    std::lock(lock1, lock2);

    childAcc.m_fValue -= amount;
    parentAcc.m_fValue += amount;
} 
Please keep in mind that behaviour of a program is undefined in case a mutex is destroyed while still owned by some thread. A thread owns the mutex since the time the mutex is successfully locked till  the call of unlock method. So you have to be sure that mutex is not locking anything before destroying it.
Condition variables are another synchronization primitive which is provided by the C++11 standard. It is always associated with mutexes and allows threads to communicate with each other. Also it allows multiple threads to wait for some certain condition to become true or for a specified timeout to expire .  To work with a condition variable thread must acquire a lock first and pass the lock to subsequent condition variable operations. This lock will be implicitly released when the thread starts to wait on the condition variable and when the thread is being awakened because of conditional variable wakeup. std::condition_variable can block threads until notification is received or timeout is expired and sometimes when spurious wakeup occurs.
Besides std::condition_variable, there is a std::condition_variable_any. Thing is std::condition_variable can  work only with std::unique_lock<std::mutex>, where std::condition_variable_any can work with any (possibly used-defined) type which meets the BasicLockable requirments. Besides that, functionality of both synchronization primitives is almost identical.

C++ threads vs. Boost threads

One of the most common used open-source libraries for C++ is Boost. This library also provides multithreading support, so let's compare C++11 threads with boost threads. C++11 threads are supported at core language level while boost threads are basically wrappers around platform-dependent thread implementations.
First thing which you may notice by now is that a C++ thread will not have its detach() method implicitly called when it is being destructed.  You have to manually call join() or detach() before destructing  a thread. If you don’t,  the program will call std::terminate() and it will abort your application.  In Boost there is no such problem because detach() is called automatically on thread destruction.  Boost threads support cancelation, but C++ standard threads don’t.
std::thread allows move-only types, such as  std::unique_ptr to be passed as arguments. Because of the use of boost::bind internally,  Boost requires copyable arguments.  To clear things up a little bit let's see an example:
void foo(std::unique_ptr<int>);
std::thread my_thread(foo, std::unique_ptr<int>(new int(228)));  
std::unique_ptr cannot be copied so this example won't work.  It works when using std::thread, but it won’t be working with boost::thread due to its semantics requiring copyable arguments. Migration from Boost threads to C++11 should not cause a lot of trouble. Of course, some of the Boost features are not supported in C++ standard yet. For example, there is no analogue of boost::shared_mutex, which allows multiple-reader and single-writer locking. It is planned to include such kind of mutex in future C++ standard (from C++14), but currently it is not implemented.Also using threads from the language standard gives few advantages comparing to usage of Boost threads.  No matter how convenient Boost is it’s still an additional library, which means you need to rely on Boost libraries during compilation and linkage. Sometimes these libraries need to be updated. When using C++ threads, which are already included into the standard you don’t  need to worry about such things.

How it works? 


We’ve seen the main features of the C++ threading model. Let’s try to use these features while solving some practical task. Producer-consumer is a well-known multithreading problem. It describes two threads working with a single queue. One of them produces something and puts it into queue and another is consuming and removes items from the queue. The main problem is to ensure that the producer won't try to add into the queue when it's full and consumer won't try to consume from the queue when it's empty.
Lets add some general variables which will be used by both threads.
bool g_isReady = false;
std::mutex g_Mutex;
std::condition_variable g_ConditionVar;

std::queue<int> g_MessagesQueue;

const int QUEUE_SIZE = 10;
const int SLEEP_TIME = 500; 
We declared a boolean flag to indicate ready status of queue, the global message queue to put data in it, and mutex for locking shared data while working with it. Also we a declare condition variable for communication between threads. To prevent hardcoding we declare constants for queue size and sleep time. Producer function will look like this:
void Producer()
{
       std::cout << "\\\\\ Producer is ready ///// \n";
      
       for( int i = 0; ; ++i )
       {
             std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME));                   
             std::unique_lock<std::mutex> lock(g_Mutex);  
            
                            
             if ( g_MessagesQueue.size() < QUEUE_SIZE )
             {
                    std::cout << "Produced " << i << "\n";
                    g_MessagesQueue.push(i);    
             }
             else
             {
                    g_isReady = true; 
                    g_ConditionVar.notify_one();             
             }
       }
} 
Here we have a an infinite loop which pushes data to queue . On each iteration it has small delay and total number of queue elements is compared with queue size. If it less  than the maximum queue size data  is being pushed to the queue, otherwise the status flag is given the appropriate status and the condition variable is used to send notification to the consumer thread.  Lock is acquired when working with shared resources.     Now in the consumer function we have one more infinite loop. It uses the status flag which prevents it from spurious wakeups and waits for notification form the producer thread. After a notification has been received the consumer pops data from the queue and sets the status flag to false:
void Consumer()
{
       std::cout << "\\\\\ Consumer is ready ///// \n";

       while (true)
       {
             std::unique_lock<std::mutex> lock(g_Mutex);

             while (!g_isReady)                            
             {
                    g_ConditionVar.wait(lock);           
             }

             while (!g_MessagesQueue.empty())            
             {
                    std::cout << "Consumed -" << g_MessagesQueue.front() << "\n";
                    g_MessagesQueue.pop();
             }

             g_isReady = false;                           
       }

} 
In the main routine there are only threads creation and waiting them to finish.
int main(int argc, char *argv[])
{
       std::thread producer(Producer);
       std::thread consumer(Consumer);

       if (producer.joinable())
             producer.join();

       if (consumer.joinable())
             consumer.join();
}  
As you can see the C++11 standard presents some powerful features for multithreading support. These features are expected to be enhanced in the next C++ standards.

11/21/2013

Cloud OCR Project: Learn to Develop for Windows Azure Today

A few months ago, we conducted a Cloud Development training course for our engineers. The attendees learned the main concepts of Cloud Computing, found out about the capabilities of the most popular cloud providers on the market, and learned the key design decisions for building highly available, scalable and fault-tolerant distributed systems in the cloud.

We concluded the course with a simple hands-on project: a Windows Azure cloud service that performs OCR (Optical Character Recognition) on images uploaded by users on a Web interface. The service works in a distributed manner, leveraging a fleet of Web and Worker roles that communicate asynchronously using queues:


The reference implementation is available on GitHub under Apache License 2.0. It uses Windows Azure Storage Tables, Blobs and Queues for data persistence and communication, Tesseract for OCR, and ASP.NET MVC 4 and Twitter Boostrap for the Web application. If you always wanted to learn the basics of implementing Web and Worker Roles for Windows Azure and using cloud storage services, this would be a great project to start. It does not involve a lot of abstraction and advanced features, so it will keep you focused on the important parts.


You're welcome to fork this project and send us pull requests.
Have fun!

About the author: Yuriy Guts is an AWS Certified Solutions Architect with several years of experience with architecting cloud solutions for various companies across the globe. He is responsible for the cloud solutions stream at ELEKS R&D and specializes in AWS and Windows Azure.

11/13/2013

js2js: why so serious?

JavaScript is the Assembly of the Web. There are dozens of tools that compile some programming language to JavaScript. You can do it with C++, Java, C#, Python, Ruby or plenty of other languages. It seems that there's one language that remains to be covered for JavaScript to dominate the world: JavaScript itself.

Last week we were joking about this and decided to fix this situation. Meet js2js, a revolutionary open-source compiler that transforms JavaScript directly to JavaScript! Have fun!

11/12/2013

Google Glass: Consumer Device in Enterprise World

You've heard of Google Glass, you have the basic idea of what it does, but you're not sure how it touches you. Right? Then we have something to talk about.
In this article I'm going to shed some light on what it is(and what it's not), how it fits into the enterprise(and how it doesn't), and finally - how can you benefit from it and what will stop you from doing it. You'll also find lots of examples down the road. So, let's start!

Englishman in New York Google Glass in Enterprise

What it is
Well actually it is anything but glasses - it's just a computer with camera, attached to your head:) But let's go step by step.
First of all, we have Android on board, i.e. a POSIX-compatible operating system, which means we could do almost anything we’ve done on mobile phones or desktop computers. The issue is that, as of now, the only official way to build apps for Glass is limited to showing pictures and text. But, unofficially Google lets us use all the features, and as the community is demanding, it seems like a matter of time when it will be official.
Second, we have a smart screen. Why is it smart? Because it’s there when you need it, and gone when you don’t. At least they say so:). The screen turns on on notifications, which you are subscribed to, and manually, by nodding your head lightly. And actually it’s not a screen, it’s projection into infinity. When I tried Glass it took me 5-10 minutes to get used to this.
Then, we have a voice control! That means that we don’t actually need to press any buttons and can keep our hands free. That’s a huge feature. Of course, there’s still a touch pad to cover cases when you want to remain silent. And speaking of sound…they’ve been experimenting with it. Let’s just say that Google Glass can produce sound.
Next, we have a camera, comfortably sitting on your head and seeing everything you see. Most of glass explorers say it’s a killer feature, actually the one that makes glass worth buying. Sharing video while doing your job, gives us a whole new set of opportunities.
And last is the connectivity module. We have Wi-Fi to be self-sufficient, but mostly Glass pairs with mobile phone via Bluetooth and gives us 3G or LTE network together with GPS tracking.
I didn't mention some minor Glass' parts, but you can have a look here for more details.

What it's not
There have been a lot of myths going through the Internet about Google Glass, and I’d like to bust some of them. So, what Google Glass doesn’t do?

First of all it doesn’t do augmented reality. You don’t see the world through the Glass, you see Glass’ screen on top right corner of your view field. So it just doesn’t fit.
Second, you can’t use the camera “secretly”. Google has foreseen this threat and made a design decision to avoid such cases. So, to take a picture we’ll have to say “OK Glass, take a picture” or lift our hand towards our head and press the touch pad. Same goes for video, but while recording, the screen is on, so people will notice you filming them.
Similar situation with face recognition. Google has cut out all standard libraries for face recognition, and also doesn’t allow such applications into their official "store". It is technically possible to implement it but is probably illegal. Yet.
And again the screen. I’ve heard lots of complains that a constant screen in one’s view field will drive people crazy. As I said, the screen is off most of the time and turns on when you need it. Period

Enterprise
Now we're getting to an interesting part. How can we apply it to the enterprise. I'll start from the examples.

Healthcare
Recently Philips together with Accenture have published results of their experiment with Google Glass, which was focused on healthcare. Functionality varied from integrating with Medical Records System, helping managing patients, showing vital signs during the operation and much more.

Warehousing
Another giant, SAP, together with Vuzix have produced their own glasses, specialized for this type of workers. As their demo shows, warehouses workers use optimized path finding, identifying needed palette, scanning barcodes, fixing technical issues by connecting to remote technician and streaming their video.


Maintenance/Tech support
Speaking of tech support, the whole procedure could be simplified, by providing busy technicians with this smart assistant. They could contact their peers and share their screen, look up repair history or take a quick look into the instruction guide while working, and all hands-free!
What's even more important, is that engineers, who use handheld devices at work are actually distracted by them. Moving this device to the default view field would make it more safe.

When is it worth it?
So, following these examples, how do we know when it’s actually worth considering investments into wearables?
Let’s take a look at typical enterprise mobility model. We have field workers, and we equip them with mobile devices, mobile applications and access to corporate network. In return we strongly increase their productivity and improve the business process. Now, there’s this type of workers, whose job requires intensive hand usage. If we equip them with wearable, i.e. hands-free devices, we would not just optimize their work flow, we would also increase their safety. So the key driver to adopting Google Glass-like devices in enterprise is the presence of hands-intensive workers, which would benefit from assistance.

But that’s just the tip of the iceberg. Why limit ourselves with B2E apps? It’s actually more probable that wearables will come into the enterprise from customer side, as it’s a consumer device. A very bright example is banking.

Banking
Most of us already know how important mobile banking is for the customers, and Google Glass could take it to another level. My favorite Google Glass ad is from one of the leading Ukrainian banks PrivatBank, where they show how Glass can simplify our lives. It includes buying things by just taking a look at them, loading car with fuel without even leaving it, finding the ATMs and withdrawing money without the card, and much much more. 

Learning
This is an area where glass explorers have already done a lot. I'll give 2 bright examples
1. A doctor making a knee operation while video-streaming his actions to the students.
2. A physicist having a lesson with his class, while cycling around Hadron Collider
There's also a nice article focused on Google Glass' role in education.

Sports
This is an area where we at ELEKS decided to experiment, as one of the most fruitful sources for integrating wearables into the process and thus expanding interaction scenarios. We've shown how race sports can be changed by equipping participants with live map and leader board, or how group sports can be changed by equipping players with live radar and possibility to see what teammates' see and much more. You can see the interactive video at glass.eleks.com.

Advertising

And what about e-commerce? Retail? Advertising? Public services? At this point wearables come into a perfect combination with contextual awareness. Imagine coming into the airport and automatically receiving notification about your registration desk number, departure gate and flight status. I recommend watching the presentation on NoUI concept and wearables for a bigger picture.

When is it worth it?#2
So Glass can be a very good way to reach your audience. And think of it - these people have consciously put a computer on their head and encouraged you to interact with them in such way. So its probably not a mainstream part of your audience.

Challenges
But let’s step away from the perfect world and face the reality. There is couple of major issues with implementing wearables in the enterprise.

Battery
Seriously, Google glass can take 40 minutes watching youtube, 4 hours standard mode(I didn't expect more from Android:)). There is a great struggle between producing more powerful batteries and wearing them on your head. So good luck here.

Security
We are still in the process of handling current security issues, and bringing this new type of device would cause tones of new concerns. Yes, Google Glass has a good theft protection, but authentication needs to be improved. Also, I imagine, coming to a secure workplace with a camera on your head may be an issue.

User Experience
As I said, screen is smaller, and obviously the interaction is different, so we again need to adapt application logic to it. There are special UX guidelines for building apps for Glass. So we can’t, or at least shouldn’t simply port mobile apps to Glass, just like we shouldn’t port desktop websites to mobile phones. They need to be reconsidered and rebuilt with new usage context in mind.

Priority
I believe most of you have more important problems to solve right now, like BYOD, mobile strategy, teaching your enterprise engineers mobile development, learning about your employees’ workflows and habits, choosing between cross-platform tools or struggling to find a reliable third-party vendor to do this for you... I do not think that focusing main efforts on Glass implementation while having that much on your shoulders is the right thing to do. 

Mass Adoption
Currently there is 10 000 Google Glass items on planet. Comparing to several billions mobile devices. For now, Google Glass is kind of a futuristic device, something cool, unexplored and compelling. But people haven’t got used to it like they did with mobile phones. So adopting it now will take time, efforts and probably training.

And let me guess what you're thinking about right now - "last time we saw mass adoption in mobility, we ended up with BYOD!". So I feel a need to at least touch BYOW

Bring Your Own Wearable?

Obviously Google Glass is not the only "Glass". There is a whole set of other wearable devices: GlassUp, Telepathy, ReconJet, Meta SpaceGlasses and many others. So one could wonder whether BYOD will repeat again.
It’s not clear whether wearables have same future. As technology grows, we see a certain resistance from people to accept them as they become too smart. For example - are you OK with what Google Now does? I sometimes feel uncomfortable, lots of my friends turend it off. Let’s take a look at the numbers. In a recent survey 18% said they’d buy the device. 20% of people agreed that Glass should be banned. More than a half had privacy concerns.  And 69% demanded greater regulation of people wearing the devices in public places. So it remains a great question, whether this new kind of interaction will go massive.
But we have to admit it - Google Glass is the first and probably the only wearable device with potential for mass adoption. Google made a really good marketing job here, which I personally admire.
For more information you can also read this article by Forbes on BYOD and Glass.

What can I do now?
First of all, we have a lot of more important problems and brighter opportunities with mobile devices right now. And I don’t recommend focusing on Google Glass before having more or less stable mobile strategy.
But if you do, you have a whole new set of opportunities! Now, whenever you detect hands intensive job, you know that you can improve it by introducing wearables.
Also, if you’re looking for new ways to reach your customers, Google Glass may just be it – the most effective way to please your most modern target audience.
And although Google Glass is not in public sale yet, you can choose other wearables, or you start building apps for it today, without the device itself.

So, let me finish my saying this - implementing mobility into known business processes and changing them is inspiring. But introducing things like Google Glass, applying them  to the areas where they actually bring value, and being among the first people who've done it - that's just awesome! So let's do it, and let's do it together!

p.s. I've been lucky to get involved in introducing Glass into one of the complex business processes. So in near future you'll see a big success or failure story.

11/06/2013

AWS: 10 Things You're Probably Doing Wrong as an Architect

Amazon Web Services is a powerful and mature cloud platform that keeps growing rapidly. Quite often, new features are added in such pace that many developers and architects barely have a chance to experiment with all of them on real projects. However, as with any cloud platform, the god is in the details. If you want to make the most out of your cloud services, you must know how to use them wisely, and, more important, how NOT to use them.
Based on what I've seen in my experience of training, consulting, designing and implementing cloud solutions, I've compiled a list of common 'gotchas' that might help you avoid many pitfalls on your own projects.
Update: Shortly after writing this blog post, I was excited to discover a very recent HighScalability article by Chris Fregly, a former Netflix Streaming Platform Engineer, which describes similar interesting facts you might encounter with AWS. Make sure to check it out as well!

1. Assuming the identity of Availability Zones across different AWS accounts. 

When you launch AWS resources in a specific AZ, you refer to this AZ by name, such as us-east-1a or us-east-1b. However, these names are purely virtual: when you create a new AWS account and use the us-east region (which has 5 different AZs at the time of this writing), AWS randomly selects 3 physical AZs in this region and assigns the letters a, b, and c to them. The primary purpose of such design decision is to balance the load across multiple AZs in the same region. Otherwise, the users would be more likely to select the first option, us-east-1a, causing an uneven load distribution across the AWS insfrastructure. As a result, us-east-1a in one AWS account is probably a completely different AZ than us-east-1a in another account.

2. Referring to Elastic Load Balancers (ELB) using IP addresses.

The golden rule of designing highly available and fault tolerant systems in the cloud is: do not assume fixed location, health or availability of individual components. The same applies to ELBs: as they scale to accommodate the traffic of your application, AWS may need to relocate or replace them, causing the IP address to change. Therefore, when dealing with ELBs, always refer to them by their DNS names. If you use a custom public domain for your application, create a CNAME record pointing to the DNS of the ELB.
If you use Route 53, there is a special kind of A record available for you: the Alias record. In this case, you can create an A record for your domain that points to the name of the ELB instead of its IP address. In this case, AWS would perform a double DNS resolution behind the scenes and substitute the alias with the particular IP address of the ELB.

3. Performing load testing without pre-warming the ELB.

Behind the scenes, ELB is a load balancing software, which is most likely installed on the instances similar to EC2. And, as any other instance in your infrastructure, it takes time to scale it up and down to accommodate the changes to the traffic. Therefore, if you plan to perform load testing on your application, or if you expect sudden significant load spikes, you should contact AWS support to "pre-warm" your ELBs ahead of time.
Update: Chris Fregly describes the DNS side of this phenomenon in his recent post on HighScalability.

4. Hard-coding the API keys inside AMIs or instances.

When you deploy computations on the EC2 instances, at some point they will inevitably need to use other AWS services (S3, SQS, DynamoDB, CloudWatch, you name it). In order to authenticate on these services, you'll need an IAM key pair: an Access Key ID and a Secret Key. Naturally, the problem is: how does an EC2 instance acquire these keys? An obvious (but a very suboptimal) solution would be to store the keys in a configuration file somewhere in the storage volume. It would work, but you'd have a lot of trouble with securing and rotating these keys.
So there's a better way: use the EC2 Metadata Service. Using this HTTP-based service, you can query many interesting details from within the instance: its public and private IP, name of its security group(s), region and availability zone, etc. The same applies to API keys: if you assign an IAM role to your EC2 instance, you can get the API credentials in your bootstrap script using a simple query:

$ curl http://169.254.169.254/iam/security-credentials/role-name

Note that 169.254.169.254 is the metadata service address that is the same for all EC2 instances.

5. Launching EC2 instances outside VPCs.

According to the release notes, new AWS accounts are now VPC-enabled by default, which means that every EC2 instance should be associated with a particular VPC at launch time. While VPC is one of the more complicated AWS features, launching EC2 instances inside VPC provides numerous benefits, particularly:
  • You can assign persistent static IP addresses that 'survive' stop and reboot operations. You can also assign multiple IPs and network interfaces to a single instance.
  • You get a more fine-grained control over the security configuration. In VPC, the security groups involve both egress and ingress filtering, compared to classic security groups where you can only configure ingress filtering.
  • You can run your instance on a single-tenant hardware.
  • You can launch resources in private subnets, which is particularly useful for database servers and  private ELBs.
So, if you're designing a new solution on an old AWS account, consider using VPC for all your instances. Probably the only case when you wouldn't want to do so is when you have a large legacy system built on top of EC2-Classic instances that would involve a lot of migration effort.

6. Performing port scanning or penetration testing without being authorized.

Doing such things is a violation of AWS Terms of Service. If you need to test your cloud applications for vulnerabilities, you should contact AWS support beforehand so that they would temporarily disable their intrusion detection systems for certain machines and services.

7. Using S3 ACL for managing access to S3 buckets.

Amazon S3 is one of the oldest AWS services. When it appeared on the market, there was no IAM yet. As a result, to manage access to S3 buckets, S3 implemented its own security mechanism, known as S3 ACLs. Nowadays, the preferred way of managing access to S3 is using IAM policies. Not only do they offer a more fine-grained control over access to S3 operations, but they also provide a unified way of managing access to other AWS services.

8. Involving your application servers for transferring data from browser to S3.

S3 supports direct browser-to-bucket uploads. All you need to do is generate a couple of hidden fields in the HTML to authenticate the client properly. If you define your form as <form enctype=“multipart/form-data">, the browser would even perform a multipart upload for large files.
Also, if you develop mobile applications that upload data to S3, you can use the AWS Security Token Service (STS) to generate temporary access keys for S3 and upload the data directly to buckets without proxying it through your servers.

9. Waiting for the EBS snapshot operation to complete before unfreezing the filesystem.

If you need to perform hot backups of your production environment, you must ensure that the backup captures the filesystem in a consistent state. To do this, you should freeze the filesystem (e.g., xfs_freeze) and then issue the snapshot creation command. However, you don't need to wait for the entire copying operation to finish before unfreezing the FS. Since the backup operation "captures a point in time", it only takes a matter of seconds for EBS services to capture the blocks that need to be persisted. Therefore, the right way would be to freeze the FS, issue the snapshot command, and then unfreeze the FS and expect the copy operation to be completed asynchronously. This helps you to ensure the minimum downtime of your environment.

10. Using On-Demand EC2 instances for every case.

An important aspect of designing solutions for the cloud is not only availability, scalability, security and fault-tolerance, but also cost-effectiveness. AWS provides you with a variety of cost-saving options under particular use cases. For example, if you expect to use a fixed amount of EC2 instances for a long period of time, consider using Reserved Instances. If you need a fleet of short-lived instances, outages of which can be tolerated, consider using Spot Instances (check out the blog post on Spot Instances by our engineer, Taras Kushnir). Choosing the right type of instance can make a dramatic improvement to the TCO of your infrastructure and you get a much bigger bang for your buck.

About the author: Yuriy Guts is an AWS Certified Solutions Architect with several years of experience with architecting cloud solutions for various companies across the globe. He is responsible for the cloud solutions stream at ELEKS R&D and specializes in AWS and Windows Azure.

11/04/2013

Getting more from the AWS: the spot instances (via SDK for .NET)

Intro

We have discussed basic principles of work with On-Demand instances of AWS web-services in the previous post. On-Demand instances are quite straightforward and have expected behaviour. But... what about something more stochastic and thus more interesting?

Amazon EC2 instance types

Amazon offers us several types of it's compute instances: on-demand, reserved and spot instances. One can read an article on the AWS website but to make long story short there are several types of instances:
  • On-Demand instances are fixed hourly rate mostly always available instances which are often used for applications which need some basic guarantees about start time of the instance
  • Reserved instances are instances, which we can (as it comes from their name) reserve for some period of time and they will be always available within this reserved time period
  • Spot instances are the most interesting kind of instances, because we act like auction player and set a price which we are willing to pay to run such an instance and if our bid beats other customers at the moment we are able to launch requested instances for some time period. If current spot price moves higher than our's, Amazon EC2 service shuts down our instance
More about Spot instances

Spot instances are kind of tricky instances which are not guaranteed to run when we request them. We have to place a bid and wait until it wins (if it will someday) in order to run a spot instance. To do this we can send spot instance request with our suggested price to Amazon EC2 service. Each request has a state which indicates if our bid won. Initially request has state "open". Our request’s state becomes "active" in case our bid won and we can see new running instances which are connected to our request with SpotInstanceRequestId property.

Describing spot requests

A DescribeSpotInstanceRequestsRequest is used to describe our spot requests state. We can query opened and active spot requests using filter property. For example, that is how one can query opened spot requests:

var describeSpotRequestsRequest = new DescribeSpotInstanceRequestsRequest();

describeSpotRequestsRequest.Filter.Add(new Filter(){Name="state", Value="open"});

var openedSpotInstanceRequests = ec2Client.DescribeInstances(describeSpotRequestsRequest);
var openedRequests =
openedSpotInstanceRequests.SpotInstanceRequest;


Running spot instances

To launch Spot instances we have to send RequestSpotInstances request and pass our price, maximum desirable spot instances number and usual launch parameters like image Id,  instance type, key pair name, security groups etc. If our price wins AWS will try to launch as many instances as it can limited by our desired maximum number.

var ec2Client = new AmazonEC2Client(accessKey, secretKey);
var spotRequest = new RequestSpotInstancesRequest();

spotRequest.SpotPrice = "2.0";
spotRequest.InstanceCount = maxInstancesCount;
spotRequest.LaunchSpecification = new LaunchSpecification() {ImageID = imageID};

var spotResponse = ec2Client.RequestSpotInstances(spotRequest);
var spotResult = spotResponse.RequestSpotInstancesResult;
var placedSpotRequests = spotResult.SpotInstanceRequest.Select(rq => rq.SpotInstanceRequestId);

Spot request can throw several exceptions, one of which is AmazonEC2Exception with ErrorCode “MaxSpotInstanceCountExceeded”. This exception means we requested more instances than our account allows us to launch.

Requesting spot instances can fail even not for our fault, but because Amazon is not able to provide us with such number of EC2 instances in our region at the moment. A “InsufficientInstanceCapacity” error code is thrown with AmazonEC2Exception in this case.

Requesting current spot price

It is useful to know the current price of spot instances when placing your own bid. AWS SDK has DescribeSpotPriceHistoryRequest for this purposes.

var ec2Client = new AmazonEC2Client(accessKey, secretKey);

var spotPriceHistoryRequest = new DescribeSpotPriceHistoryRequest();
spotPriceHistoryRequest.StartTime = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.000Z");
spotPriceHistoryRequest.EndTime = spotPriceHistoryRequest.StartTime;

var spotPriceHistoryResponse = ec2Client.DescribeSpotPriceHistory(spotPriceHistoryRequest);
var priceHistory = spotPriceHistoryResponse.DescribeSpotPriceHistoryResult.SpotPriceHistory;

var currentPrice = priceHistory.First().SpotPrice;


A note: as it is said in the official documentation: “You can view the Spot Price history over a period from one to 90 days based on the instance type, the operating system you want the instance to run on, the time period, and the Availability Zone in which it will be launched.”

Tagging spot instances

There is a problem with tagging of spot instances: we cannot tag them just after start, because we don’t know when they will start. But there is a simple workaround: when we place spot requests, we can tag them and when actual spot instances would be launched, we can match each running instance spot request id and get corresponding tags.

Stopping spot instances

To stop Spot instances we have to work with SpotInstanceRequest but not with the running spot instance itself just like when launching spot instances. CancelSpotInstanceRequestsRequest does the job with SpotInstanceRequest Id’s to stop in parameters.

var ec2Client = new AmazonEC2Client(accessKey, secretKey);

var cancelSpotRequestsRequest = new CancelSpotInstanceRequestsRequest();
cancelSpotRequestsRequest.SpotInstanceRequestId.Add(spotRequestId);

var cancelSpotInstancesResponse = ec2Client.CancelSpotInstanceRequests(cancelSpotRequestsRequest);
var cancelledSpotRequests = cancelSpotInstancesResponse.CancelSpotInstanceRequestsResult.CancelledSpotInstanceRequest.Select(csr => csr.SpotInstanceRequestId);


After the spot request is cancelled AWS shuts down corresponding Spot instance.

Conclusion

Spot instances service from Amazon is interesting, tricky yet powerful. It allows using Amazon unused capacities at a lower price. You can purchase these instances by placing a bid, which you are willing to pay for those instances and for the time your bid is highest, you get them. Spot instances are useful in a number of situations when losing partial work is acceptable like cost-driven workloads or application testing. They help you to save your money when used wisely.

11/01/2013

Google Glass Development without Glass



Here are the slides of my "Google Glass Development without Glass" presentation. As I promised, here is the follow-up blogpost with some code samples. If you haven't seen my presentation, I strongly suggest clicking through the slides!

0.Intro

Technologies emerge. Extremely. Wearable trend takes over the world. It seems like every week we start with articles about brand new devices, which would change our life! We've heard about lots of glasses, watches, wristbands, you name it. The most popular one is definitely Google Glass. Actually, it is Glass, who started this wearable hype!
You can just imagine, how all the wearbles can impact our daily and extreme activities. Check out, how we imagined that at eleks: https://glass.eleks.com/

From the other point of view, each new device brings new UX, SDKs and APIs. That's why we, developers, have to quickly adopt to the new techs. In this sense, Google Glass is a rather good device for developers. It runs the world-known Android OS. It just has an extremely strange UI and UX.

Google created a set of "best practices" of awesome Glassware. Actually, it can be applied to any wearble software:
  • Design for device -- know & test your device and it's abilities. 
  • Don't get in the way -- show the best data when users want it and be out of the way when they don't.
  • Keep it timely -- platform is the most effective when in-the-moment and up-to-date.
  • Avoid the unexpected -- surprising users with unexpected functionality is bad. On any platform.
Glass is different from the regular phone or tablet. The usual way of creating Android apps is through the Android SDK. Because of specific Glass's usage principles, Google introduced Mirror API. We'll dive into both of them later in the post.

1. Obtaining Glass

If you are among those 10000 people, who have Glass, you can skip this chapter. Unfortunately, that's just 0.000002% of the world's population. So, welcome Stranger to this amazing world of Glass hacking without Glass.



Hopefully, you have some Android device. Then, you can install Google Glass UI there (disclaimer: I've tried this with Nexus 7 tablet with 4.2.2 rom and it worked perfectly, but I can't guarantee it will work on other device). In short, Google Glass UI is just another Home screen provider for your Android. In order to set it up, follow these steps:
  1. Go to: https://github.com/zhuowei/Xenologer
  2. Download Glass APKs: https://github.com/zhuowei/Xenologer#install
  3. Install them as you usually install APKs from third-parties
  4. Follow steps at http://imgur.com/a/IBqFf to set up your "Nexus Glass"
  5. Say "ok glass, take a picture" and share your "woohoo-reaction" with the world #throughglass
You've obtained Glass. Now its time to hack!
Let's dive into Glass development with the help of our friend Mr. Bond. James Bond.
Once upon a time, he was in London. Somehow, he's got his Google Glass and enjoys the experience on a daily basis.

2. Example #1: Mirror API

If you are eager to try Mirror API out and don't want to mess with quick-start projects, I have a shortcut for you!
Let's try inserting a simple card into Glass Timeline:
  1. Go to: Google API Explorer --> Mirror API --> mirror.timeline.insert 
  2. Authorise via OAuth 2.0. Use Glass scopes:
    • https://www.googleapis.com/auth/glass.timeline
    • https://www.googleapis.com/auth/glass.location
  3. Populate request fields with values from the API.
  4. Execute request!
  5. Here's a link with some pre-populated data.
Now it's time to have even more fun! Let's try setting up demo-project.
  1. Set up a new project in https://code.google.com/apis/console
  2. Go to API Access, update project settings:
    1. Add to Redirect URIs: 
      • http://localhost:8080/oauth2callback
    2. Add to JavaScript origins: 
      • https://plusone.google.com
      • http://localhost:8080
      • https://mirror-api-playground.appspot.com (will be useful later) 
  3. Clone https://github.com/googleglass/mirror-quickstart-java
  4. Update file src/main/resources/oauth.properties with the values provided in Google API Access Console.
  5. mvn jetty:run it.
If everything goes smooth, you'll be able to authorize and have fun with your Glass Timeline! If you want to have even more fun with Mirror API, especially with Subscriptions to Location and Notifications, you should deploy your war to the real webserver. Google sends these updates only to https secured web-sites. For development purposes you can use provided ssl-proxy. Just modify MirrorClient#insertSubscription method.

3. Example #2: GDK

Update: Google recently released GDK Sneak Peak. Right now, when you try creating apps with it and running it on Nexus Glass, you'll get [INSTALL_FAILED_MISSING_SHARED_LIBRARY]. We're trying to find the way, to avoid that. As of now, there's no support for the official GDK Sneak Peak (auth, live cards, etc).


Google Glass is just another Android device with 640x360 screen (hello, screen fragmentation), Android 4.0.4, API level 15. Maybe, in the next releases of Glass, this will change. Now, when you want to port your existing Android app to Google Glass, you should just:
  1. Build your APK.
  2. Install it.
  3. Run via adb.
  4. Understand, that you need to update touch gestures support.
  5. Understand, that your UI is hardly usable.
  6. Understand, that your awesome Google Maps stopped working.
  7. So, double-check your application on real device! Everything can change in the near future!
It's a good idea to check out Google Glass Quick Start by Google. It explains a lot about Timeline, UI, Gestures and current limitations of the GDK.
In order to support touch gestures of Google Glass, have a look at this article: Touch Gestures. In short, here's the table with events corresponding to keycodes:
TapKEYCODE_DPAD_CENTER
Swipe rightKEYCODE_TAB
Swipe leftKEYCODE_TAB + isShiftPressed()
Swipe downKEYCODE_BACK
CameraKEYCODE_CAMERA

4. Example #3: GDK + Timeline API

Update: Google released GDKvXE12 update. It has Static Card support, but it is still limited and lacks menus, html templates, etc. The code mentioned below follows hacky way and may not work on the latest version of Glass.
So far, we've tried the official Mirror API way and the hacky GDK road. Now its time to combine both approaches. Let's insert a card into Timeline from withing your app!

I've  set up a sample project at github for you: https://github.com/pif/ukrbash-for-glass. After you fork/clone it, you can see glasslib.jar inside libs folder. This library would probably become the aforementioned GDK. It provides everything you need to know about Timeline UI.

All the magic is done via these steps:
  1. Initialise Timeline, get Timeline contentresolver. Look at:
    com.andrusiv.glass.bash.GlassService#onStartCommand(Intent, int, int).
  2. Create MenuItems for your card.
  3. Create TimelineItem.
  4. Insert it into ContentResolver.
Look through the classes & methods provided inside glasslib.jar. I hope, you'll find loads of interesting information!

5. Outro

Thanks everyone, for reading all the way down here. I hope now you have your pseudo-Glass and know how to develop for it. Share your experience in the comments and on github! Ok guys, have fun #throughglass!