Browse Source

Fix trigger creation failed

Currently, karbor use 'calendar' format as the default
time format, but karbor-dashboard use 'crontab', this
makes the trigger creation failed. This patch convert
the time format of the dashboard to canlendar to make
it work.

Change-Id: I7a89365005af3256bdf02478dd60428a118a8bbe
Closes-Bug: #1613587
Jiao Pengju 1 year ago
parent
commit
cce93819d1

+ 6
- 0
karbor_dashboard/locale/en_GB/LC_MESSAGES/django.po View File

@@ -112,6 +112,12 @@ msgstr "Error Deleting"
112 112
 msgid "Event Trigger"
113 113
 msgstr "Event Trigger"
114 114
 
115
+msgid "Every Minute"
116
+msgstr "Every Minute"
117
+
118
+msgid "Every Hour"
119
+msgstr "Every Hour"
120
+
115 121
 msgid "Every Day"
116 122
 msgstr "Every Day"
117 123
 

+ 12
- 0
karbor_dashboard/templates/triggers/_detail.html View File

@@ -22,5 +22,17 @@
22 22
       <dt>{% trans "Execution Time (HH:MM)" %}</dt>
23 23
       <dd>{{ trigger.time }}</dd>
24 24
     {% endif %}
25
+    {% if trigger.hour %}
26
+      <dt>{% trans "Hour" %}</dt>
27
+      <dd>{{ trigger.hour }}</dd>
28
+    {% endif %}
29
+    {% if trigger.minute %}
30
+      <dt>{% trans "Minute" %}</dt>
31
+      <dd>{{ trigger.minute }}</dd>
32
+    {% endif %}
33
+    {% if trigger.interval %}
34
+      <dt>{% trans "Execution Interval" %}</dt>
35
+      <dd>{{ trigger.interval }}</dd>
36
+    {% endif %}
25 37
   </dl>
26 38
 </div>

+ 3
- 3
karbor_dashboard/triggers/forms.py View File

@@ -34,7 +34,7 @@ class CreateTriggerForm(horizon_forms.SelfHandlingForm):
34 34
                              }))
35 35
     frequence = forms.ChoiceField(
36 36
         label=_('Frequence'),
37
-        choices=utils.FREQUENCE_CHOICES,
37
+        choices=utils.CRONTAB_FREQUENCE_CHOICES,
38 38
         widget=forms.Select(attrs={
39 39
             'class': 'switchable switched',
40 40
             'data-slug': 'frequence'}))
@@ -60,12 +60,12 @@ class CreateTriggerForm(horizon_forms.SelfHandlingForm):
60 60
     def __init__(self, request, *args, **kwargs):
61 61
         super(CreateTriggerForm, self).__init__(request, *args, **kwargs)
62 62
 
63
-        self.fields['day'].choices = utils.DAY_CHOICES
63
+        self.fields['day'].choices = utils.CRONTAB_DAY_CHOICES
64 64
         self.fields['date'].choices = [(e, e) for e in range(1, 31 + 1)]
65 65
 
66 66
     def handle(self, request, data):
67 67
         try:
68
-            data_properties = utils.CrontabUtil.convert_to_crontab(data)
68
+            data_properties = utils.CalendarUtil.convert_to_calendar(data)
69 69
             new_trigger = karborclient.trigger_create(request,
70 70
                                                       data["name"],
71 71
                                                       data["type"],

+ 128
- 17
karbor_dashboard/triggers/utils.py View File

@@ -14,29 +14,32 @@
14 14
 
15 15
 import collections
16 16
 from django.utils.translation import ugettext_lazy as _
17
+from icalendar.cal import Component
18
+from icalendar import Event
19
+from oslo_serialization import jsonutils
17 20
 
18 21
 TRIGGERTYPE_CHOICES = [('time', _('Time Trigger')),
19 22
                        ('event', _('Event Trigger'))]
20 23
 
21 24
 CRONTAB = 'crontab'
22 25
 
23
-DAY_CHOICES = [('1', _('Monday')),
24
-               ('2', _('Tuesday')),
25
-               ('3', _('Wednesday')),
26
-               ('4', _('Thursday')),
27
-               ('5', _('Friday')),
28
-               ('6', _('Saturday')),
29
-               ('0', _('Sunday'))]
30
-DAY_DICT = collections.OrderedDict(DAY_CHOICES)
26
+CRONTAB_DAY_CHOICES = [('1', _('Monday')),
27
+                       ('2', _('Tuesday')),
28
+                       ('3', _('Wednesday')),
29
+                       ('4', _('Thursday')),
30
+                       ('5', _('Friday')),
31
+                       ('6', _('Saturday')),
32
+                       ('0', _('Sunday'))]
33
+CRONTAB_DAY_DICT = collections.OrderedDict(CRONTAB_DAY_CHOICES)
31 34
 
32 35
 EVERYDAY = 'everyday'
33 36
 EVERYWEEK = 'everyweek'
34 37
 EVERYMONTH = 'everymonth'
35 38
 
36
-FREQUENCE_CHOICES = [(EVERYDAY, _('Every Day')),
37
-                     (EVERYWEEK, _('Every Week')),
38
-                     (EVERYMONTH, _('Every Month'))]
39
-FREQUENCE_DICT = collections.OrderedDict(FREQUENCE_CHOICES)
39
+CRONTAB_FREQUENCE_CHOICES = [(EVERYDAY, _('Every Day')),
40
+                             (EVERYWEEK, _('Every Week')),
41
+                             (EVERYMONTH, _('Every Month'))]
42
+CRONTAB_FREQUENCE_DICT = collections.OrderedDict(CRONTAB_FREQUENCE_CHOICES)
40 43
 
41 44
 
42 45
 class CrontabUtil(object):
@@ -78,7 +81,9 @@ class CrontabUtil(object):
78 81
 
79 82
     @staticmethod
80 83
     def convert_from_crontab(dict_crontab):
81
-        data = {}
84
+        data = {
85
+            'format': dict_crontab['format']
86
+        }
82 87
         if dict_crontab["format"] == CRONTAB:
83 88
             pattern = dict_crontab["pattern"]
84 89
             patterns = pattern.split(" ")
@@ -86,18 +91,124 @@ class CrontabUtil(object):
86 91
                 if patterns[2] == "*" \
87 92
                         and patterns[3] == "*" \
88 93
                         and patterns[4] == "*":
89
-                    data["frequence"] = FREQUENCE_DICT[EVERYDAY]
94
+                    data["frequence"] = CRONTAB_FREQUENCE_DICT[EVERYDAY]
90 95
                 elif patterns[2] == "*" \
91 96
                         and patterns[3] == "*" \
92 97
                         and patterns[4] != "*":
93
-                    data["frequence"] = FREQUENCE_DICT[EVERYWEEK]
94
-                    data["day"] = DAY_DICT[patterns[4]]
98
+                    data["frequence"] = CRONTAB_FREQUENCE_DICT[EVERYWEEK]
99
+                    data["day"] = CRONTAB_DAY_DICT[patterns[4]]
95 100
                 elif patterns[2] != "*" \
96 101
                         and patterns[3] == "*" \
97 102
                         and patterns[4] == "*":
98
-                    data["frequence"] = FREQUENCE_DICT[EVERYMONTH]
103
+                    data["frequence"] = CRONTAB_FREQUENCE_DICT[EVERYMONTH]
99 104
                     data["date"] = patterns[2]
100 105
 
101 106
                 data["time"] = '%s:%s' % (patterns[1].zfill(2),
102 107
                                           patterns[0].zfill(2))
103 108
         return data
109
+
110
+CALENDAR = 'calendar'
111
+CALENDAR_DAY_CHOICES = [('1', _('MO')),
112
+                        ('2', _('TU')),
113
+                        ('3', _('WE')),
114
+                        ('4', _('TH')),
115
+                        ('5', _('FR')),
116
+                        ('6', _('SA')),
117
+                        ('0', _('SU'))]
118
+CALENDAR_DAY_DICT = collections.OrderedDict(CALENDAR_DAY_CHOICES)
119
+CALENDAR_DAY_MAPPING = [('MO', _('Monday')),
120
+                        ('TU', _('Tuesday')),
121
+                        ('WE', _('Wednesday')),
122
+                        ('TH', _('Thursday')),
123
+                        ('FR', _('Friday')),
124
+                        ('SA', _('Saturday')),
125
+                        ('SU', _('Sunday'))]
126
+CALENDAR_DAY_MAPPING_DICT = collections.OrderedDict(CALENDAR_DAY_MAPPING)
127
+MINUTELY = 'MINUTELY'
128
+HOURLY = 'HOURLY'
129
+DAILY = 'DAILY'
130
+WEEKLY = 'WEEKLY'
131
+MONTHLY = 'MONTHLY'
132
+
133
+
134
+class CalendarUtil(object):
135
+    """Convert to or from calendar format."""
136
+    @staticmethod
137
+    def convert_to_calendar(data):
138
+        dict_calendar = {
139
+            "format": CALENDAR,
140
+        }
141
+
142
+        pattern_frequence = ''
143
+        if data['frequence'] == EVERYMONTH:
144
+            pattern_frequence = MONTHLY
145
+        elif data['frequence'] == EVERYWEEK:
146
+            pattern_frequence = WEEKLY
147
+        elif data['frequence'] == EVERYDAY:
148
+            pattern_frequence = DAILY
149
+        calendar_event = Event()
150
+        rule_pattern = {
151
+            'freq': pattern_frequence,
152
+            'byhour': data["time"].hour,
153
+            'byminute': data["time"].minute,
154
+        }
155
+
156
+        if pattern_frequence == MONTHLY:
157
+            rule_pattern['bymonthday'] = data["date"]
158
+        elif pattern_frequence == WEEKLY:
159
+            rule_pattern['byday'] = CALENDAR_DAY_DICT[data["day"]]
160
+
161
+        calendar_event.add('rrule', rule_pattern)
162
+        dict_calendar['pattern'] = calendar_event.to_ical()
163
+        return dict_calendar
164
+
165
+    @staticmethod
166
+    def decode_calendar_pattern(pattern):
167
+        try:
168
+            pattern.index('\\')
169
+            pattern_dict = jsonutils.loads('{"pattern": "%s"}' % pattern)
170
+            return pattern_dict["pattern"]
171
+        except Exception:
172
+            return pattern
173
+
174
+    @staticmethod
175
+    def convert_from_calendar(dict_calendar):
176
+        data = {
177
+            'format': dict_calendar['format']
178
+        }
179
+        if dict_calendar["format"] == CALENDAR:
180
+            pattern = dict_calendar["pattern"]
181
+            calendar_event = Component.from_ical(
182
+                CalendarUtil.decode_calendar_pattern(pattern)
183
+            )
184
+            if isinstance(calendar_event, Event):
185
+                calendar_event_rule = calendar_event['RRULE']
186
+                data['frequence'] = calendar_event_rule['FREQ'][0]
187
+
188
+                if data['frequence'] == MONTHLY and not (
189
+                        'INTERVAL' in calendar_event['RRULE']):
190
+                    data['date'] = ' '.join(
191
+                        str(date)
192
+                        for date in calendar_event_rule['BYMONTHDAY'])
193
+
194
+                if data['frequence'] == WEEKLY and not (
195
+                        'INTERVAL' in calendar_event['RRULE']):
196
+                    data['day'] = ' '.join(
197
+                        str(CALENDAR_DAY_MAPPING_DICT[day])
198
+                        for day in calendar_event_rule['BYDAY'])
199
+
200
+                if 'BYHOUR' in calendar_event['RRULE']:
201
+                    data['hour'] = ' '.join(
202
+                        str(hour) for hour in calendar_event_rule['BYHOUR'])
203
+
204
+                if 'BYMINUTE' in calendar_event['RRULE']:
205
+                    data['minute'] = ' '.join(
206
+                        str(minute)
207
+                        for minute in calendar_event_rule['BYMINUTE'])
208
+
209
+                if 'INTERVAL' in calendar_event['RRULE']:
210
+                    data['interval'] = ' '.join(
211
+                        str(interval)
212
+                        for interval in calendar_event_rule['INTERVAL'])
213
+
214
+        return data

+ 10
- 5
karbor_dashboard/triggers/views.py View File

@@ -89,11 +89,16 @@ class DetailView(horizon_views.HorizonTemplateView):
89 89
 
90 90
         if trigger is not None and trigger.properties is not None:
91 91
             if trigger.properties["format"] == utils.CRONTAB:
92
-                data = utils.CrontabUtil\
93
-                    .convert_from_crontab(trigger.properties)
94
-                if data:
95
-                    for key, value in data.items():
96
-                        setattr(trigger, key, value)
92
+                data = utils.CrontabUtil.convert_from_crontab(
93
+                    trigger.properties
94
+                )
95
+            else:
96
+                data = utils.CalendarUtil.convert_from_calendar(
97
+                    trigger.properties
98
+                )
99
+            if data:
100
+                for key, value in data.items():
101
+                    setattr(trigger, key, value)
97 102
 
98 103
         context["trigger"] = trigger
99 104
         context["url"] = reverse("horizon:karbor:triggers:index")

Loading…
Cancel
Save