Verified Commit 5be5c0b6 authored by Sebastian Schüpbach's avatar Sebastian Schüpbach
Browse files

use single quotes for strings

parent eb6c6cab
Pipeline #31978 passed with stages
in 2 minutes and 21 seconds
......@@ -10,7 +10,7 @@ from autodeploy_service_app.app import app
class AutoDeploy(Resource):
def post(self):
"""
'''
Deploy on k8s
---
tags:
......@@ -38,78 +38,78 @@ class AutoDeploy(Resource):
type: string
example: Unexpected Kafka error
"""
'''
status = "ignore"
body = ""
status = 'ignore'
body = ''
output = []
try:
body = json.loads(flaskRequest.data.decode("utf-8"))
tag = ""
branch = ""
if body["object_attributes"]["tag"]:
tag = body["object_attributes"]["ref"]
body = json.loads(flaskRequest.data.decode('utf-8'))
tag = ''
branch = ''
if body['object_attributes']['tag']:
tag = body['object_attributes']['ref']
else:
branch = body["object_attributes"]["ref"]
branch = body["object_attributes"]["ref"]
for stage in body["builds"]:
if stage["stage"] == "publish" and stage["status"] == "success":
projectName = body["project"]["path_with_namespace"].split("/")[-1]
repositoryUrl = body["project"]["git_http_url"]
repositoryPath = body["project"]["path_with_namespace"]
branch = body['object_attributes']['ref']
branch = body['object_attributes']['ref']
for stage in body['builds']:
if stage['stage'] == 'publish' and stage['status'] == 'success':
projectName = body['project']['path_with_namespace'].split('/')[-1]
repositoryUrl = body['project']['git_http_url']
repositoryPath = body['project']['path_with_namespace']
app.logger.info(
'deploy-request received from "' + repositoryUrl + '"'
'deploy-request received from '' + repositoryUrl + '''
)
app.logger.debug("removing workdir")
shutil.rmtree("autodeploy-workdir/", ignore_errors=True)
app.logger.debug('removing workdir')
shutil.rmtree('autodeploy-workdir/', ignore_errors=True)
# if tag = semver: deploy on prod+stage
if re.match(r"^(([0-9]+)\.([0-9]+)\.([0-9]+))$", tag):
if re.match(r'^(([0-9]+)\.([0-9]+)\.([0-9]+))$', tag):
app.logger.debug(
"commit with semver-tag detected: installing on prod+stage"
'commit with semver-tag detected: installing on prod+stage'
)
pullChartUri = (
os.environ["GITLAB_REGISTRY"]
+ "/"
os.environ['GITLAB_REGISTRY']
+ '/'
+ repositoryPath
+ ":"
+ ':'
+ tag
+ "-chart"
+ '-chart'
)
msgs, status = installFromRepo(pullChartUri, projectName)
output.extend(msgs)
# deploy on test
elif branch == "master":
elif branch == 'master':
app.logger.debug(
"commit on master without semver-tag detected: installing on test"
'commit on master without semver-tag detected: installing on test'
)
msgs, status = installFromDir(repositoryUrl, projectName)
output.extend(msgs)
except subprocess.CalledProcessError as ex:
msg = "command {} failed with return code {} -- STDOUT: {} -- STDERR: {}".format(
msg = 'command {} failed with return code {} -- STDOUT: {} -- STDERR: {}'.format(
ex.cmd, ex.returncode, ex.stdout, ex.stderr
)
output.append(msg)
status = "failure"
status = 'failure'
app.logger.warning(msg)
except json.JSONDecodeError as ex:
msg = "the json in the body could not be decoded: {}".format(str(ex))
msg = 'the json in the body could not be decoded: {}'.format(str(ex))
output.append(msg)
status = "failure"
status = 'failure'
app.logger.warning(msg)
except Exception as ex:
msg = "an exception occured: {}".format(str(ex))
msg = 'an exception occured: {}'.format(str(ex))
output.append(msg)
status = "failure"
status = 'failure'
app.logger.warning(msg)
returnVal = {"status": status, "log": output, "body": body}
if status == "success":
returnVal = {'status': status, 'log': output, 'body': body}
if status == 'success':
app.logger.info(json.dumps(returnVal))
return returnVal, 200
elif status == "ignore":
elif status == 'ignore':
app.logger.debug(json.dumps(returnVal))
return returnVal, 500
else:
......@@ -119,70 +119,70 @@ class AutoDeploy(Resource):
def _upgrade_installation(chartsDir, projectName, filenameBase, filename=None):
app.logger.debug(
"upgrading new deployment for {}{}".format(
projectName, "" if filename is None else ": " + filename
'upgrading new deployment for {}{}'.format(
projectName, '' if filename is None else ': ' + filename
)
)
try:
cmd = "helm upgrade -i {}-deployment {}{}".format(
cmd = 'helm upgrade -i {}-deployment {}{}'.format(
filenameBase,
""
''
if filename is None
else "-f " + chartsDir + "/helm-values/" + filename + " ",
else '-f ' + chartsDir + '/helm-values/' + filename + ' ',
chartsDir,
)
proc = subprocess.run(
cmd, shell=True, capture_output=True, text=True, check=True
)
app.logger.info(
"successfully installed helm chart{}".format(
"" if filename is None else " with " + filename
'successfully installed helm chart{}'.format(
'' if filename is None else ' with ' + filename
)
)
return (
"installing {}-deployment\n{}\n{}".format(
'installing {}-deployment\n{}\n{}'.format(
filenameBase, proc.stdout, proc.stderr
),
"success",
'success',
)
except subprocess.CalledProcessError as ex:
msg = "upgrading helm chart failed with return code {} -- STDOUT: {} -- STDERR: {}".format(
msg = 'upgrading helm chart failed with return code {} -- STDOUT: {} -- STDERR: {}'.format(
ex.returncode, ex.stdout, ex.stderr
)
app.logger.warning(msg)
return msg, "failure"
return msg, 'failure'
def installFromRepo(pullChartUri, projectName):
output = []
status = ""
app.logger.debug("pulling helm charts")
status = ''
app.logger.debug('pulling helm charts')
try:
proc = subprocess.run(
"export HELM_EXPERIMENTAL_OCI=1 && helm chart pull " + pullChartUri,
'export HELM_EXPERIMENTAL_OCI=1 && helm chart pull ' + pullChartUri,
shell=True,
capture_output=True,
text=True,
check=True,
)
output.append(
"pulling charts from {}: {} (stderr: {})".format(
'pulling charts from {}: {} (stderr: {})'.format(
pullChartUri, proc.stdout, proc.stderr
)
)
except subprocess.CalledProcessError as ex:
msg = "pulling helm chart failed with return code {} -- STDOUT: {} -- STDERR: {}".format(
msg = 'pulling helm chart failed with return code {} -- STDOUT: {} -- STDERR: {}'.format(
ex.returncode, ex.stdout, ex.stderr
)
app.logger.warning(msg)
return output, "failure"
pulledChartsDir = os.getcwd() + "/autodeploy-workdir/pulled-helm-charts/"
app.logger.debug("exporting helm charts")
return output, 'failure'
pulledChartsDir = os.getcwd() + '/autodeploy-workdir/pulled-helm-charts/'
app.logger.debug('exporting helm charts')
try:
proc = subprocess.run(
"export HELM_EXPERIMENTAL_OCI=1 && helm chart export "
'export HELM_EXPERIMENTAL_OCI=1 && helm chart export '
+ pullChartUri
+ " -d "
+ ' -d '
+ pulledChartsDir,
shell=True,
capture_output=True,
......@@ -190,22 +190,22 @@ def installFromRepo(pullChartUri, projectName):
check=True,
)
output.append(
"exporting charts to local directory: {} (stderr: {})".format(
'exporting charts to local directory: {} (stderr: {})'.format(
proc.stdout, proc.stderr
)
)
except subprocess.CalledProcessError as ex:
msg = "exporting helm chart failed with return code {} -- STDOUT: {} -- STDERR: {}".format(
msg = 'exporting helm chart failed with return code {} -- STDOUT: {} -- STDERR: {}'.format(
ex.returncode, ex.stdout, ex.stderr
)
app.logger.warning(msg)
return output, "failure"
return output, 'failure'
pulledChartsDir += projectName
if os.path.exists(pulledChartsDir + "/helm-values"):
app.logger.debug("helm value files detected")
for filename in os.listdir(pulledChartsDir + "/helm-values/"):
if os.path.exists(pulledChartsDir + '/helm-values'):
app.logger.debug('helm value files detected')
for filename in os.listdir(pulledChartsDir + '/helm-values/'):
filenameBase = os.path.splitext(filename)[0]
if "-prod." in filename or "-stage." in filename:
if '-prod.' in filename or '-stage.' in filename:
msg, status = _upgrade_installation(
pullChartUri, projectName, filenameBase, filename
)
......@@ -215,33 +215,33 @@ def installFromRepo(pullChartUri, projectName):
def installFromDir(repositoryUrl, projectName):
output = []
status = ""
app.logger.debug("cloning repository")
status = ''
app.logger.debug('cloning repository')
try:
proc = subprocess.run(
"git clone " + repositoryUrl + " autodeploy-workdir/",
'git clone ' + repositoryUrl + ' autodeploy-workdir/',
shell=True,
capture_output=True,
text=True,
check=True,
)
output.append(
"git clone {}: {} (stderr: {})".format(
'git clone {}: {} (stderr: {})'.format(
repositoryUrl, proc.stdout, proc.stderr
)
)
except subprocess.CalledProcessError as ex:
msg = "cloning git repo failed with return code {} -- STDOUT: {} -- STDERR: {}".format(
msg = 'cloning git repo failed with return code {} -- STDOUT: {} -- STDERR: {}'.format(
ex.returncode, ex.stdout, ex.stderr
)
app.logger.warning(msg)
return output, "failure"
chartsDir = os.getcwd() + "/autodeploy-workdir/helm-charts"
if os.path.exists(chartsDir + "/helm-values"):
app.logger.debug("helm value files detected")
for filename in os.listdir(chartsDir + "/helm-values/"):
return output, 'failure'
chartsDir = os.getcwd() + '/autodeploy-workdir/helm-charts'
if os.path.exists(chartsDir + '/helm-values'):
app.logger.debug('helm value files detected')
for filename in os.listdir(chartsDir + '/helm-values/'):
filenameBase = os.path.splitext(filename)[0]
if "-test." in filename:
if '-test.' in filename:
msg, status = _upgrade_installation(
chartsDir, projectName, filenameBase, filename
)
......
NAMESPACE = "memobase"
NAMESPACE = 'memobase'
......@@ -20,53 +20,53 @@ except BaseException:
# for local development
config.load_kube_config()
except BaseException:
app.logger.error("No kubernetes cluster defined")
app.logger.error('No kubernetes cluster defined')
# If app is started via gunicorn
if __name__ != "__main__":
gunicorn_logger = logging.getLogger("gunicorn.error")
if __name__ != '__main__':
gunicorn_logger = logging.getLogger('gunicorn.error')
app.logger.handlers = gunicorn_logger.handlers
app.logger.setLevel(gunicorn_logger.level)
app.logger.removeHandler(default_handler)
app.logger.info("Starting production server")
app.logger.info('Starting production server')
api = Api(app)
app.config["SWAGGER"] = {
"title": "autodeploy-service",
"version": "dev",
"uiversion": 3,
"termsOfService": "http://memobase.ch/de/disclaimer",
"description": "service to deploy on k8s form a gitlab webhook",
"contact": {
"name": "UB Basel",
"url": "https://ub.unibas.ch",
"email": "swissbib-ub@unibas.ch",
app.config['SWAGGER'] = {
'title': 'autodeploy-service',
'version': 'dev',
'uiversion': 3,
'termsOfService': 'http://memobase.ch/de/disclaimer',
'description': 'service to deploy on k8s form a gitlab webhook',
'contact': {
'name': 'UB Basel',
'url': 'https://ub.unibas.ch',
'email': 'swissbib-ub@unibas.ch',
},
"favicon": "/favicon.ico",
'favicon': '/favicon.ico',
}
Swagger(app)
@app.route("/")
@app.route('/')
def home():
return redirect("/apidocs")
return redirect('/apidocs')
@app.route("/favicon.ico")
@app.route('/favicon.ico')
def favicon():
return send_from_directory(
os.path.join(app.root_path, "assets"),
"favicon.ico",
mimetype="image/vnd.microsoft.icon",
os.path.join(app.root_path, 'assets'),
'favicon.ico',
mimetype='image/vnd.microsoft.icon',
)
api.add_resource(AutoDeploy, "/v1/autodeploy")
api.add_resource(AutoDeploy, '/v1/autodeploy')
# If app is started with Flask
if __name__ == "__main__":
logging.basicConfig(format="%(levelname)-8s [%(filename)s:%(lineno)d] %(message)s")
app.logger.info("Starting development server")
app.run(host="0.0.0.0", port=5000, debug=True)
if __name__ == '__main__':
logging.basicConfig(format='%(levelname)-8s [%(filename)s:%(lineno)d] %(message)s')
app.logger.info('Starting development server')
app.run(host='0.0.0.0', port=5000, debug=True)
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment