]> git.somenet.org - pub/jan/aic18.git/blob - camunda-overlay/camunda.py
updated design
[pub/jan/aic18.git] / camunda-overlay / camunda.py
1 #!/usr/bin/env python3
2
3 import sys
4 import os
5 import json
6 import requests
7 import argparse
8 from pprint import pprint
9
10 CAMUNDA="http://localhost:8085/engine-rest/"
11
12 def get_current_deployments(key = 'sentiment-analysis'):
13     res = requests.get(CAMUNDA + "deployment")
14     #return [proc for proc in res.json() if proc['name'] == key]
15     return res.json()
16
17 def get_current_process_instances(key = 'sentiment-analysis'):
18     res = requests.get(CAMUNDA + 'process-instance')
19     if (key is None):
20         return res.json()
21     else:
22         return [instance for instance in res.json() if instance['definitionId'].startswith(key + ":")]
23
24 def cleanup_old_deployments(key='sentiment-analysis'):
25     print ("Cleaning up old deployments")
26     for deployment in get_current_deployments(key):
27         res = requests.delete(CAMUNDA + "deployment/" + deployment['id'] + "?cascade=true&skipCustomListeners=true")
28         if (res.status_code == 204):
29             print ("Cleaned up deployment {}".format(deployment['id']))
30         else:
31             print ("Error cleaning old deployment {}: Code: {}".format(deployment['id'], res.status_code))
32             try:
33                 pprint(res.json())
34             except:
35                 pprint(res.content)
36
37 def get_users():
38     res = requests.get(CAMUNDA + "user")
39     return res.json()
40
41 def get_groups():
42     res = requests.get(CAMUNDA + "group")
43     return res.json()
44
45 def cleanup_users(keep = ["demo"]):
46     for user in get_users():
47         # keep user "demo"
48         if user['id'] in keep:
49             continue
50
51         res = requests.delete(CAMUNDA + "user/" + user['id'])
52         if (res.status_code == 204):
53             print ("Cleaned up user {}".format(user['id']))
54         else:
55             print ("Error cleaning user {}: Code: {}".format(user['id'], res.status_code))
56             try:
57                 pprint(res.json())
58             except:
59                 pprint(res.content)
60
61 def cleanup_groups():
62     for group in get_groups():
63         res = requests.delete(CAMUNDA + "group/" + group['id'])
64         if (res.status_code == 204):
65             print ("Cleaned up group {}".format(group['id']))
66         else:
67             print ("Error cleaning group {}: Code: {}".format(group['id'], res.status_code))
68             try:
69                 pprint(res.json())
70             except:
71                 pprint(res.content)
72
73 def get_authorizations():
74     res = requests.get(CAMUNDA + "authorization")
75     return res.json()
76
77 def create_admin_user():
78     # create user
79     params = {
80             "profile": {
81                 "id": "admin",
82                 "firstName": "Admin",
83                 "lastName": "User",
84                 "email": "aic@dsg.tuwien.ac.at"
85                 },
86             "credentials": {
87                 "password": "admin"
88                 }
89             }
90     res = requests.post(CAMUNDA + "user/create", json=params)
91     if (res.status_code == 204):
92         print ("Created user admin")
93     else:
94         print ("Error creating user admin: Code: {}".format(res.status_code))
95         try:
96             pprint(res.json())
97         except:
98             pprint(res.content)
99
100
101     # clean all authorizations
102     for auth in get_authorizations():
103         res = requests.delete(CAMUNDA + "authorization/" + auth['id'])
104         if (res.status_code == 204):
105             print ("Cleaned up authorization {}".format(auth['id']))
106         else:
107             print ("Error cleaning authorization {}: Code: {}".format(auth['id'], res.status_code))
108             try:
109                 pprint(res.json())
110             except:
111                 pprint(res.content)
112
113
114     # set all permissions for modifying users
115     params = {
116             "type": 1,
117             "permissions": ["ALL"],
118             "userId": "admin",
119             "groupId": None,
120             "resourceType": 1,
121             "resourceId": "admin"
122             }
123     res = requests.post(CAMUNDA + "authorization/create", json=params)
124     if (res.status_code == 200):
125         print ("Set users permissions for admin users")
126     else:
127         print ("Error setting users permissions for admin user: Code: {}".format(res.status_code))
128         try:
129             pprint(res.json())
130         except:
131             pprint(res.content)
132
133     # create admin group
134     params = {
135             "id": "camunda-admin",
136             "name": "camunda BPM Administrators",
137             "type": "SYSTEM"
138             }
139     res = requests.post(CAMUNDA + "group/create", json=params)
140     if (res.status_code == 204):
141         print ("Created user admin")
142     else:
143         print ("Error creating group camunda-admin: Code: {}".format(res.status_code))
144         try:
145             pprint(res.json())
146         except:
147             pprint(res.content)
148
149     # add admin user to camunda-admin
150     res = requests.put(CAMUNDA + "group/camunda-admin/members/admin")
151     if (res.status_code == 204):
152         print ("Added admin to camunda-admin")
153     else:
154         print ("Error adding user admin to group camunda-admin: Code: {}".format(res.status_code))
155         try:
156             pprint(res.json())
157         except:
158             pprint(res.content)
159
160     # set all permissions for admin group
161     for resourceType in range(0, 16):
162         params = {
163                 "type": 1,
164                 "permissions": ["ALL"],
165                 "userId": None,
166                 "groupId": "camunda-admin",
167                 "resourceType": resourceType,
168                 "resourceId": "*"
169                 }
170         res = requests.post(CAMUNDA + "authorization/create", json=params)
171         if (res.status_code == 200):
172             print ("Set group permissions for id {}".format(resourceType))
173         else:
174             print ("Error setting application permissions for admin user: Code: {}".format(res.status_code))
175             try:
176                 pprint(res.json())
177             except:
178                 pprint(res.content)
179
180 def get_filters():
181     res = requests.get(CAMUNDA + "filter")
182     return res.json()
183
184 def cleanup_filters(keep = ["All Tasks"]):
185     for filter in get_filters():
186         # keep filter "All Tasks"
187         if filter['name'] in keep:
188             continue
189
190         res = requests.delete(CAMUNDA + "filter/" + filter['id'])
191         if (res.status_code == 204):
192             print ("Cleaned up filter {}".format(filter['name']))
193         else:
194             print ("Error cleaning filter {} ({}): Code: {}".format(filter['name'], filter['id'], res.status_code))
195             try:
196                 pprint(res.json())
197             except:
198                 pprint(res.content)
199
200 def create_deployment(cleanup=False):
201     parameters = [
202             ("deployment-name", "sentiment-analysis"),
203             #("enable-duplicate-filtering", "true"),
204             #("deploy-changed-only", "true"),
205             ("file1", open("sentiment-analysis.bpmn")),
206             ("file2", open("forms/input-terms.html")),
207             ("file3", open("forms/download-pdf.html")),
208             ]
209     if cleanup:
210         cleanup_old_deployments()
211     res = requests.post(CAMUNDA + "deployment/create", files=parameters)
212     if (res.status_code == 200):
213         print ("Successfully deployed Sentiment Analysis")
214     else:
215         pprint ("Status Code: {}".format(res.status_code))
216         try:
217             pprint(res.json())
218         except:
219             pprint(res.content)
220
221 def submit_terms(terms):
222     termlist = [{'term': term} for term in terms]
223     # submit to camunda
224     params = {
225             'variables': {
226                 'terms': {
227                     'value': json.dumps(termlist),
228                     'type': "json",
229                     'valueInfo': {
230                         'serializationDataFormat': "application/json",
231                         }
232                     }
233                 }
234             }
235     res = requests.post(CAMUNDA + "process-definition/key/sentiment-analysis/start", json=params)
236     if (res.status_code == 200):
237         print ("Successfully started Sentiment Analysis")
238     else:
239         pprint ("Status Code: {}".format(res.status_code))
240         try:
241             pprint(res.json())
242         except:
243             try:
244                 import xml.dom.minidom
245                 content = res.content.decode('utf-8').replace('<!doctype html>', '')
246                 print(xml.dom.minidom.parseString(content).toprettyxml())
247             except:
248                 pprint(res.content)
249
250 def download_pdf():
251     instances = get_current_process_instances()
252     if len(instances) == 0:
253         print ("Error: no running instance found.")
254         return
255     instance = instances[0]['id']
256     res = requests.get(CAMUNDA + 'process-instance/' + instance + '/variables')
257     try:
258         pprint(res.json())
259     except:
260         pprint(res.content)
261
262 if __name__ == "__main__":
263     parser = argparse.ArgumentParser()
264     parser.add_argument('--no-deploy', dest='deploy', default=True, action='store_false', help="Do not run the deployment step")
265     parser.add_argument('--no-cleanup', dest='cleanup', default=True, action='store_false', help="Initial deploy does not need cleanup")
266     parser.add_argument('--autoclick', dest='autoclick', type=int, default=0, help="How many steps to autoclick")
267     parser.add_argument('--terms', dest='terms', type=str, nargs='*', default=["aic", "TU Wien"], help="How many steps to autoclick")
268     args = parser.parse_args()
269
270     if args.deploy:
271         # initialize camunda process
272         create_deployment(cleanup=args.cleanup)
273         if args.cleanup:
274             cleanup_users()
275             cleanup_groups()
276             cleanup_filters()
277             create_admin_user()
278
279     if args.autoclick >= 1:
280         # start clicking
281         submit_terms(args.terms)
282
283     if args.autoclick >= 2:
284         download_pdf()