-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.py
More file actions
343 lines (271 loc) · 9.73 KB
/
Copy pathclient.py
File metadata and controls
343 lines (271 loc) · 9.73 KB
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
336
337
338
339
340
341
342
import rpyc
import sys
import string
import random
import os
import pathlib
import subprocess
import time
import signal
import timeout_decorator
""" Interactive Client that communicates with Handler and accepts user instructions """
#Directory Address
DIRECTORY_ADDR = 'localhost'
DIRECTORY_PORT = 12345
# backup_directory_address
BACKUP_DIRECTORY_ADDR = 'localhost'
BACKUP_DIRECTORY_PORT = 12346
TEMP_DIR = str(pathlib.Path().absolute()) + "/tmp/"
USER_INPUT_TIMEOUT = 5
LEASE_TIME = 30
# random string generator
def get_random_string():
letters = string.ascii_lowercase
result_str = ''.join(random.choice(letters) for i in range(9))
return result_str
# create file in filesystem
def create_file(handler, filename):
try:
handler.create(filename)
except ValueError as e:
print("File Name Exists; Try another File Name")
# seek file in filesystem
def seek_file(handler, filename):
try:
data = handler.read(filename)
print("File found.")
except ValueError as e:
print("File not found.")
# read file in filesystem
def read_file(handler, filename):
try:
data = handler.read(filename)
print(data)
except ValueError as e:
print(e)
# Write Commit to Handler
def write_file(handler, filename, commit_id):
with open(TEMP_DIR + str(filename), 'r') as f:
data = f.read()
try:
handler.write(filename, commit_id, data)
except ValueError as e:
print("Error Writing")
print(e)
print("Try again later")
# receives timed user input
@timeout_decorator.timeout(5)
def timed_input(input_str=None):
if input_str is not None:
print(input_str)
s = input("Would you like to extend lease? ")
return s
@timeout_decorator.timeout(LEASE_TIME)
def timed_write():
s = input("Press any key when done..")
return
# Supports lease extension logic;
# accepts user input before timeout
# commits otherwise
def timed_commit(handler, filename, commit_id, input_str=None):
try:
user_input = timed_input(input_str)
if user_input[0] == "Y":
print("Asking to extend lease..")
try:
can_extend, lease_time = handler.extend_lease(filename, commit_id)
except ValueError as e:
raise e
print(can_extend, lease_time)
if can_extend:
print("Request to extend lease granted..")
print("Continue writing..")
try:
timed_write()
timed_commit(handler, filename, commit_id)
except:
timed_commit(handler, filename, commit_id, input_str="Your time is up")
else:
print("Lease extension was denied..")
print("Committing..")
write_file(handler, filename, commit_id)
else:
print("User didn't ask for lease..")
print("Committing..")
write_file(handler, filename, commit_id)
except timeout_decorator.timeout_decorator.TimeoutError:
print("User response not found..")
print("Committing..")
write_file(handler, filename, commit_id)
# Write (Pessimistic)
def write(handler, filename):
global LEASE_TIME
print("Please wait while others finish writing...")
commit_id = get_random_string()
request_info = handler.write_request(filename, commit_id)
if request_info is None:
print("File not Found")
return
write_info = request_info[0]
time_stamp = request_info[1]
lease_time = LEASE_TIME
ready_to_write = write_info[0]
while not ready_to_write:
queue_number = write_info[1]
sleep_time = (10 * int(queue_number))
time.sleep(sleep_time)
request_info = handler.write_request(filename, commit_id, timestamp_str=time_stamp)
# In case file is deleted by previous action on queue
if request_info is None:
print("File not Found")
return
write_info = request_info[0]
ready_to_write = write_info[0]
time_stamp = request_info[1]
LEASE_TIME = write_info[1] - 5
file_data = write_info[2]
if not os.path.exists(TEMP_DIR):
os.mkdir(TEMP_DIR)
with open(TEMP_DIR + str(filename), 'w') as f:
f.write(file_data)
print("*****************WRITE***********************")
print("Opening file for write...")
print("File will auto commit after %s seconds; unless you ask for extension." % (str(LEASE_TIME)))
p = subprocess.call(['open', '-a', 'TextEdit', TEMP_DIR + str(filename)])
try:
timed_write()
timed_commit(handler, filename, commit_id)
except:
timed_commit(handler, filename, commit_id, input_str="\nYour time is up")
# Delete
def delete(handler, filename):
global LEASE_TIME
print("Please wait while others finish writing...")
commit_id = get_random_string()
request_info = handler.write_request(filename, commit_id)
if request_info is None:
print("File not Found")
return
write_info = request_info[0]
time_stamp = request_info[1]
lease_time = LEASE_TIME
ready_to_write = write_info[0]
while not ready_to_write:
queue_number = write_info[1]
sleep_time = (LEASE_TIME * int(queue_number))
time.sleep(sleep_time)
request_info = handler.write_request(filename, commit_id, timestamp_str=time_stamp)
# In case file is deleted by previous action on queue
if request_info is None:
print("File not Found")
return
write_info = request_info[0]
ready_to_write = write_info[0]
time_stamp = request_info[1]
try:
handler.delete(filename, commit_id)
print("Deleted %s" % (filename))
if os.path.exists(TEMP_DIR + str(filename)):
os.remove(TEMP_DIR + str(filename))
except ValueError:
print("File Not found")
# Append to file
def append(handler, filename):
try:
data = input("\nEnter string to append: ")
new_data = handler.append(filename, data)
print("New data at file:")
print(new_data)
except ValueError as e:
print("File not found")
# Optimistic write
def overwrite(handler_addr, filename):
try:
con_handler = rpyc.connect(host=handler_addr[0], port=handler_addr[1])
handler = con_handler.root.Handler()
data, version_id = handler.optimistic_write_request(filename)
con_handler.close()
# Creating temp file on Client machine
if not os.path.exists(TEMP_DIR):
os.mkdir(TEMP_DIR)
with open(TEMP_DIR + str(filename), 'w') as f:
f.write(data)
print("*****************OPTIMISTIC WRITE***********************")
p = subprocess.call(['open', '-a', 'TextEdit', TEMP_DIR + str(filename)])
keyboard_interrupt = input("Press any key when done..")
with open(TEMP_DIR + str(filename), 'r') as f:
data = f.read()
new_version_id = version_id + 1
try:
con_handler = rpyc.connect(host=handler_addr[0], port=handler_addr[1])
handler = con_handler.root.Handler()
can_write = handler.optimistic_write_commit(filename, new_version_id, data)
if can_write:
print("Write completed successfully")
con_handler.close()
else:
print("Your file version is out of data")
print("Please sync before writing")
con_handler.close()
except ValueError as e:
print("Error Writing")
print(e)
print("Try again later")
con_handler.close()
except ValueError as e:
print("Error writing")
con_handler.close()
# Connect to Directory
def directory_connect():
try:
con = rpyc.connect(DIRECTORY_ADDR, port=DIRECTORY_PORT)
return con
except ConnectionError:
con = rpyc.connect(BACKUP_DIRECTORY_ADDR, port=BACKUP_DIRECTORY_PORT)
return con
# Connect to Handler
def try_handler_connect():
# Request Connection to Directory
con_primary = directory_connect()
directory = con_primary.root.Directory()
handler_addr = directory.connect_request_client()
if handler_addr is None:
return None
else:
print(handler_addr)
return handler_addr
def main():
handler_addr = try_handler_connect()
if handler_addr is None:
print("No Live Server Found")
else:
con_handler = rpyc.connect(host=handler_addr[0], port=handler_addr[1])
handler = con_handler.root.Handler()
print("Connected to" + str(handler_addr[0]) + ":" + str(handler_addr[1]))
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
take_input = True
while (take_input):
arg = input("What would you like to do next? ")
args = arg.split(" ")
if args[0] == "exit":
take_input = False
# Handle Client operation
elif args[0] == "create":
create_file(handler, filename=args[1])
elif args[0] == "seek":
seek_file(handler, filename=args[1])
elif args[0] == "read":
read_file(handler, filename=args[1])
elif args[0] == "write":
write(handler, filename=args[1])
elif args[0] == "delete":
delete(handler, filename=args[1])
elif args[0] == "append":
append(handler, filename=args[1])
elif args[0] == "overwrite":
overwrite(handler_addr, filename=args[1])
else:
print("Error reading client request")
if __name__ == "__main__":
#main(sys.argv[1:])
main()