0% found this document useful (0 votes)
85 views3 pages

Empacar Py

The document defines functions for interacting with APIs to build and deploy artifacts to different environments. It parses command line arguments to initiate builds by authenticating with ATP and calling functions to start builds, get build status updates, and handle build completion.

Uploaded by

AF
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views3 pages

Empacar Py

The document defines functions for interacting with APIs to build and deploy artifacts to different environments. It parses command line arguments to initiate builds by authenticating with ATP and calling functions to start builds, get build status updates, and handle build completion.

Uploaded by

AF
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

#!

/usr/bin/env python3

import urllib, httplib2, json, time, sys, argparse

local = {'atp': "https://desa.atp.despexds.net", 'empacar':


"http://localhost:9000"}
team = {'atp': "https://desa.atp.despexds.net", 'empacar':
"http://backoffice.dev.despexds.net"}
dev = {'atp': "https://auth.despegar.com", 'empacar':
"http://backoffice.despegar.com"}
baprod = {'atp': "https://auth.despegar.com", 'empacar':
"http://backoffice.despegar.com"}
prod = {'atp': "https://auth.despexds.net", 'empacar': "http://backend-
cross.despexds.net"}
endpoints = {'local': local, 'team': team, 'dev': dev, 'prod': prod, 'baprod':
baprod}

atp = None
empacar = None
http = None

def console_url(buildId):
return "%s/empacar/build-console/%s" % (empacar, buildId)

def build_url(projectName, submodule, tag, scanBugs):


sm = ""
if submodule != "":
sm = "&submodule=%s" % submodule
return '%s/empacapi/build?projectName=%s&tag=%s%s&scanBugs=%s' % (empacar,
projectName, tag, sm, scanBugs)

def verification_url(buildId):
return "%s/empacapi/build/status/%s" % (empacar, buildId)

def init_endpoints(environment):
global empacar
empacar = endpoints[environment]['empacar']
global atp
atp = endpoints[environment]['atp']

def init_http_client(env):
global http
cacerts_file = '/etc/ssl/certs/ca-certificates.crt'
if env in ['team']:
cacerts_file = '/usr/local/utils/cgp-cert-%s.pem' % env
if env == 'local':
cacerts_file = '/usr/local/utils/cgp-cert-team.pem'

http = httplib2.Http(ca_certs = cacerts_file)

def authenticate(client_id, client_secret):


params = { 'grant_type': 'client_credentials', 'scope': 'openid empacar
cloudia', 'client_id': client_id, 'client_secret': client_secret }
url = atp + '/token'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}

response, content = http.request(url, 'POST',


body=urllib.parse.urlencode(params), headers=headers)
if response.status != 200:
print(content)
sys.exit("ATP3 login failed. url=" + url)
obj = json.loads(content.decode('utf-8'))
return obj['id_token']

def launch_build(jwt, projectName, submodule, tag, scanBugs):


headers = {'Authorization': 'Bearer ' + jwt}
url = build_url(projectName, submodule, tag, scanBugs)
response, content = http.request(url, 'POST', headers=headers)

if response.status != 200:
sys.exit("Failure creating build task in empacar (reason: %s)." %
content.decode("utf-8"))
return content.decode("utf-8")

def verify_build_status(jwt, project, tag, buildId):


headers = {'Authorization': 'Bearer ' + jwt}
url = verification_url(buildId)
response, content = http.request(url, 'GET', headers=headers)
if response.status == 200:
obj = json.loads(content.decode("utf-8"))
status = obj[u'status']
print("Current status: %s" % status.upper())
if status == u"completed":
print("Artifact published to: %s" % obj[u'artifactUrl'])
print("Deploy finish with status [%s]" % status.upper())
sys.exit()
if status == u"error" or status == u"cancelled":
sys.exit("Deploy finish with status [%s]. Check for details at %s" %
(status.upper(), console_url(buildId)))
else:
print("Error verifying state (response status code: %d)" % response.status)

def parsed_args():
parser = argparse.ArgumentParser(description='Create (build) an artifact using
Empacar API, and publish it to Despegar verified nexus')
parser.add_argument('-u', metavar='USR', type=str, help='ATP3 client id',
required=True)
parser.add_argument('-p', metavar='PASS', type=str, help='ATP3 client secret',
required=True)
parser.add_argument('-r', metavar='PROJECT', type=str, help='Project name',
required=True)
parser.add_argument('-t', metavar='TAG', type=str, help='Tag name',
required=True)
parser.add_argument('-s', metavar='SUBMODULE', type=str, help='Project
submodule (not required)', default="")
parser.add_argument('-l', metavar='ENV', type=str, help='Cloudia environment
[dev, prod] where this script runs', choices=["local", "team", "dev", "prod",
"baprod"], default="dev")
parser.add_argument('--skip-scan', dest='skip-scan', action='store_true',
help='Do NOT scan for security vulnerabilities')
return vars(parser.parse_args())

if __name__ == "__main__":
args = parsed_args()

print(args)
user = args['u']
password = args['p']

projectName = args['r']
submodule = args['s']
tag = args['t']

scanBugs = 0 if args['skip-scan'] else 1

environment = args['l']

init_endpoints(environment)
init_http_client(environment)

# ATP3 authentication
jwt = authenticate(user, password)

# Build
buildId = launch_build(jwt, projectName, submodule, tag, scanBugs)
print("Build task started in empacar. Check progress at %s" %
console_url(buildId))

# Verify build status


while True:
verify_build_status(jwt, projectName, tag, buildId)
time.sleep(5)

You might also like