Skip to content

Commit 86fb629

Browse files
committed
Merge pull request apache#7 from mesosphere/add-token
Add token
2 parents 1e2cadd + 0dda4fb commit 86fb629

File tree

2 files changed

+65
-38
lines changed

2 files changed

+65
-38
lines changed

README.md

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,12 @@ When run with the `uninstall` command, it will:
3232
git clone https://github.com/mesosphere/cd-demo.git
3333
```
3434
2. [Set up the DCOS CLI](https://docs.mesosphere.com/administration/introcli/cli/) locally.
35-
3. Ensure you have a DCOS cluster available. 1 node will work but more than 1 node is preferable to demonstrate build parallelism.
35+
3. Ensure you have a DCOS cluster available. 1 node will work but more than 1 node is preferable to demonstrate build parallelism. If you already had the CLI installed, make sure you set the new cluster URL and authenticate against it:
36+
37+
```
38+
dcos config set core.dcos_url http://my.dcos.cluster/
39+
dcos auth login
40+
```
3641
3742
### Running Demo
3843
@@ -41,7 +46,7 @@ When run with the `uninstall` command, it will:
4146
```
4247
bin/demo.py install --branch=my-demo-branch --password=mypass123 http://my.dcos.cluster/
4348
```
44-
NOTE: Dependeing on your environment you may need to prepend the above command with `python` Also you must use the domain name for your cluster; the IP address will fail.
49+
NOTE: Depending on your environment you may need to prepend the above command with `python` Also you must use the domain name for your cluster; the IP address will fail.
4550
4651
2. The script will install Jenkins and pause. Check that the Jenkins UI is running before hitting enter to proceed.
4752
3. The script will now use the Jenkins HTTP API to install jobs, necessary credentials and a view. It will automatically trigger the initial build before pausing.

bin/demo.py

Lines changed: 58 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -32,21 +32,46 @@
3232
pass or fail. The duration of each job will be between 120 and 240 seconds.
3333
"""
3434

35-
from docopt import docopt
3635
import json
3736
import os
3837
import random
39-
import requests
4038
import shutil
41-
from subprocess import call
39+
from subprocess import call, CalledProcessError, check_output
40+
41+
import requests
42+
from docopt import docopt
4243

4344
def log(message):
4445
print "[demo] {}".format(message)
4546

47+
def log_and_exit(message):
48+
log(message)
49+
exit(1)
50+
51+
def get_auth_wrapper(token_arg):
52+
def auth_wrapper(headers):
53+
if token_arg is not None and len(token_arg.strip()) > 0:
54+
headers['Authorization'] = "token={}".format(token_arg)
55+
return headers
56+
return auth_wrapper
57+
58+
auth_func = get_auth_wrapper(None)
59+
60+
def check_and_set_token(jenkins_url):
61+
try:
62+
global auth_func
63+
command = "dcos config show core.dcos_acs_token"
64+
token = check_output(command, shell=True).strip('\n')
65+
auth_func = get_auth_wrapper(token)
66+
r = requests.get(jenkins_url, headers=auth_func({}))
67+
if r.status_code == 401:
68+
log_and_exit("Not authenticated. Please run `dcos auth login` and try again.")
69+
except CalledProcessError:
70+
log_and_exit ("Not authenticated. Please run `dcos auth login` and try again.")
71+
4672
def config_dcos_cli(dcos_url):
4773
if call (["dcos", "config", "set", "core.dcos_url", dcos_url],stdout=open(os.devnull, 'wb')) == 1:
48-
log("Unable to configure DCOS CLI.")
49-
exit(1)
74+
log_and_exit ("Unable to configure DCOS CLI.")
5075

5176
def make_temp_dir():
5277
remove_temp_dir()
@@ -66,13 +91,12 @@ def install(dcos_url, jenkins_name, jenkins_url):
6691
command = "dcos package install --yes --options=tmp/jenkins.json jenkins"
6792
print ("\n> " + command)
6893
if call (['dcos', 'package', 'install', '--yes', '--options=tmp/jenkins.json', 'jenkins']) != 0:
69-
log ("Failed to install Jenkins")
70-
exit(1)
94+
log_and_exit ("Failed to install Jenkins.")
7195
print("\n[demo] Jenkins has been installed! Wait for it to come up before proceeding at: {}".format(jenkins_url))
7296
raw_input("[demo] Press [Enter] to continue, or ^C to cancel...")
7397

7498
def verify(jenkins_url):
75-
r = requests.get(jenkins_url)
99+
r = requests.get(jenkins_url, headers=auth_func({}))
76100
if r.status_code != 200:
77101
log ("Couldn't find a Jenkins instance running at {}".format(jenkins_url))
78102
return False
@@ -82,53 +106,53 @@ def verify(jenkins_url):
82106
def create_credentials(jenkins_url, id, username, password):
83107
credential = { 'credentials' : { 'scope' : 'GLOBAL', 'id' : id, 'username' : username, 'password' : password, 'description' : id, '$class' : 'com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl'} }
84108
data = {'json' : json.dumps(credential) }
109+
headers = auth_func({})
85110
post_url = "{}/credential-store/domain/_/createCredentials".format(jenkins_url)
86-
r = requests.post(post_url, data=data)
111+
r = requests.post(post_url, headers=headers, data=data)
87112

88113
def create_job(jenkins_url, job_name, job_config):
89114
log ("Creating job")
90-
headers = {'Content-Type' : 'application/xml' }
115+
headers = auth_func({'Content-Type' : 'application/xml' })
91116
post_url = "{}/createItem?name={}".format(jenkins_url, job_name)
92117
r = requests.post(post_url, headers=headers, data=job_config)
93118
if r.status_code != 200:
94-
log ("Failed to create job {} at {}".format(job_name, jenkins_url))
95-
exit(1)
96-
log ("Job {} created successfully".format(job_name))
119+
log_and_exit ("Failed to create job {} at {}".format(job_name, jenkins_url))
120+
log ("Job {} created successfully.".format(job_name))
97121

98122
def create_view(jenkins_url, view_name, view_config):
99123
log ("Creating view")
100-
headers = {'Content-Type' : 'text/xml' }
124+
headers = auth_func({'Content-Type' : 'text/xml' })
101125
post_url = "{}/createView?name={}".format(jenkins_url, view_name)
102126
r = requests.post(post_url, headers=headers, data=view_config)
103127

104128
def trigger_build(jenkins_url, job_name, parameter_string = None):
105-
log ("Triggering build {}".format(job_name))
129+
log ("Triggering build {}.".format(job_name))
106130
if parameter_string:
107131
post_url = "{}/job/{}/buildWithParameters?{}".format(jenkins_url, job_name, parameter_string)
108132
else:
109133
post_url = "{}/job/{}/build".format(jenkins_url, job_name)
110-
r = requests.post(post_url)
134+
r = requests.post(post_url, headers=auth_func({}))
111135

112136
def delete_credentials(jenkins_url, credential_name):
113-
log ("Deleting credentials {}".format(credential_name))
137+
log ("Deleting credentials {}.".format(credential_name))
114138
post_url = "{}/credential-store/domain/_/credential/{}/doDelete".format(jenkins_url, credential_name)
115-
r = requests.post(post_url)
139+
r = requests.post(post_url, headers=auth_func({}))
116140

117141
def delete_job(jenkins_url, job_name):
118-
log ("Deleting job {}".format(job_name))
142+
log ("Deleting job {}.".format(job_name))
119143
post_url = "{}/job/{}/doDelete".format(jenkins_url, job_name)
120-
r = requests.post(post_url)
144+
r = requests.post(post_url, headers=auth_func({}))
121145

122146
def delete_view(jenkins_url, view_name):
123-
log ("Deleting view {}".format(view_name))
147+
log ("Deleting view {}.".format(view_name))
124148
post_url = "{}/view/{}/doDelete".format(jenkins_url, view_name)
125-
r = requests.post(post_url)
149+
r = requests.post(post_url, headers=auth_func({}))
126150

127151
def remove_temp_dir():
128152
shutil.rmtree("tmp", ignore_errors=True)
129153

130154
def demo_pipeline(jenkins_url, dcos_url, name, branch, org, username, password):
131-
log ("Creating demo pipeline")
155+
log ("Creating demo pipeline.")
132156
create_credentials(jenkins_url, 'docker-hub-credentials', username, password)
133157
with open("jobs/build-cd-demo/config.xml") as build_job:
134158
job_config = build_job.read().replace("GIT_BRANCH", branch)
@@ -146,11 +170,11 @@ def demo_pipeline(jenkins_url, dcos_url, name, branch, org, username, password):
146170
view_config = pipeline_view.read()
147171
create_view(jenkins_url, "cd-demo-pipeline", view_config)
148172
trigger_build(jenkins_url, "build-cd-demo")
149-
log ("Created demo pipeline")
173+
log ("Created demo pipeline.")
150174
raw_input("[demo] Press [Enter] to continue, or ^C to cancel...")
151175

152176
def demo_dynamic_slaves(jenkins_url, builds):
153-
log ("Creating {} freestyle Jenkins jobs".format(builds))
177+
log ("Creating {} freestyle Jenkins jobs.".format(builds))
154178
random.seed()
155179
with open("jobs/demo-job/config.xml") as demo_job:
156180
job_config = demo_job.read()
@@ -162,36 +186,35 @@ def demo_dynamic_slaves(jenkins_url, builds):
162186
parameter_string = '?DURATION={}&RESULT={}'.format(duration, result)
163187
trigger_build(jenkins_url, job_name, parameter_string)
164188
log ("Job {} created successfully. Duration: {}. Result: {}. Triggering build.".format(job_name, duration, result))
165-
log ("Created {} freestyle Jenkins jobs".format(builds))
189+
log ("Created {} freestyle Jenkins jobs.".format(builds))
166190
raw_input("[demo] Press [Enter] to continue, or ^C to cancel...")
167191

168192
def cleanup_pipeline_jobs (jenkins_url):
169-
log ("Cleaning up demo pipeline")
193+
log ("Cleaning up demo pipeline.")
170194
delete_credentials(jenkins_url, "docker-hub-credentials")
171195
delete_view(jenkins_url, "cd-demo-pipeline")
172196
delete_job(jenkins_url, "deploy-cd-demo")
173197
delete_job(jenkins_url, "test-cd-demo")
174198
delete_job(jenkins_url, "build-cd-demo")
175199

176200
def cleanup_dynamic_slaves_jobs(jenkins_url, builds):
177-
log ("Cleaning up {} builds".format(builds))
201+
log ("Cleaning up {} builds.".format(builds))
178202
for i in range(1, builds):
179203
job_name = "demo-job-{0:02d}".format(i)
180204
delete_job(jenkins_url, job_name)
181-
log ("Cleaned up {} builds".format(builds))
205+
log ("Cleaned up {} builds.".format(builds))
182206

183207
def cleanup(jenkins_url, builds):
184-
log ("Cleaning up Jenkins")
208+
log ("Cleaning up Jenkins.")
185209
cleanup_pipeline_jobs(jenkins_url)
186210
cleanup_dynamic_slaves_jobs(jenkins_url, builds)
187211

188212
def uninstall(dcos_url, jenkins_name):
189-
log ("Uninstalling Jenkins with name {}".format(jenkins_name))
213+
log ("Uninstalling Jenkins with name {}.".format(jenkins_name))
190214
command = "dcos package uninstall --app-id={} jenkins".format(jenkins_name)
191215
print (command)
192216
if call (['dcos','package','uninstall','--app-id={}'.format(jenkins_name), 'jenkins']) != 0:
193-
log ("Failed to uninstall Jenkins")
194-
exit(1)
217+
log_and_exit ("Failed to uninstall Jenkins.")
195218
log ("Jenkins has been uninstalled!")
196219

197220
if __name__ == "__main__":
@@ -202,8 +225,8 @@ def uninstall(dcos_url, jenkins_name):
202225
dcos_url = arguments['<dcos_url>']
203226
jenkins_url = '{}service/{}/'.format(dcos_url, jenkins_name)
204227

228+
check_and_set_token(jenkins_url)
205229
config_dcos_cli(dcos_url)
206-
207230
try:
208231
if arguments['install']:
209232
make_temp_dir()
@@ -212,8 +235,7 @@ def uninstall(dcos_url, jenkins_name):
212235
if not arguments['--no-pipeline']:
213236
branch = arguments['--branch'].lower()
214237
if branch == 'master':
215-
log("Cannot run demo against the master branch.")
216-
exit(1)
238+
log_and_exit ("Cannot run demo against the master branch.")
217239
org = arguments['--org']
218240
username = arguments['--username']
219241
password = arguments['--password']

0 commit comments

Comments
 (0)