blob: e229a11fba2791d603866b1e5a03710a57c83bf3 [file] [log] [blame]
Jakub Josef7bb17ab2017-01-12 14:52:53 +01001import logging
Adam Tengler70763e02017-08-21 16:50:32 +00002
Jakub Josef7d9fce32017-03-24 16:46:56 +01003from json import dumps
Adam Tengler70763e02017-08-21 16:50:32 +00004
Jakub Josef7bb17ab2017-01-12 14:52:53 +01005logger = logging.getLogger(__name__)
6
7add_view_groovy = """\
Jakub Josefe74e7a62017-04-06 11:50:55 +02008import java.util.stream.Collectors
9import org.jenkinsci.plugins.categorizedview.CategorizedJobsView
10import org.jenkinsci.plugins.categorizedview.GroupingRule
Adam Tengler70763e02017-08-21 16:50:32 +000011view = Jenkins.instance.getView("${view_name}")
12if(view){
13 if(view.getClass().getName().equals("hudson.model.ListView")){
14 include_regex="${include_regex}"
15 if(include_regex != "" && !view.getIncludeRegex().equals(include_regex)){
Jakub Josef7bb17ab2017-01-12 14:52:53 +010016 view.setIncludeRegex(include_regex)
17 print("ADDED/CHANGED")
Adam Tengler70763e02017-08-21 16:50:32 +000018 }else{
Jakub Josef7bb17ab2017-01-12 14:52:53 +010019 print("EXISTS")
Adam Tengler70763e02017-08-21 16:50:32 +000020 }
21 }else if(view.getClass().getName().equals("org.jenkinsci.plugins.categorizedview.CategorizedJobsView")){
Jakub Josef7d9fce32017-03-24 16:46:56 +010022 def jsonSlurper = new groovy.json.JsonSlurper()
Adam Tengler70763e02017-08-21 16:50:32 +000023 def inputCategories = jsonSlurper.parseText('${categories_string}')
24 def groupRegexes = inputCategories.stream().map{e -> e["group_regex"]}.collect(Collectors.toList())
25 def namingRules = inputCategories.stream().map{e -> e["naming_rule"]}.collect(Collectors.toList())
Jakub Josef7d9fce32017-03-24 16:46:56 +010026 def actualCategories = view.categorizationCriteria
27 def equals = !actualCategories.isEmpty()
Adam Tengler70763e02017-08-21 16:50:32 +000028 def include_regex="${include_regex}"
29 if(include_regex != "" && !view.getIncludeRegex().equals(include_regex)){
Jakub Josef7d9fce32017-03-24 16:46:56 +010030 view.setIncludeRegex(include_regex)
31 equals = false
Adam Tengler70763e02017-08-21 16:50:32 +000032 }
33 for(int i=0;i<actualCategories.size();i++){
34 if(!groupRegexes.contains(actualCategories[i].groupRegex) || !namingRules.contains(actualCategories[i].namingRule)){
Jakub Josef7d9fce32017-03-24 16:46:56 +010035 equals = false
Adam Tengler70763e02017-08-21 16:50:32 +000036 }
37 }
38 if(!equals){
Jakub Josef7d9fce32017-03-24 16:46:56 +010039 view.categorizationCriteria.clear()
Adam Tengler70763e02017-08-21 16:50:32 +000040 for(int i=0;i<inputCategories.size();i++){
Jakub Josef7d9fce32017-03-24 16:46:56 +010041 view.categorizationCriteria.add(new GroupingRule(inputCategories[i].group_regex,inputCategories[i].naming_rule))
Adam Tengler70763e02017-08-21 16:50:32 +000042 }
Jakub Josef7d9fce32017-03-24 16:46:56 +010043 print("ADDED/CHANGED")
Adam Tengler70763e02017-08-21 16:50:32 +000044 }else{
Jakub Josef7d9fce32017-03-24 16:46:56 +010045 print("EXISTS")
Adam Tengler70763e02017-08-21 16:50:32 +000046 }
47 }else{
Jakub Josef7bb17ab2017-01-12 14:52:53 +010048 print("EXISTS")
Adam Tengler70763e02017-08-21 16:50:32 +000049 }
50}else{
51 try{
52 ${view_def}
Jakub Josef7bb17ab2017-01-12 14:52:53 +010053 Jenkins.instance.addView(view)
54 print("ADDED/CHANGED")
Adam Tengler70763e02017-08-21 16:50:32 +000055 }catch(Exception e){
Jakub Josef7bb17ab2017-01-12 14:52:53 +010056 print("FAILED")
Adam Tengler70763e02017-08-21 16:50:32 +000057 }
58}
Jakub Josef7d9fce32017-03-24 16:46:56 +010059""" # noqa
Jakub Josef7bb17ab2017-01-12 14:52:53 +010060
61remove_view_groovy = """\
Adam Tengler70763e02017-08-21 16:50:32 +000062view = Jenkins.instance.getView("${view_name}")
63if(view){
64 try{
Jakub Josef7bb17ab2017-01-12 14:52:53 +010065 Jenkins.instance.deleteView(view)
66 print("REMOVED")
Adam Tengler70763e02017-08-21 16:50:32 +000067 }catch(Exception e){
Jakub Josef7bb17ab2017-01-12 14:52:53 +010068 print("FAILED")
Adam Tengler70763e02017-08-21 16:50:32 +000069 }
70}else{
Jakub Josef7bb17ab2017-01-12 14:52:53 +010071 print("NOT PRESENT")
Adam Tengler70763e02017-08-21 16:50:32 +000072}
Jakub Josef7d9fce32017-03-24 16:46:56 +010073""" # noqa
Jakub Josef7bb17ab2017-01-12 14:52:53 +010074
75
Ilya Kharin3d8bffe2017-06-22 17:40:31 +040076def __virtual__():
77 '''
78 Only load if jenkins_common module exist.
79 '''
80 if 'jenkins_common.call_groovy_script' not in __salt__:
81 return (
82 False,
83 'The jenkins_view state module cannot be loaded: '
84 'jenkins_common not found')
85 return True
86
87
Jakub Josef7bb17ab2017-01-12 14:52:53 +010088def present(name, type="ListView", **kwargs):
89 """
90 Jenkins view present state method
91
92 :param name: view name
93 :param type: view type (default ListView)
94 :returns: salt-specified state dict
95 """
Adam Tengler70763e02017-08-21 16:50:32 +000096 return _plugin_call(name, type, add_view_groovy, [
97 "ADDED/CHANGED", "EXISTS"], **kwargs)
Jakub Josef7bb17ab2017-01-12 14:52:53 +010098
99
100def absent(name, **kwargs):
101 """
102 Jenkins view absent state method
103
104 :param name: view name
105 :returns: salt-specified state dict
106 """
Adam Tengler70763e02017-08-21 16:50:32 +0000107 return _plugin_call(name, None, remove_view_groovy, [
108 "REMOVED", "NOT PRESENT"], **kwargs)
Jakub Josef7bb17ab2017-01-12 14:52:53 +0100109
110
111def _plugin_call(name, type, template, success_msgs, **kwargs):
112 test = __opts__['test'] # noqa
113 ret = {
114 'name': name,
115 'changes': {},
116 'result': False,
117 'comment': '',
118 }
119 result = False
120 if test:
121 status = success_msgs[0]
122 ret['changes'][name] = status
123 ret['comment'] = 'Jenkins view %s %s' % (name, status.lower())
124 else:
125 view_def = "view = new {}(\"{}\")".format(type, name)
126 # handle view specific params
127 include_regex = kwargs.get('include_regex')
Jakub Josef7d9fce32017-03-24 16:46:56 +0100128 categories_string = ""
Jakub Josef7bb17ab2017-01-12 14:52:53 +0100129 if type == "ListView":
130 if include_regex:
Jakub Josef7d9fce32017-03-24 16:46:56 +0100131 view_def += "\nview.setIncludeRegex(\"{}\")".format(
132 include_regex)
133 if type == "CategorizedJobsView":
134 # add imports for categorized views
Jakub Josef7d9fce32017-03-24 16:46:56 +0100135 if include_regex:
136 view_def += "\nview.setIncludeRegex(\"{}\")".format(
137 include_regex)
138 categories = kwargs.get('categories', [])
139 for category in categories:
140 view_def += "\nview.categorizationCriteria.add(new GroupingRule(\"{}\", \"{}\"))".format(
141 category["group_regex"], category["naming_rule"])
142 # create catogories string readable in groovy
143 categories_string = dumps(categories)
Jakub Josef7bb17ab2017-01-12 14:52:53 +0100144
145 call_result = __salt__['jenkins_common.call_groovy_script'](
Jakub Josef7d9fce32017-03-24 16:46:56 +0100146 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 +0100147 if call_result["code"] == 200 and call_result["msg"] in success_msgs:
148 status = call_result["msg"]
149 if status == success_msgs[0]:
150 ret['changes'][name] = status
151 ret['comment'] = 'Jenkins view %s %s' % (name, status.lower())
152 result = True
153 else:
154 status = 'FAILED'
155 logger.error(
156 "Jenkins view API call failure: %s", call_result["msg"])
157 ret['comment'] = 'Jenkins view API call failure: %s' % (call_result[
Jakub Josef7d9fce32017-03-24 16:46:56 +0100158 "msg"])
Jakub Josef7bb17ab2017-01-12 14:52:53 +0100159 ret['result'] = None if test else result
160 return ret