blob: e14d3fd9800b74fb59f71e8d13323f68987840ed [file] [log] [blame]
Jakub Josef7bb17ab2017-01-12 14:52:53 +01001import logging
2logger = logging.getLogger(__name__)
3
4add_view_groovy = """\
5view = Jenkins.instance.getView("{view_name}")
6if(view){{
7 if(view.getClass().getName().equals("hudson.model.ListView")){{
8 include_regex="{include_regex}"
9 if(include_regex != "" && !view.getIncludeRegex().equals(include_regex)){{
10 view.setIncludeRegex(include_regex)
11 print("ADDED/CHANGED")
12 }}else{{
13 print("EXISTS")
14 }}
15 }}else{{
16 print("EXISTS")
17 }}
18}}else{{
19 try{{
20 {view_def}
21 Jenkins.instance.addView(view)
22 print("ADDED/CHANGED")
23 }}catch(Exception e){{
24 print("FAILED")
25 }}
26}}
27""" # noqa
28
29remove_view_groovy = """\
30view = Jenkins.instance.getView("{view_name}")
31if(view){{
32 try{{
33 Jenkins.instance.deleteView(view)
34 print("REMOVED")
35 }}catch(Exception e){{
36 print("FAILED")
37 }}
38}}else{{
39 print("NOT PRESENT")
40}}
41""" # noqa
42
43
44def present(name, type="ListView", **kwargs):
45 """
46 Jenkins view present state method
47
48 :param name: view name
49 :param type: view type (default ListView)
50 :returns: salt-specified state dict
51 """
52 return _plugin_call(name, type, add_view_groovy, ["ADDED/CHANGED", "EXISTS"], **kwargs)
53
54
55def absent(name, **kwargs):
56 """
57 Jenkins view absent state method
58
59 :param name: view name
60 :returns: salt-specified state dict
61 """
62 return _plugin_call(name, None, remove_view_groovy, ["REMOVED", "NOT PRESENT"], **kwargs)
63
64
65def _plugin_call(name, type, template, success_msgs, **kwargs):
66 test = __opts__['test'] # noqa
67 ret = {
68 'name': name,
69 'changes': {},
70 'result': False,
71 'comment': '',
72 }
73 result = False
74 if test:
75 status = success_msgs[0]
76 ret['changes'][name] = status
77 ret['comment'] = 'Jenkins view %s %s' % (name, status.lower())
78 else:
79 view_def = "view = new {}(\"{}\")".format(type, name)
80 # handle view specific params
81 include_regex = kwargs.get('include_regex')
82 if type == "ListView":
83 if include_regex:
84 view_def += "\nview.setIncludeRegex(\"{}\")".format(include_regex)
85
86 call_result = __salt__['jenkins_common.call_groovy_script'](
87 template, {"view_def": view_def, "view_name": name, "type": type if type else "", "include_regex": include_regex if include_regex else ""})
88 if call_result["code"] == 200 and call_result["msg"] in success_msgs:
89 status = call_result["msg"]
90 if status == success_msgs[0]:
91 ret['changes'][name] = status
92 ret['comment'] = 'Jenkins view %s %s' % (name, status.lower())
93 result = True
94 else:
95 status = 'FAILED'
96 logger.error(
97 "Jenkins view API call failure: %s", call_result["msg"])
98 ret['comment'] = 'Jenkins view API call failure: %s' % (call_result[
99 "msg"])
100 ret['result'] = None if test else result
101 return ret