blob: 6f0d9950aeba32a992d72c574321e3e458dcd4b7 [file] [log] [blame]
Jakub Josef7bb17ab2017-01-12 14:52:53 +01001import logging
Jakub Josef7d9fce32017-03-24 16:46:56 +01002from json import dumps
Jakub Josef7bb17ab2017-01-12 14:52:53 +01003logger = logging.getLogger(__name__)
4
5add_view_groovy = """\
6view = Jenkins.instance.getView("{view_name}")
7if(view){{
8 if(view.getClass().getName().equals("hudson.model.ListView")){{
9 include_regex="{include_regex}"
10 if(include_regex != "" && !view.getIncludeRegex().equals(include_regex)){{
11 view.setIncludeRegex(include_regex)
12 print("ADDED/CHANGED")
13 }}else{{
14 print("EXISTS")
15 }}
Jakub Josef7d9fce32017-03-24 16:46:56 +010016 }}else if(view.getClass().getName().equals("org.jenkinsci.plugins.categorizedview.CategorizedJobsView")){{
17 def jsonSlurper = new groovy.json.JsonSlurper()
18 def inputCategories = jsonSlurper.parseText('{categories_string}')
19 def groupRegexes = inputCategories.stream().map{{e -> e["group_regex"]}}.collect(Collectors.toList())
20 def namingRules = inputCategories.stream().map{{e -> e["naming_rule"]}}.collect(Collectors.toList())
21 def actualCategories = view.categorizationCriteria
22 def equals = !actualCategories.isEmpty()
23 def include_regex="{include_regex}"
24 if(include_regex != "" && !view.getIncludeRegex().equals(include_regex)){{
25 view.setIncludeRegex(include_regex)
26 equals = false
27 }}
28 for(int i=0;i<actualCategories.size();i++){{
29 if(!groupRegexes.contains(actualCategories[i].groupRegex) || !namingRules.contains(actualCategories[i].namingRule)){{
30 equals = false
31 }}
32 }}
33 if(!equals){{
34 view.categorizationCriteria.clear()
35 for(int i=0;i<inputCategories.size();i++){{
36 view.categorizationCriteria.add(new GroupingRule(inputCategories[i].group_regex,inputCategories[i].naming_rule))
37 }}
38 print("ADDED/CHANGED")
39 }}else{{
40 print("EXISTS")
41 }}
Jakub Josef7bb17ab2017-01-12 14:52:53 +010042 }}else{{
43 print("EXISTS")
44 }}
45}}else{{
46 try{{
47 {view_def}
48 Jenkins.instance.addView(view)
49 print("ADDED/CHANGED")
50 }}catch(Exception e){{
51 print("FAILED")
52 }}
53}}
Jakub Josef7d9fce32017-03-24 16:46:56 +010054""" # noqa
Jakub Josef7bb17ab2017-01-12 14:52:53 +010055
56remove_view_groovy = """\
57view = Jenkins.instance.getView("{view_name}")
58if(view){{
59 try{{
60 Jenkins.instance.deleteView(view)
61 print("REMOVED")
62 }}catch(Exception e){{
63 print("FAILED")
64 }}
65}}else{{
66 print("NOT PRESENT")
67}}
Jakub Josef7d9fce32017-03-24 16:46:56 +010068""" # noqa
Jakub Josef7bb17ab2017-01-12 14:52:53 +010069
70
71def present(name, type="ListView", **kwargs):
72 """
73 Jenkins view present state method
74
75 :param name: view name
76 :param type: view type (default ListView)
77 :returns: salt-specified state dict
78 """
79 return _plugin_call(name, type, add_view_groovy, ["ADDED/CHANGED", "EXISTS"], **kwargs)
80
81
82def absent(name, **kwargs):
83 """
84 Jenkins view absent state method
85
86 :param name: view name
87 :returns: salt-specified state dict
88 """
89 return _plugin_call(name, None, remove_view_groovy, ["REMOVED", "NOT PRESENT"], **kwargs)
90
91
92def _plugin_call(name, type, template, success_msgs, **kwargs):
93 test = __opts__['test'] # noqa
94 ret = {
95 'name': name,
96 'changes': {},
97 'result': False,
98 'comment': '',
99 }
100 result = False
101 if test:
102 status = success_msgs[0]
103 ret['changes'][name] = status
104 ret['comment'] = 'Jenkins view %s %s' % (name, status.lower())
105 else:
106 view_def = "view = new {}(\"{}\")".format(type, name)
107 # handle view specific params
108 include_regex = kwargs.get('include_regex')
Jakub Josef7d9fce32017-03-24 16:46:56 +0100109 categories_string = ""
Jakub Josef7bb17ab2017-01-12 14:52:53 +0100110 if type == "ListView":
111 if include_regex:
Jakub Josef7d9fce32017-03-24 16:46:56 +0100112 view_def += "\nview.setIncludeRegex(\"{}\")".format(
113 include_regex)
114 if type == "CategorizedJobsView":
115 # add imports for categorized views
116 template = "import java.util.stream.Collectors\nimport org.jenkinsci.plugins.categorizedview.CategorizedJobsView\nimport org.jenkinsci.plugins.categorizedview.GroupingRule\n" + template
117 if include_regex:
118 view_def += "\nview.setIncludeRegex(\"{}\")".format(
119 include_regex)
120 categories = kwargs.get('categories', [])
121 for category in categories:
122 view_def += "\nview.categorizationCriteria.add(new GroupingRule(\"{}\", \"{}\"))".format(
123 category["group_regex"], category["naming_rule"])
124 # create catogories string readable in groovy
125 categories_string = dumps(categories)
Jakub Josef7bb17ab2017-01-12 14:52:53 +0100126
127 call_result = __salt__['jenkins_common.call_groovy_script'](
Jakub Josef7d9fce32017-03-24 16:46:56 +0100128 template, {"view_def": view_def, "view_name": name, "type": type if type else "", "include_regex": include_regex if include_regex else "", "categories_string": categories_string if categories_string else ""})
Jakub Josef7bb17ab2017-01-12 14:52:53 +0100129 if call_result["code"] == 200 and call_result["msg"] in success_msgs:
130 status = call_result["msg"]
131 if status == success_msgs[0]:
132 ret['changes'][name] = status
133 ret['comment'] = 'Jenkins view %s %s' % (name, status.lower())
134 result = True
135 else:
136 status = 'FAILED'
137 logger.error(
138 "Jenkins view API call failure: %s", call_result["msg"])
139 ret['comment'] = 'Jenkins view API call failure: %s' % (call_result[
Jakub Josef7d9fce32017-03-24 16:46:56 +0100140 "msg"])
Jakub Josef7bb17ab2017-01-12 14:52:53 +0100141 ret['result'] = None if test else result
142 return ret