Skip to content

Commit 2eee77a

Browse files
committed
Initial commit
0 parents  commit 2eee77a

File tree

10 files changed

+331
-0
lines changed

10 files changed

+331
-0
lines changed

.gitignore

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
build
2+
dist
3+
*.egg-info
4+
*.pyc

LICENSE.txt

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
Copyright 2015-2016 Trainline.com Ltd
2+
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
7+
http://www.apache.org/licenses/LICENSE-2.0
8+
9+
Unless required by applicable law or agreed to in writing, software
10+
distributed under the License is distributed on an "AS IS" BASIS,
11+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
See the License for the specific language governing permissions and
13+
limitations under the License.

NOTICE.txt

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Environment Manager
2+
Copyright Trainline Limited, 2016

contributors/ContributorAgreement.txt

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
Contributor Agreement
2+
Thank you for your interest in Trainline. In order to clarify the intellectual property license granted with code contributions from any person or entity, Trainline.com Limited ("Trainline") requires a Contributor License Agreement on file that has been signed by each contributor, indicating agreement to the license terms below. This license is for your protection as a Contributor as well as the protection of Trainline and its users; it does not change your rights to use your own contributions for any other purpose.
3+
Please send confirmation that you accept the terms set out below to [email protected]. Please read the terms carefully before accepting and keep a copy for your records.
4+
You accept and agree to the following terms and conditions for Your present and future Contributions submitted to Trainline. Except for the license granted herein to Trainline and recipients of software distributed by Trainline, You reserve all right, title, and interest in and to Your Contributions.
5+
6+
1. Definitions.
7+
"You" (or "Your") shall mean the copyright owner or legal entity authorized by the copyright owner that is making this Agreement with Trainline. For legal entities, the entity making a Contribution and all other entities that control, are controlled by, or are under common control with that entity are considered to be a single Contributor. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty per cent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
8+
"Contribution" shall mean any original work of authorship, including any modifications or additions to an existing work, that is intentionally submitted by You to Trainline for inclusion in, or documentation of, any of the products owned or managed by Trainline (the "Work"). For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to Trainline or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, Trainline for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by You as "Not a Contribution."
9+
2. Grant of Copyright License. Subject to the terms and conditions of this Agreement, You hereby grant to Trainline and to recipients of software distributed by Trainline a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute Your Contributions and such derivative works.
10+
3. Grant of Patent License. Subject to the terms and conditions of this Agreement, You hereby grant to Trainline and to recipients of software distributed by Trainline a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by You that are necessarily infringed by Your Contribution(s) alone or by combination of Your Contribution(s) with the Work to which such Contribution(s) was submitted. If any entity institutes patent litigation against You or any other entity (including a cross-claim or counterclaim in a lawsuit) alleging that your Contribution, or the Work to which you have contributed, constitutes direct or contributory patent infringement, then any patent licenses granted to that entity under this Agreement for that Contribution or Work shall terminate as of the date such litigation is filed.
11+
4. You represent that you are legally entitled to grant the above license. If your employer(s) has rights to intellectual property that you create that includes your Contributions, you represent that you have received permission to make Contributions on behalf of that employer, that your employer has waived such rights for your Contributions to Trainline, or that your employer has executed a separate agreement with Trainline.
12+
5. You represent that each of Your Contributions is Your original creation (see section 7 for submissions on behalf of others). You represent that Your Contribution submissions include complete details of any third-party license or other restriction (including, but not limited to, related patents and trademarks) of which you are personally aware and which are associated with any part of Your Contributions.
13+
6. You are not expected to provide support for Your Contributions, except to the extent You desire to provide support. You may provide support for free, for a fee, or not at all. Unless required by applicable law or agreed to in writing, You provide Your Contributions on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE.
14+
7. Should You wish to submit work that is not Your original creation, You may submit it to Trainline separately from any Contribution, identifying the complete details of its source and of any license or other restriction (including, but not limited to, related patents, trademarks, and license agreements) of which you are personally aware, and conspicuously marking the work as "Submitted on behalf of a third-party: [named here]".
15+
8. You agree to notify Trainline of any facts or circumstances of which you become aware that would make these representations inaccurate in any respect.
16+
17+
Please sign: __________________________________ Date: ________________

contributors/MarcCluet.txt

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
Contributor Agreement
2+
Thank you for your interest in Trainline. In order to clarify the intellectual property license granted with code contributions from any person or entity, Trainline.com Limited ("Trainline") requires a Contributor License Agreement on file that has been signed by each contributor, indicating agreement to the license terms below. This license is for your protection as a Contributor as well as the protection of Trainline and its users; it does not change your rights to use your own contributions for any other purpose.
3+
Please send confirmation that you accept the terms set out below to [email protected]. Please read the terms carefully before accepting and keep a copy for your records.
4+
You accept and agree to the following terms and conditions for Your present and future Contributions submitted to Trainline. Except for the license granted herein to Trainline and recipients of software distributed by Trainline, You reserve all right, title, and interest in and to Your Contributions.
5+
6+
1. Definitions.
7+
"You" (or "Your") shall mean the copyright owner or legal entity authorized by the copyright owner that is making this Agreement with Trainline. For legal entities, the entity making a Contribution and all other entities that control, are controlled by, or are under common control with that entity are considered to be a single Contributor. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty per cent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
8+
"Contribution" shall mean any original work of authorship, including any modifications or additions to an existing work, that is intentionally submitted by You to Trainline for inclusion in, or documentation of, any of the products owned or managed by Trainline (the "Work"). For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to Trainline or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, Trainline for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by You as "Not a Contribution."
9+
2. Grant of Copyright License. Subject to the terms and conditions of this Agreement, You hereby grant to Trainline and to recipients of software distributed by Trainline a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute Your Contributions and such derivative works.
10+
3. Grant of Patent License. Subject to the terms and conditions of this Agreement, You hereby grant to Trainline and to recipients of software distributed by Trainline a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by You that are necessarily infringed by Your Contribution(s) alone or by combination of Your Contribution(s) with the Work to which such Contribution(s) was submitted. If any entity institutes patent litigation against You or any other entity (including a cross-claim or counterclaim in a lawsuit) alleging that your Contribution, or the Work to which you have contributed, constitutes direct or contributory patent infringement, then any patent licenses granted to that entity under this Agreement for that Contribution or Work shall terminate as of the date such litigation is filed.
11+
4. You represent that you are legally entitled to grant the above license. If your employer(s) has rights to intellectual property that you create that includes your Contributions, you represent that you have received permission to make Contributions on behalf of that employer, that your employer has waived such rights for your Contributions to Trainline, or that your employer has executed a separate agreement with Trainline.
12+
5. You represent that each of Your Contributions is Your original creation (see section 7 for submissions on behalf of others). You represent that Your Contribution submissions include complete details of any third-party license or other restriction (including, but not limited to, related patents and trademarks) of which you are personally aware and which are associated with any part of Your Contributions.
13+
6. You are not expected to provide support for Your Contributions, except to the extent You desire to provide support. You may provide support for free, for a fee, or not at all. Unless required by applicable law or agreed to in writing, You provide Your Contributions on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE.
14+
7. Should You wish to submit work that is not Your original creation, You may submit it to Trainline separately from any Contribution, identifying the complete details of its source and of any license or other restriction (including, but not limited to, related patents, trademarks, and license agreements) of which you are personally aware, and conspicuously marking the work as "Submitted on behalf of a third-party: [named here]".
15+
8. You agree to notify Trainline of any facts or circumstances of which you become aware that would make these representations inaccurate in any respect.
16+
17+
Please sign: Marc Cluet Date: 2016-09-21

environment_manager/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
""" Copyright (c) Trainline Limited, 2016. All rights reserved. See LICENSE.txt in the project root for license information. """

environment_manager/api.py

+143
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
""" Copyright (c) Trainline Limited, 2016. All rights reserved. See LICENSE.txt in the project root for license information. """
2+
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
3+
4+
import time
5+
import requests
6+
from environment_manager.utils import LogWrapper
7+
8+
class EMApi(object):
9+
"""Defines all api calls and treats them like an object to give proper interfacing"""
10+
11+
def __init__(self, server=None, user=None, password=None, retries=5):
12+
""" Initialise new API object """
13+
self.server = server
14+
self.user = user
15+
self.password = password
16+
self.retries = retries
17+
self.token = None
18+
# Sanitise input
19+
if server is None or user is None or password is None:
20+
raise ValueError('EMApi(server=SERVERNAME, user=USERNAME, password=PASSWORD, [retries=N])')
21+
if server == '' or user == '' or password == '':
22+
raise ValueError('EMApi(server=SERVERNAME, user=USERNAME, password=PASSWORD, [retries=N])')
23+
24+
def _api_auth(self):
25+
""" Function to authenticate in Environment Manager """
26+
log = LogWrapper()
27+
log.info('Authenticating in EM with user %s' % self.user)
28+
# Build base url
29+
base_url = 'https://%s' % self.server
30+
# Request token
31+
token_payload = {'grant_type': 'password',
32+
'username': self.user,
33+
'password': self.password}
34+
token = None
35+
no_token = True
36+
retries = 0
37+
while no_token and retries < self.retries:
38+
em_token_url = '%s/api/token' % base_url
39+
em_token = requests.post(em_token_url, data=token_payload, timeout=5, verify=False)
40+
if int(str(em_token.status_code)[:1]) == 2:
41+
token = em_token.text
42+
no_token = False
43+
else:
44+
log.debug('Could not authenticate, trying again: %s' % em_token.status_code)
45+
time.sleep(2)
46+
retries += 1
47+
if token is not None:
48+
# Got token now lets get URL
49+
token_bearer = 'Bearer %s' % token
50+
return token_bearer
51+
else:
52+
raise SystemError('Could not authenticate against Environment Manager')
53+
54+
def query(self, query_endpoint=None, retries=5, backoff=2):
55+
""" Function to querying Environment Manager """
56+
log = LogWrapper()
57+
if query_endpoint is None:
58+
log.info('No query endpoint specified, cant just go and query nothing')
59+
raise SyntaxError('No query endpoint specified, cant just go and query nothing')
60+
retry_num = 0
61+
while retry_num < retries:
62+
retry_num += 1
63+
log.debug('Going through query iteration %s out of %s' % (retry_num, retries))
64+
token = self._api_auth()
65+
log.debug('Using token %s for auth' % token)
66+
# Build base url
67+
base_url = 'https://%s' % self.server
68+
request_url = '%s%s' % (base_url, query_endpoint)
69+
log.debug('Calling URL %s' % request_url)
70+
request = requests.get(request_url, headers={'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': token}, timeout=30, verify=False)
71+
if int(str(request.status_code)[:1]) == 2:
72+
return request.json()
73+
else:
74+
log.info('Got a status %s from EM, cant serve, retrying' % request.status_code)
75+
log.debug(request.request.headers)
76+
log.debug(request.__dict__)
77+
time.sleep(backoff)
78+
# General one if we exceeded our retries
79+
raise SystemError('Max number of retries (%s) querying Environment Manager, will abort for now' % retries)
80+
81+
#######################################################
82+
# This is a full API implementation based on EM docs #
83+
#######################################################
84+
85+
## Accounts
86+
87+
## AMI
88+
89+
## ASG
90+
def get_asgs(self, account='Non-Prod', **kwargs):
91+
""" Get list of ASGs from EM """
92+
request_endpoint = '/api/v1/asgs?account=%s' % account
93+
return self.query(request_endpoint, **kwargs)
94+
95+
## Audit
96+
97+
## Cluster
98+
99+
## Deployment
100+
101+
## Deployment Map
102+
103+
## Environment
104+
def get_environment_asg_servers(self, environment=None, asgname=None, **kwargs):
105+
""" Get list of servers belonging to an environment ASG """
106+
if environment is None or asgname is None:
107+
raise SyntaxError('Either environment or asgname has not been specified')
108+
request_endpoint = '/api/v1/environments/%s/servers/%s' % (environment, asgname)
109+
return self.query(request_endpoint, **kwargs)
110+
111+
## Environment Type
112+
113+
## Export
114+
115+
## Import
116+
117+
## Instance
118+
119+
## Load Balancers
120+
def get_lb_settings(self, **kwargs):
121+
""" Get list of Services from EM """
122+
request_endpoint = '/api/v1/config/lb-settings'
123+
return self.query(request_endpoint, **kwargs)
124+
125+
## Package
126+
127+
## Permissions
128+
129+
## Service
130+
def get_services(self, **kwargs):
131+
""" Get list of Services from EM """
132+
request_endpoint = '/api/v1/config/services'
133+
return self.query(request_endpoint, **kwargs)
134+
135+
## Status
136+
137+
## Target State
138+
139+
## Upstream
140+
def get_upstreams(self, **kwargs):
141+
""" Get list of Upstreams from EM """
142+
request_endpoint = '/api/v1/config/upstreams'
143+
return self.query(request_endpoint, **kwargs)

0 commit comments

Comments
 (0)