Mercurial > repos > yating-l > gonramp_apollo_tools
comparison util/subtools.py @ 0:ce4f91831680 draft default tip
planemo upload for repository https://github.com/Yating-L/suite_gonramp_apollo.git commit 5367a00befb467f162d1870edb91f9face72e894
author | yating-l |
---|---|
date | Fri, 16 Feb 2018 10:57:13 -0500 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:ce4f91831680 |
---|---|
1 #!/usr/bin/env python | |
2 | |
3 """ | |
4 This file include common used functions for converting file format to gff3 | |
5 """ | |
6 from collections import OrderedDict | |
7 import json | |
8 import subprocess | |
9 import os | |
10 import sys | |
11 import tempfile | |
12 import string | |
13 import logging | |
14 | |
15 class PopenError(Exception): | |
16 def __init__(self, cmd, error, return_code): | |
17 self.cmd = cmd | |
18 self.error = error | |
19 self.return_code = return_code | |
20 | |
21 def __str__(self): | |
22 message = "The subprocess {0} has returned the error: {1}.".format( | |
23 self.cmd, self.return_code) | |
24 message = ','.join( | |
25 (message, "Its error message is: {0}".format(self.error))) | |
26 return repr(message) | |
27 | |
28 | |
29 def _handleExceptionAndCheckCall(array_call, **kwargs): | |
30 """ | |
31 This class handle exceptions and call the tool. | |
32 It maps the signature of subprocess.check_call: | |
33 See https://docs.python.org/2/library/subprocess.html#subprocess.check_call | |
34 """ | |
35 stdout = kwargs.get('stdout', subprocess.PIPE) | |
36 stderr = kwargs.get('stderr', subprocess.PIPE) | |
37 shell = kwargs.get('shell', False) | |
38 stdin = kwargs.get('stdin', None) | |
39 | |
40 cmd = array_call[0] | |
41 | |
42 output = None | |
43 error = None | |
44 | |
45 # TODO: Check the value of array_call and <=[0] | |
46 logging.debug("Calling {0}:".format(cmd)) | |
47 logging.debug("%s", array_call) | |
48 logging.debug("---------") | |
49 | |
50 # TODO: Use universal_newlines option from Popen? | |
51 try: | |
52 p = subprocess.Popen(array_call, stdout=stdout, | |
53 stderr=stderr, shell=shell, stdin=stdin) | |
54 | |
55 # TODO: Change this because of possible memory issues => https://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate | |
56 | |
57 output, error = p.communicate() | |
58 | |
59 if stdout == subprocess.PIPE: | |
60 logging.debug("\t{0}".format(output)) | |
61 else: | |
62 logging.debug("\tOutput in file {0}".format(stdout.name)) | |
63 # If we detect an error from the subprocess, then we raise an exception | |
64 # TODO: Manage if we raise an exception for everything, or use CRITICAL etc... but not stop process | |
65 # TODO: The responsability of returning a sys.exit() should not be there, but up in the app. | |
66 if p.returncode: | |
67 if stderr == subprocess.PIPE: | |
68 raise PopenError(cmd, error, p.returncode) | |
69 else: | |
70 # TODO: To Handle properly with a design behind, if we received a option as a file for the error | |
71 raise Exception("Error when calling {0}. Error as been logged in your file {1}. Error code: {2}".format(cmd, stderr.name, p.returncode)) | |
72 | |
73 except OSError as e: | |
74 message = "The subprocess {0} has encountered an OSError: {1}".format( | |
75 cmd, e.strerror) | |
76 if e.filename: | |
77 message = '\n'.join( | |
78 (message, ", against this file: {0}".format(e.filename))) | |
79 logging.error(message) | |
80 sys.exit(-1) | |
81 except PopenError as p: | |
82 message = "The subprocess {0} has returned the error: {1}.".format( | |
83 p.cmd, p.return_code) | |
84 message = '\n'.join( | |
85 (message, "Its error message is: {0}".format(p.error))) | |
86 | |
87 logging.exception(message) | |
88 | |
89 sys.exit(p.return_code) | |
90 except Exception as e: | |
91 message = "The subprocess {0} has encountered an unknown error: {1}".format( | |
92 cmd, e) | |
93 logging.exception(message) | |
94 | |
95 sys.exit(-1) | |
96 return output | |
97 | |
98 def arrow_add_organism(organism_name, organism_dir, public=False): | |
99 array_call = ['arrow', 'organisms', 'add_organism', organism_name, organism_dir] | |
100 if public: | |
101 array_call.append('--public') | |
102 p = _handleExceptionAndCheckCall(array_call) | |
103 #p = subprocess.check_output(array_call) | |
104 return p | |
105 | |
106 def arrow_create_user(user_email, firstname, lastname, password, admin=False): | |
107 """ | |
108 Create a new user of Apollo, the default user_role is "user" | |
109 """ | |
110 array_call = ['arrow', 'users', 'create_user', user_email, firstname, lastname, password] | |
111 if admin: | |
112 array_call += ['--role', 'admin'] | |
113 p = _handleExceptionAndCheckCall(array_call) | |
114 j = json.loads(p) | |
115 if "userId" in j: | |
116 return j['userId'] | |
117 elif "error" in j: | |
118 logging.error("Got error message: %s", j['error']) | |
119 exit(-1) | |
120 | |
121 | |
122 def arrow_delete_user(user_email): | |
123 array_call = ['arrow', 'users', 'delete_user', user_email] | |
124 p = _handleExceptionAndCheckCall(array_call) | |
125 j = json.loads(p) | |
126 if "error" in j: | |
127 logging.error("Got error message: %s", j['error']) | |
128 exit(-1) | |
129 | |
130 def arrow_add_to_group(groupname, user_email): | |
131 if not arrow_get_groups(groupname): | |
132 arrow_create_group(groupname) | |
133 array_call = ['arrow', 'users', 'add_to_group', groupname, user_email] | |
134 p = _handleExceptionAndCheckCall(array_call) | |
135 j = json.loads(p) | |
136 if j != dict(): | |
137 logging.error("Error add user %s to group %s. The user doesn't exist", user_email, groupname) | |
138 | |
139 | |
140 def arrow_remove_from_group(groupname, user_email): | |
141 if arrow_get_groups(groupname): | |
142 array_call = ['arrow', 'users', 'remove_from_group', groupname, user_email] | |
143 p = _handleExceptionAndCheckCall(array_call) | |
144 j = json.loads(p) | |
145 if j != dict(): | |
146 logging.error("Error remove user %s to group %s. The user doesn't exist", user_email, groupname) | |
147 else: | |
148 logging.error("Group %s doesn't exist. Check if you spell the name correctly", groupname) | |
149 | |
150 def arrow_create_group(groupname): | |
151 if arrow_get_groups(groupname): | |
152 logging.error("Group %s already exist. Create a group with another name.", groupname) | |
153 array_call = ['arrow', 'groups', 'create_group', groupname] | |
154 p = _handleExceptionAndCheckCall(array_call) | |
155 | |
156 def arrow_get_groups(groupname): | |
157 array_call = ['arrow', 'groups', 'get_groups'] | |
158 p = _handleExceptionAndCheckCall(array_call) | |
159 all_groups = json.loads(p) | |
160 for g in all_groups: | |
161 if g['name'] == groupname: | |
162 return True | |
163 return False | |
164 | |
165 def arrow_update_organism_permissions(user_id, organism, **user_permissions): | |
166 array_call = ['arrow', 'users', 'update_organism_permissions', str(user_id), str(organism)] | |
167 admin = user_permissions.get("admin", False) | |
168 write = user_permissions.get("write", False) | |
169 read = user_permissions.get("read", False) | |
170 export = user_permissions.get("export", False) | |
171 if admin: | |
172 array_call.append('--administrate') | |
173 if write: | |
174 array_call.append('--write') | |
175 if read: | |
176 array_call.append('--read') | |
177 if export: | |
178 array_call.append('--export') | |
179 p = _handleExceptionAndCheckCall(array_call) | |
180 return p | |
181 | |
182 def arrow_get_users(user_email): | |
183 array_call = ['arrow', 'users', 'get_users'] | |
184 p = _handleExceptionAndCheckCall(array_call) | |
185 all_users = json.loads(p) | |
186 for d in all_users: | |
187 if d['username'] == user_email: | |
188 return d['userId'] | |
189 logging.error("Cannot find user %s", user_email) | |
190 | |
191 def arrow_get_organism(organism_name): | |
192 array_call= ['arrow', 'organisms', 'get_organisms', '--common_name', organism_name] | |
193 p = _handleExceptionAndCheckCall(array_call) | |
194 org = json.loads(p) | |
195 if 'error' not in org: | |
196 return org[0]['id'] | |
197 else: | |
198 logging.debug("Got error msg %s when look for organism %s.", org['error'], organism_name) | |
199 | |
200 def arrow_delete_organism(organism_id): | |
201 array_call = ['arrow', 'organisms', 'delete_organism', str(organism_id)] | |
202 p = _handleExceptionAndCheckCall(array_call) | |
203 return p | |
204 | |
205 def verify_user_login(username, password, apollo_host): | |
206 user_info = {'username': username, 'password': password} | |
207 array_call = ['curl', | |
208 '-b', 'cookies.txt', | |
209 '-c', 'cookies.txt', | |
210 '-H', 'Content-Type:application/json', | |
211 '-d', json.dumps(user_info), | |
212 apollo_host + '/Login?operation=login' | |
213 ] | |
214 p = _handleExceptionAndCheckCall(array_call) | |
215 msg = json.loads(p) | |
216 if 'error' in msg: | |
217 logging.error("The Authentication for user %s failed. Get error message %s", username, msg['error']) | |
218 exit(-1) | |
219 | |
220 |