Created
March 7, 2016 18:02
-
-
Save bGorle/2a0eda470a417a840526 to your computer and use it in GitHub Desktop.
Jenkins python script to build the job and getting the apk from the build
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from jenkinsapi.jenkins import Jenkins | |
import requests | |
from requests.auth import HTTPBasicAuth | |
import json | |
import datetime | |
from giturlparse import parse | |
import base64 | |
import time | |
from jenkinsapi.queue import QueueItem | |
from jenkinsapi.job import Job | |
import pprint | |
import send_mail | |
jobs_data = [] | |
def get_todays_commits(job): | |
url = "https://bitbucket.org/api/1.0/repositories/group_name/{}/changesets".format(job['repo_slug']) | |
r = requests.get(url, auth=HTTPBasicAuth('user_name', "password")) | |
changesets = json.loads(r.text) | |
try: | |
cs_size = len(changesets['changesets']) | |
time = changesets['changesets'][cs_size - 1]['utctimestamp'] | |
last_commit_day = datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S+00:00').date().day | |
today_date = datetime.date.today() | |
print today_date.day | |
print last_commit_day | |
if(last_commit_day == today_date.day): | |
commit_info = [] | |
for changeset in changesets['changesets']: | |
ch_time = changeset['utctimestamp'] | |
ch_date = datetime.datetime.strptime(ch_time, '%Y-%m-%d %H:%M:%S+00:00').date().day | |
if today_date.day == ch_date: | |
commit_info.append(changeset['message']) | |
job['commit_info'] = commit_info | |
return True | |
except KeyError: | |
return False | |
return False | |
def get_server_instance(): | |
jenkins_url = 'http://jenkins_host' | |
server = Jenkins(jenkins_url, username = 'user_name', password='ce4e6e284c3a65bdcfd9659d502b018d') | |
return server | |
###"""Get job details of each job that is running on the Jenkins instance""" | |
def get_job_details(): | |
# Refer Example #1 for definition of function 'get_server_instance' | |
server = get_server_instance() | |
print server.version | |
for j in server.get_jobs(): | |
print j | |
job_instance = server.get_job(j[0]) | |
print 'Job Name:%s' %(job_instance.name) | |
print 'Job Description:%s' %(job_instance.get_description()) | |
print 'Is Job running:%s' %(job_instance.is_running()) | |
print 'Is Job enabled:%s' %(job_instance.is_enabled()) | |
print 'SCM url:%s' %(job_instance.get_scm_url()) | |
def check_job_status(job_instance): | |
print "build is running" + str(job_instance.is_running()) | |
if job_instance.is_running(): | |
return True | |
else: | |
return False | |
if __name__ == '__main__': | |
# print get_server_instance().version | |
# get_job_details() | |
jenkins_server = get_server_instance() | |
for j in jenkins_server.get_jobs(): | |
job_instance = jenkins_server.get_job(j[0]) | |
p = parse(job_instance.get_scm_url()[0]) | |
job = {} | |
job['name'] = job_instance.name | |
job['repo_slug'] = p.repo | |
job['to_addr'] = ["[email protected]"] | |
job['cc'] = cc = ["[email protected]"] | |
if get_todays_commits(job): | |
print "Running build for " + job_instance.name | |
#jenkins_server.pprint() | |
#print jenkins_server.get_data(job_instance.) | |
jenkins_server.build_job(job_instance.name) | |
time.sleep(10) | |
while(check_job_status(job_instance)): | |
print "came" | |
time.sleep(60) | |
#pprint.pprint( job_instance._data ) | |
gen = job_instance.get_last_completed_build().get_artifacts() | |
filepath = "/opt/{}.apk".format(p.repo) | |
for g in gen: | |
print type(g) | |
print g._do_download(filepath) | |
send_mail.smtp_send("Daily build {} apk".format(p.repo), filepath, job['to_addr'],job['cc'], job['commit_info']) | |
else: | |
print "No build for " + job_instance.name | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python2.7 | |
import json | |
import requests | |
import time | |
import datetime | |
from time import gmtime, strftime | |
from smtplib import SMTP | |
from email.MIMEMultipart import MIMEMultipart | |
from email.MIMEBase import MIMEBase | |
from email.MIMEText import MIMEText | |
from email import Encoders | |
import shutil | |
from pytz import timezone | |
to_addr = ["[email protected]"] | |
cc = ["[email protected]"] | |
debuglevel = 0 | |
def smtp_send(subject, attachment,to_addr=to_addr, cc=cc, extra_info=[]): | |
smtp = SMTP() | |
smtp.set_debuglevel(debuglevel) | |
smtp.connect('mail_host', 587) | |
smtp.login('[email protected]', 'password') | |
from_addr = "Bharath<[email protected]>" | |
subj = subject | |
msg = MIMEMultipart('mixed') | |
msg['Subject'] = subj | |
msg['From'] = from_addr | |
msg['To'] = ', '.join(to_addr) | |
msg['Cc'] = ', '.join(cc) | |
# The main body is just another attachment | |
fmt = "%d %b %Y, %H:%M" | |
now_utc = datetime.datetime.now(timezone('UTC')) | |
now_india = now_utc.astimezone(timezone('Asia/Kolkata')) | |
message_text = "Hello,\nThis is your latest application file for your project. Built on {}\n\n".format(now_india.strftime(fmt)) | |
message_text += "\n\nIssues resloved: \n\n" | |
for idx, val in enumerate(extra_info): | |
message_text += str(idx + 1) + "." + val | |
#message_text += '\n '.join(extra_info) | |
body = MIMEText(message_text) | |
msg.attach(body) | |
#msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, message_text ) | |
part = MIMEBase('application', "octet-stream") | |
part.set_payload(open(attachment, "rb").read()) | |
Encoders.encode_base64(part) | |
part.add_header('Content-Disposition', 'attachment; filename="apk-debug.apk"') | |
msg.attach(part) | |
#to_addrs = [to_addr] + cc | |
x = smtp.sendmail(from_addr, to_addr+cc, msg.as_string()) | |
smtp.quit() | |
def sendmail(msg, attachment): | |
now = datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S") | |
print "Sending email for server {} at {}".format(msg, now) | |
smtp_send(msg, attachment) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment