-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAzureUserPool.py
335 lines (274 loc) · 11.6 KB
/
AzureUserPool.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
__author__ = 'Natalie'
import os
from time import sleep
from sys import stderr
from copy import copy
from azure import *
from validate_email import validate_email
import AzureUser
from AzureSimulation import sms, blob_service
from AzureTools import comp_user
class AzureUserPool:
def __init__(self):
self.user_list = {}
self.curr_user = AzureUser.AzureUser()
def add_user(self, name="", email="", ARG=False):
"""
The provided username is used to to create a new 'account' where simulations
can be stored and accessed. The client's username is used to create a cloud service
which will run all their simulations on VMs and to create a storage account where
input and results files and loaded/downloaded.
:param name:
:param ARG:
:return:
"""
# Check that there is room for more cloud services.
subscription = sms.get_subscription()
services_available = subscription.max_hosted_services - subscription.current_hosted_services
if ARG:
self.curr_user.username = name
self.curr_user.email = email
if not validate_email(self.curr_user.email):
stderr.write("\nEmail invalid")
exit(1)
if not services_available:
stderr.write('This Azure subscription has reached capacity. To delete an old account, use the -d flag.')
exit(1)
# Check that username has correct syntax and is available
valid = self.curr_user.check_username()
# If valid a cloud service is created.
if valid:
self.setup_account()
self.save_user()
# If not valid, the program exits
else:
exit(1)
else:
if not services_available:
stderr.write('This Azure subscription has reached capacity.')
return 1
if self.user_getUsername() == 1:
return 1
if self.user_getEmail() == 1:
return 1
self.setup_account()
self.save_user()
return 0
def user_getUsername(self):
"""
User chooses a username which is checked for uniqueness and validity
:return:
"""
# Choose username
print "\nRestrictions:\n" \
"Usernames can only contain numbers, letters, and hyphens.\n" \
'The first and last characters must be a number or a letter.\n' \
'Must be between 3 and 10 characters.' \
# Assign the username
self.curr_user.username= raw_input('\nChoose username: ')
# Username is not valid
while self.curr_user.check_username() == False:
option = None
while option not in ['1', '2', '3']:
option = raw_input('(1) Choose another username\n'
'(2) Back to login\n'
'(3) Quit\n'
'>> ')
if option not in ['1', '2', '3']:
stderr.write("\nInput not recognized.\n")
sleep(0.5)
if option == '1':
self.curr_user.username= raw_input('\nChoose username: ')
elif option == '2':
return 1
elif option == '3':
quit(0)
def user_getEmail(self):
"""
User gives their email so that results can be sent to the directly
:return:
"""
# Assign the username
self.curr_user.email= raw_input('\nPlease, enter an email address to receive your results: ')
# Email is not valid
if not validate_email(self.curr_user.email):
print "\nEmail invalid"
option = None
while option not in ['1', '2', '3']:
option = raw_input('\n(1) Enter email again\n'
'(2) Back to login\n'
'(3) Quit\n'
'>> ')
if option not in ['1', '2', '3']:
stderr.write("\nInput not recognized.\n")
sleep(0.5)
if option == '1':
self.curr_user.email= raw_input('\nPlease, enter an email address to receive your results: ')
elif option == '2':
return 1
elif option == '3':
quit(0)
def save_user(self):
"""
The current user is saved to the UserPool list
:return:
"""
self.curr_user.save_curr_sim() # saves current simulation of the current user
key = copy(self.curr_user.username)
val = copy(self.curr_user)
self.user_list[key] = val # saves a copy of the user to the user_list
def logout(self):
"""
curr_user is given a new object
:return:
"""
key = copy(self.curr_user.username)
val = copy(self.curr_user)
self.user_list[key] = val # so that changing curr_user when someone logs back in won't alter the dictionary entry
self.curr_user = AzureUser.AzureUser()
def setup_account(self):
"""
Creates a container for the user in a Azure storage account and creates a simulation folder
for simulation results on the user's computer
:return:
"""
########## Create Cloud Service #############
label = 'IMOD simulation for ' + self.curr_user.username
location = 'East US'
try:
sms.create_hosted_service(service_name=self.curr_user.username, label=label, description=label, location=location)
except:
stderr.write("An error occurred while creating a cloud service for your account")
exit(1)
############ Create User Storage ############
# Creates a storage container for the user to upload input files
# and download results files. Named after the username.
print '\nCreating storage space in cloud...'
try:
blob_service.create_container(self.curr_user.username.lower())
except:
stderr.write("There was an error creating storage for your account.")
exit(1)
######### Create Simulation Folder ##########
print '\nCreating simulation folder...'
new_path = 'C:/Users/' + comp_user + '/Simulations'
if not os.path.exists(new_path):
os.makedirs(new_path)
new_path = 'C:/Users/' + comp_user + '/Simulations/' + self.curr_user.username
if not os.path.exists(new_path):
os.makedirs(new_path)
def sign_in(self, name="", ARG=False):
"""
User signs in via commandline or UI with their username, loading the appropriate object from the UserPool
:param name:
:param ARG:
:return:
"""
if(ARG):
exists = self.check_user_exists(name)
if not exists:
stderr.write("Username does not exist. Use the '-new' flag to create a new account.")
exit(1)
else:
self.curr_user = self.user_list[name]
else:
while True:
name = raw_input('\nEnter username: ')
# Check username exists
exists = self.check_user_exists(name)
# Username does not exist
if not exists:
stderr.write('\nUsername does not exist.\n')
sleep(0.5)
option = None
while option not in ['1', '2', '3']:
option = raw_input(
'(1) Re-enter username\n'
'(2) Back to login\n'
'(3) Quit\n'
'>> ')
if option not in ['1', '2', '3']:
stderr.write("\nInput not recognized.\n")
sleep(0.5)
elif option == '2':
return 1
elif option == '3':
quit(0)
else:
self.curr_user = self.user_list[name]
return 0
def check_user_exists(self, name):
"""
Checks that the username used to login exists, that is that there is a cloud service for this username.
:param name:
:return:
"""
services = sms.list_hosted_services() # Lists all cloud services
# Checks that given username exists as a cloud service
exists1 = False
exists2 = False
for hosted_service in services:
if hosted_service.service_name == name:
exists1 = True
break
if self.user_list.has_key(name):
exists2 = True
return (exists1 and exists2)
def delete_account(self, ARG=False):
"""
Deletes the specified user account. This includes deleting the associated cloud service, storage container, and
simulation file.
:param ARG:
:return:
"""
if self.check_user_exists(self.curr_user.username):
user_input = raw_input("\nAre you sure you want to delete " + self.curr_user.username + "'s account? (y/n): ")
if user_input == 'y':
print '\nDeleting ' + self.curr_user.username + '\'s account...'
wait = True
first = True
# Deletes deployment on user's cloud service if needed
while wait:
service = sms.get_hosted_service_properties(self.curr_user.username, True)
if service.deployments:
try:
sms.delete_deployment(self.curr_user.username, self.curr_user.username)
except WindowsAzureConflictError:
if first:
print '\nWindows Azure is currently performing an operation on this account that ' \
'requires exclusive access. \nPlease, wait...'
first = False
except:
stderr.write('\nAn error occurred while deleting your account.')
if ARG:
exit(1)
else:
sleep(0.5)
return 0
else:
wait = False
try:
sms.delete_hosted_service(self.curr_user.username)
blob_service.delete_container(self.curr_user.username.lower())
except not WindowsAzureMissingResourceError:
stderr.write('\nAn error occurred while deleting your account.')
if ARG:
exit(1)
else:
return 0
#path = 'C:/Users/' + comp_user + '/Simulations/' + self.curr_user.username + '/' + self.curr_user.username + \
# '_simulations.txt'
#if os.path.exists(path):
# os.remove(path)
self.user_list.pop(self.curr_user.username)
return 1;
elif user_input == 'n':
return 0
else:
stderr.write('')
else:
stderr.write('Account does not exist.')
if ARG:
exit(1)
else:
return 0