blob: 00698b2aa1674c6eb95a199e5098f565294b19de [file] [log] [blame]
Jakub Josef8e7385e2016-12-07 21:20:34 +01001import bcrypt
2import logging
3import requests
4from salt.exceptions import SaltInvocationError
5
6logger = logging.getLogger(__name__)
7
8
9def call_groovy_script(script, props):
10 """
11 Common method for call Jenkins groovy script API
12
13 :param script groovy script template
14 :param props groovy script properties
15 :returns: HTTP dict {status,code,msg}
16 """
17 ret = {
18 "status": "FAILED",
19 "code": 999,
20 "msg": ""
21 }
22 jenkins_url, jenkins_user, jenkins_password = get_jenkins_auth()
23 if not jenkins_url:
24 raise SaltInvocationError('No Jenkins URL found.')
25 tokenObj = get_api_crumb(jenkins_url, jenkins_user, jenkins_password)
26 if tokenObj:
27 logger.debug("Calling Jenkins script API with URL: %s",jenkins_url)
28 req = requests.post('%s/scriptText' % jenkins_url,
29 auth=(jenkins_user, jenkins_password),
30 data={tokenObj["crumbRequestField"]: tokenObj["crumb"],
31 "script": render_groovy_script(script, props)})
32 ret["code"] = req.status_code
33 if req.status_code == 200:
34 ret["status"] = "SUCCESS"
35 logger.debug("Jenkins script API call success")
36 ret["msg"] = req.text
37 else:
38 logger.error("Jenkins script API call failed. \
39 Return code %s. Text: %s", req.status_code,req.text)
40 else:
41 logger.error("Cannot call Jenkins script API, Token is invalid!")
42 return ret
43
44
45def render_groovy_script(script, props):
46 """
47 Helper method for rendering groovy script with props
48
49 :param name: groovy script tempalte
50 :param scope: groovy script properties
51 :returns: generated groovy script
52 """
53 return script.format(**props)
54
55
56def get_api_crumb(jenkins_url=None, jenkins_user=None, jenkins_password=None):
57 """
58 Obtains Jenkins API crumb, if CSRF protection is enabled.
59 Jenkins params can be given by params or not, if not,
60 params will be get from salt.
61
62 :param jenkins_url: Jenkins URL (optional)
63 :param jenkins_user: Jenkins admin username (optional)
64 :param jenkins_password: Jenkins admin password (optional)
65 :returns: salt-specified state dict
66 """
67 if not jenkins_url:
68 jenkins_url, jenkins_user, jenkins_password = get_jenkins_auth()
69 logger.debug("Obtaining Jenkins API crumb for URL: %s", jenkins_url)
70 tokenReq = requests.get("%s/crumbIssuer/api/json" % jenkins_url,
71 auth=(jenkins_user, jenkins_password) if jenkins_user else None)
72 if tokenReq.status_code == 200:
73 return tokenReq.json()
74 else:
75 logger.error("Cannot obtain Jenkins API crumb. Status code: %s. Text: %s",
76 tokenReq.status_code,tokenReq.text)
77
78
79
80def get_jenkins_auth():
81 """
82 Get jenkins params from salt
83 """
84 jenkins_url = __salt__['config.get']('jenkins.url') or \
85 __salt__['config.get']('jenkins:url') or \
86 __salt__['pillar.get']('jenkins.url')
87
88 jenkins_user = __salt__['config.get']('jenkins.user') or \
89 __salt__['config.get']('jenkins:user') or \
90 __salt__['pillar.get']('jenkins.user')
91
92 jenkins_password = __salt__['config.get']('jenkins.password') or \
93 __salt__['config.get']('jenkins:password') or \
94 __salt__['pillar.get']('jenkins.password')
95
96 return (jenkins_url, jenkins_user, jenkins_password)
97
98
99def encode_password(password):
100 """
101 Hash plaintext password by jenkins bcrypt algorithm
102 :param password: plain-text password
103 :returns: bcrypt hashed password
104 """
105 if isinstance(password, str):
106 return bcrypt.hashpw(password, bcrypt.gensalt(prefix=b"2a"))