In web development we have to deal with different environments when developing, testing and deploying our websites or applications. This way of doing things is very useful because it lets you show new features or changes to the client without changing anything on the live, stable site. You, as a developer, would first push that new shiny feature to a “development” Elastic Compute Service (ECS) instance to see if what you built works. Then, after a couple of iterations polishing all, everything would go to the “staging” site. The so-called “staging” site it’s a full but independent copy of the production environment as well as the database. Pushing code to a “staging” instance is a good idea because it serves as a very powerful platform for real QA. It replicates exactly what is in production.
This means having an ECS instance for production, another for development preview and another one for staging (and potentially more, depending on your workflow). That makes 3 instances (or more) running 24 hours, this is, 168 hours per week per instance. With all the associated costs.
With a serverless solution like Alibaba Cloud Function Compute, you can power-schedule the instances you don’t use outside work hours. In this case, both staging and development. If we only need an ECS from 9AM to 5PM during weekdays, means that, instead of 168 hours per week the instances are going to be working only 40. That’s more than 76% in savings per instance!
Okay, now that I got your attention, let’s dive into the details of Function Compute.
What Is Function Compute?
I’m sure you heard the concept of “serverless”, it’s all over the place this days. Well, this is all about it.
According to Alibaba Cloud, Function Compute is “A fully hosted and serverless running environment that takes away the need to manage infrastructure such as servers and enables developers to focus on writing and uploading code”. It’s as good as it sounds. You can upload a piece of code, invoke it with a payload and get some output. You will pay only for the memory and the time it uses, which it makes it very cost-effective. There is no maintenance associated, auto-scales within milliseconds and is extremely flexible. You can upload code in your favorite programming language as it currently supports Python (2.7 & 3), Nodejs (6 & 8), Java 8 and PHP 7. About pricing, the first 1 million calls per month are free of charge, as well as the first 400,000 GB-seconds.
For our example we will use the built-in JavaScript aliyun-sdk
package to manage our resources, running on Nodejs 8. If you feel more comfortable coding in Python, Java or PHP the examples shown below are easily adaptable, as Alibaba Cloud provides SDKs in all that languages as well.
Creating the First Service
To write our functions, we first need to create what is called a “Service”. A Service is what is used in Function Compute to organize and govern functions. All the functions in a given Service will share the same setup as logging preferences and authorizations.
Once logged in the console, go to the Function Compute Dashboard and choose your preferred region. To add the new service, click on the “Create Service” button on the right side of the screen. In this tutorial we will use “PowerSchedule” as name. Because we are going to manage ECS instances, you will need to activate “Advanced Settings”.
In Advanced Settings select the VPC, VSwitch and Security Group related to the instance you want to manage. In order to enable the VPC feature, you will need to grant permissions to Function Compute via Roles. If this is the first time you work with Roles, select “Create new role” under “Role Operation” and “AliyunECSFullAccess” under “System Policies”. You could fine-tune this a bit more, but for this example lets click on “Authorize”. A new window will open to confirm the Policy, where we will click “Confirm Authorization Policy”. Back on the creation of the service, a confirmation message will appear, and we then could click “OK” to finish this stage. Our Service is ready to be used.
Get Alibaba Cloud Access Keys
Again, from your Alibaba Cloud console, go to the top Menu and click “AccessKey” located directly under your email address.
Once in the keys screen, copy the Access Key ID and the Access Key Secret into a safe place. To show the Secret Key to need to click on “Show”. Be careful where you save this data, as it is very sensitive. And, as said before, this should be fine-tuned to make the best of Roles and Policies.
Creating the ‘StopInstance’ Function
There we go, let’s create our first function. This one will stop the instance we want at the time of the day we want. As we are using Nodejs, we can write modern JavaScript like in the example below:
const ALY = require('aliyun-sdk')
const accessKeyId = '_accessKeyId_'
const secretAccessKey = '_secretAccessKey_'
exports.handler = (event, context, callback) => {
const {payload} = JSON.parse(event)
const {action, args} = payload
const ecs = new ALY.ECS({
accessKeyId,
secretAccessKey,
endpoint: 'https://ecs.aliyuncs.com',
apiVersion: '2014-05-26',
})
ecs.stopInstance(args, callback)
}
As you can see, it loads the SDK with the ECS API and executes the “stopInstance” function. You guessed right, this function triggers the underlying “StopInstance” API action.
Like every function in Function Compute, it has a “handler” and a “callback”, important pieces in this service.
Click “Next”, under “Permission Configuration” select again “AliyunECSFullAccess” and hit “Authorize”. Then, in the new window “Confirm Authorization Policy”. From here, just follow the on-screen steps, and you are done!
Creating the ‘StartInstance’ Function
This function it’s almost the same as “StopInstance” with a small difference, it executes the “startInstance” function. Repeat all the steps from the last one.
const ALY = require('aliyun-sdk')
const accessKeyId = '_accessKeyId_'
const secretAccessKey = '_secretAccessKey_'
exports.handler = (event, context, callback) => {
const {payload} = JSON.parse(event)
const {action, args} = payload
const ecs = new ALY.ECS({
accessKeyId,
secretAccessKey,
endpoint: 'https://ecs.aliyuncs.com',
apiVersion: '2014-05-26',
})
ecs.startInstance(args, callback)
}
Function Compute Event Triggers
In essence, Function Compute is an event-driven compute service. To make all this work, we need to set up the event triggers. An event can include any data as long as is in JSON format. Considering that we want to power-schedule an instance, the option we will take here is “Time Trigger”, a trigger we can schedule using cron expressions and providing a payload.
To create our first trigger, open the newly created “StartInstance” function and go to the tab named “Triggers” next to “Code” and click “Create Trigger”. As we said, select “Time Trigger” in the dropdown and use the following JSON as payload. To keep things simple, the payload will only contain the ID of the instance we want to manage.
Note that, for payload testing, we should create the following event:
{
"payload": "i-p0w0wvamtl4mtf97zlld"
}
In the example before, we said the instance was going to run from 9AM to 5PM, so the cron expression here will be 0 0 9 ? * MON-FRI
. And 0 0 17 ? * MON-FRI
for “StopInstance”. Note that Cron will run on UTC times.
As you can see, Alibaba Cloud Function Compute gives you a lot of freedom to write whatever you want and with the programming language you love. In this case we manage resources, but you can add the logic of your preference to perform normal tasks for your own application. A great use-case is to create APIs, as you could expose the functions to a publicly accessible URL.