It is very difficult to find a bug if we are using bugzilla. For e.g. visit this page...
https://bugzilla.mozilla.org/query.cgi
Choose "ALL" in status and "Socorro" in Product to search for a bug. The bug database is also accessible using API and the URL will look something like this...
https://bugzilla.mozilla.org/rest/bug?product=Socorro&component=Backend&include_fields=status,id,resolution,summary
We can programatically access this page using 4 lines of python code:
url='https://bugzilla.mozilla.org/rest/bug'
params={'product': u'Socorro', 'component': u'Backend', 'include_fields': 'status,id,resolution,summary'}
import requests
bugs=requests.get(url, params=params).json()
Let's try to add this bugs list to pandas dataframe.
import pandas as pd
pd.DataFrame(bugs)
This will create a row for each bug, but all the fields are merged into one. We need separate column for each one like status, id, title so that we can manage, sort and export data.
documents = []
for bug in bugs['bugs']:
documents.append({
'url': 'https://bugzilla.mozilla.org/show_bug.cgi?id={}'.format(bug['id']),
'title': bug['summary'],
'id': bug['id'],
'status': bug['status'],
'popularity': bug['id'],
'group': 'Socorro',
'resolution': bug['resolution']
})
We created a list of dictionaries called documents. This object can be imported in pandas without any problem.
import pandas as pd
pd.DataFrame(documents)
Once we have all the data, it can be easily exported to another service as shown here...
https://gist.github.com/shantanuo/f9f4a595b7bee10e1f36
Labels: pandas, python, usability
Lambda Function:
import boto3
client = boto3.resource('dynamodb')
table = client.Table('minfo')
def lambda_handler(event, context):
item = {
'marker': int(event['mar']),
'latitude': str(event['late']),
'longitude': str(event['long'])}
table.put_item(Item=item)
return event['mar']
Link the above lambda function name for e.g. "dyno" to the API gateway.
It is important to correctly specify the mapping for API get method execution request:
{
"mar": "$input.params('mar')",
"late": "$input.params('late')",
"long": "$input.params('long')"
}
Once deployed, the URL will look something like this...
https://t4pwupa9vc.execute-api.us-east-1.amazonaws.com/stag2/?mar=8&long=865&late=56
The latitude and longitude are saved to dynamoDB database with key as "mar".
Python code is short (10 lines) and readable. Creating API gateway takes a few minutes and the cost is minimum.
This can also be achieved by using the instructions found here...
https://aws.amazon.com/blogs/compute/using-amazon-api-gateway-as-a-proxy-for-dynamodb/
Labels: aws, aws_lambda, boto, usability
This lambda code will copy the given URL to S3
import boto3
import os
import urllib2
bucket = 'billingac'
s3 = boto3.resource('s3')
s3_client = boto3.client('s3')
def lambda_handler(event, context):
url = event['url']
key = os.path.basename(url)
response = urllib2.urlopen(url)
zipcontent= response.read()
with open("/tmp/log.zip", 'w') as f:
f.write(zipcontent)
s3_client.upload_file('/tmp/log.zip', bucket, key)
We can link this function to API gateway so that we can access it from the browser something like this...
https://12o3jwx4pi.execute-api.us-east-1.amazonaws.com/stag/?url=https://github.com/shantanuo/easyboto/archive/master.zip
https://12o3jwx4pi.execute-api.us-east-1.amazonaws.com/stag/?url=http://oksoft.blogspot.in/2016_01_01_archive.html
Labels: aws, aws_lambda
There are times when you need an email alert when-ever an instance is initiated or terminated from your account. There is an excellent blog post about how to do it.
https://aws.amazon.com/blogs/aws/new-cloudwatch-events-track-and-respond-to-changes-to-your-aws-resources/
Based on that post, I have written a python script that should be called lambda_function.py which should be uploaded to lambda along with requests module.
ip install requests -t .
cat lambda_function.py
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
import requests
import json
key = 'key-xxx'
sandbox = 'sandboxXXX.mailgun.org'
request_url = 'https://api.mailgun.net/v2/{0}/messages'.format(sandbox)
def lambda_handler(event, context):
logger.info('got event{}'.format(event))
myfile = '{}'.format(event)
import ast
myfile2 = ast.literal_eval(myfile)
myfile1=json.dumps(myfile2, indent=4, sort_keys=True)
recipient='xxx@gmail.com'
request = requests.post(request_url, auth=('api', key), data={
'from': 'xxx@gmail.com',
'to': recipient,
'subject': 'status alert',
'text': myfile1
})
Compress all the files along with sub-directories and then upload it to lambda.
zip -r myp.zip .
It has been explained in the blog post about how to create an event.
Labels: aws, aws_lambda
I can create an API that will take the current IP of requesting client and add that IP address to a security group to open up certain ports.
Integration request:
content-type: application/json
Template:
{
"sourceip": "$context.identity.sourceIp"
}
The lambda function will look something like this...
def lambda_handler(event, context):
from boto3.session import Session
session = Session(aws_access_key_id='XXX', aws_secret_access_key='YYY')
ec2 = session.resource('ec2')
security_group = ec2.SecurityGroup('sg-f682c78f')
myip=event['sourceip']+"/32"
security_group.authorize_ingress(IpProtocol="tcp",CidrIp=myip,FromPort=80,ToPort=80)
return (event['sourceip'])
Labels: aws, aws_lambda, boto, redshift, usability
Here is an API that will return the Mumbai Municipal ward name for a given location. For e.g. if you want to find in which ward does lat=19.1645972 and lon=72.8496286
https://291w32lbja.execute-api.us-east-1.amazonaws.com/stag/mward?lat=19.1645972&lon=72.8496286
The above page will correctly return P/S (p south ward). If you provide Nariman Point co-ordinates in the URL then it will return "A" ward as shown below...
https://291w32lbja.execute-api.us-east-1.amazonaws.com/stag/mward?lat=18.92&lon=72.83
The python code can be found here...
https://gist.github.com/shantanuo/05187dd23b96f5e92f6b
Labels: aws, aws_lambda
Here is an incomplete list of commands admins must be using frequently.
common commands:
cd, cp, file, cat, head, less more, tail, locate, ls, mkdir, mv, pwd, rm, rmdir, scp, ssh, wc, split, md5sum, date, man, clear, nice, nohup, passwd, screen, script, spell, su, find, grep (egrep, fgrep), strings, tar, gzip, gunzip, bzip2, bunzip2, cpio, zcat (gzcat), crontab,df, du, env, kill, ps, who, awk, sed, grep, cut, join, paste, sort, tr, uniq, vi, xargs , iconv, parallel
Example commands:
ln -s /tmp/mysql.sock /var/lib/mysql/mysqld.sock
chown mysql:mysql /var/lib/mysql/
chmod 700 nov15a.pem
Comparisons:
cmp Compare two files, byte by byte
comm COmpare items in two sorted files
diff compare two files, line by line
dircmp compare directories
sdiff Compare two files, side by side
Shell Programming:
basename
dirname
echo
expr
id
line
printf
sleep
test
Labels: linux tips
You can create Amazon Cloud API that will simply redirect to your own API hosted on your server.
1) Choose "Create API" link from API Gateway homepage. The "API name" can be something like circle_data.
2) Click on Create Resouce to add a URL resource for e.g. "getcircle"
3) Select the circle Resource and choose Create Method: GET
4) Select GET method and choose "HTTP Proxy" in Integration type. The endpoint URL will be your own server API. for e.g.
Endpoint URL: http://site.com/circle_info/InboundDetails.asmx/GetCallerDetails
5) Select GET method created in the last step and choose Method Request:
URL Query String Parameters: Add Query string:
destination
6) Select GET method again and then choose Integration Requst:
URL Query String Parameters: Add query string:
Name: destination
mapped from: method.request.querystring.destination
7) Click on Deploy API button:
Add a name for e.g. staging and save.
8) You will get Invoke URL something like this...
https://n10hs00rr8.execute-api.us-east-1.amazonaws.com/staging
After adding resource and query string (like circle?destination=1234567890) the final URL will look something like this...
https://x.execute-api.us-east-1.amazonaws.com/staging/getcircle?destination=1234567891
The advantage of building a cloud API on top of current in-house API are:
1) Security: You can hide your own URL and publish the Amazon URL
2) Amazon Provides API Cache so the requests are faster.
3) CloudWatch setting allows us to save request - response info that can help to debug and troubleshoot problems. It will also help us to log who is accessing data and from where.
4) Throttling settings allow us to manage high load.
Labels: aws
Here is an example how you can build simple hosted API services for anyone (free!) Let's assume you need to calculate the Equal Monthly Installment for a given loan amount. The user will send the amount, rate of interest and tenure in months. You should get back the monthly installment that the financial institution should charge. For e.g. if you pass the amount 7692 followed by interest rate 18% and repayment period of 12 months, you should get back 705.2 as shown here...
https://mh9zd7l5ak.execute-api.us-east-1.amazonaws.com/staging/int-cal?amt=7692&i=18&nper=12
We are using 2 services provided by Amazon.
1) API Gateway - This will generate a dynamic URL that will have the get method with all 3 variables.
2) Lambda - Python code that will actually do all the calculation.
1) API Gateway:
a) Method Execution - Get Method Request - URL Query String Parameters - add 3 variables i, amt and nper
b) Method Execution - Get Integration Request - Mapping Templates - Content-Type - application/json - Mapping template
{
"amt": "$input.params('amt')",
"i": "$input.params('i')",
"nper": "$input.params('nper')"
}
The above will link the variables received from the API gateway to the lambda function event dictionary.
2) Lambda function:
def lambda_handler(event, context):
amt=int(event['amt'])
i=int(event['i'])/100.0
nper=int(event['nper'])
i = i/12
i1 = i + 1
return round(amt*i1**nper*i/(i1**nper-1),2)
Since this function is only 7 lines and there are no external dependencies, we can directly copy - paste this function code. In other cases, you will beed to upload a zip file.
Labels: aws, aws_lambda
Here is a web service that will email the contents of the website. For e.g. I want the contents of webpage maharashtra times to be sent to shantanu.oak@gmail.com
https://t8hp2gl22l.execute-api.us-east-1.amazonaws.com/staging/sendmail?url=http://maharashtratimes.com&email=shantanu.oak@gmail.com
The API gateway Mapping template in this case will look something like this...
{
"url": "$input.params('url')",
"email": "$input.params('email')"
}
The lambda function code needs "requests" module. We can embed that module using the following command...
pip install requests -t /path/to/python_code/
The filename should be named "lambda_function.py" and the main function will be "lambda_handler"
import requests
import urllib2
def lambda_handler(event, context):
url = event['url']
if event['email']:
email=event['email']
else:
email='xxx@gmail.com'
url1 = urllib2.unquote(url)
myfile=urllib2.urlopen(url1)
print requests.post("https://api.mailgun.net/v3/sandboxxxx.mailgun.org/messages",
auth=("api", "key-1234"),
files=[("attachment", myfile)
#("attachment", open("files/test.txt"))
],
data={"from": "Excited User ",
"to": email,
#"cc": "YYY@yahoo.com",
#"bcc": "ZZZ@hotmail.com",
"subject": "Hello",
"text": "Testing some awesomness with attachments!",
"html": myfile})
You may need to increase the default timeout from 3 seconds to 1 minute because some sites may be slow and take more time to process. This can be done using Configuration - Advance Settings - Timeout. You can also increase the memory allocated to this function.
Labels: aws, aws_lambda
This is a simple AWS Lambda function that will check a website for it's content. If the dictionary response is not "Ok" then it will send an alert mail to the user.
def reportUser():
import requests
key = 'key-1234'
sandbox = 'sandbox.mailgun.org'
recipient = 'shantanu.oak@gmail.com'
request_url = 'https://api.mailgun.net/v2/{0}/messages'.format(sandbox)
request = requests.post(request_url, auth=('api', key), data={
'from': 'shantanu.oak@gmail.com',
'to': recipient,
'subject': 'status alert',
'text': 'done server status not ok at api.site.to:5000'
})
print 'Status: {0}'.format(request.status_code)
print 'Body: {0}'.format(request.text)
import urllib, json
def lambda_handler(event, context):
url = "http://api.site.to:5000/site-server-status"
response = urllib.urlopen(url)
data = json.loads(response.read())
if data['responseMsg'] == 'Ok':
return 'ok'
else:
reportUser()
return 'error'
Since this function is using "requests" module to send mails, we will need to embed that module as well in a zip file and upload the code to lambda. This lambda function should be called every 5 minutes just like cron. There is an option in "Event sources" to configure just that.
We do not need to use API gateway in this case because this is like cron application.
Labels: aws, aws_lambda