#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Florian Lambert <florian.lambert@cycloid.io>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import sys
import argparse
import logging as log
import json
import requests
import yaml

VERSION = '1.0'

PARSER = argparse.ArgumentParser(description='Refresh pipeline Cycloid.io')

PARSER.add_argument("-u", "--username",
                    required=True,
                    type=str,
                    help='Username')
PARSER.add_argument("-p", "--password",
                    required=True,
                    type=str,
                    help='Password')
PARSER.add_argument("-t", "--pipeline-template",
                    required=True,
                    type=argparse.FileType('r'),
                    help='Pipeline-template yml file')
PARSER.add_argument("-v", "--pipeline-variables",
                    required=True,
                    type=argparse.FileType('r'),
                    help='Pipeline-variables yml file')
PARSER.add_argument("-o", "--organization",
                    required=True,
                    type=str,
                    help='Organization name')
PARSER.add_argument("-P", "--pipeline-name",
                    required=True,
                    type=str,
                    help='Pipeline_name (Usually $project-$env)')
PARSER.add_argument("-a", "--api-url",
                    type=str,
                    help='Cycloid api url name',
                    default='https://http-api.cycloid.io')
PARSER.add_argument("--version", action='store_true',
                    help='Print script version')
ARGS = PARSER.parse_args()


def login(apilogin, api_password, api_url, organization):
    payload = {'email': apilogin, 'password': api_password}
    headers = {'content-type': 'application/vnd.cycloid.io.v1+json'}

    try:
        # Get user token
        r = requests.post('%s/user/login' % (api_url), data=json.dumps(payload), headers=headers)
        user_token = r.json().get('data').get('token')
        # Get org token
        headers['Authorization'] = 'Bearer %s' % user_token
        r = requests.get('%s/user/refresh_token?organization_canonical=%s' % (api_url, organization), headers=headers)
        return r.json().get('data').get('token')
    except:
        log.error("There is an error on login, please check your configuration - %s" % r.text)
        exit(1)


def update_pipeline(api_url, token, organization, pipeline_name, pipeline_template, pipeline_variables):
    try:
        y_pipe=yaml.safe_load(pipeline_template)
        y_vars=yaml.safe_load(pipeline_variables)
    except yaml.YAMLError as exc:
        print(exc)

    data = {
        "passed_config": json.dumps(y_pipe),
        "yaml_vars": json.dumps(y_vars)
    }
    headers = {
        'content-type': 'application/vnd.cycloid.io.v1+json',
        'Authorization':'Bearer %s' % token
    }

    r = requests.put('%s/organizations/%s/pipelines/%s' % (api_url, organization, pipeline_name),
                     data=json.dumps(data), headers=headers)
    log.debug(r.text)
    if r.status_code != 200:
        log.error("Unable pipeline : %s" % r.text)
        exit(1)


if __name__ == "__main__":

    if ARGS.version:
        print "version: %s" % (VERSION)
        sys.exit(0)

    token = login(ARGS.username, ARGS.password, ARGS.api_url, ARGS.organization)
    update_pipeline(api_url=ARGS.api_url,
                    token=token,
                    organization=ARGS.organization,
                    pipeline_name=ARGS.pipeline_name,
                    pipeline_template=ARGS.pipeline_template,
                    pipeline_variables=ARGS.pipeline_variables)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114