forked from pritunl/pritunl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__main__.py
452 lines (364 loc) · 14 KB
/
__main__.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
import pritunl
import optparse
import sys
import os
import time
import json
USAGE = """\
Usage: pritunl [command] [options]
Command Help: pritunl [command] --help
Commands:
start Start server
version Print the version and exit
setup-key Print the setup key and exit
default-password Print the default administrator password
reset-password Reset administrator password
reset-version Reset database version to server version
reset-ssl-cert Reset the server ssl certificate
reconfigure Reconfigure database connection
set-mongodb Set the mongodb uri
logs View server logs
clear-logs Clear server logs"""
def main(default_conf=None):
if len(sys.argv) > 1:
cmd = sys.argv[1]
else:
cmd = 'start'
parser = optparse.OptionParser(usage=USAGE)
if cmd == 'start':
parser.add_option('-d', '--daemon', action='store_true',
help='Daemonize process')
parser.add_option('-p', '--pidfile', type='string',
help='Path to create pid file')
parser.add_option('-c', '--conf', type='string',
help='Path to configuration file')
parser.add_option('-q', '--quiet', action='store_true',
help='Suppress logging output')
elif cmd == 'logs':
parser.add_option('--archive', action='store_true',
help='Archive log file')
parser.add_option('--tail', action='store_true',
help='Tail log file')
parser.add_option('--limit', type='int',
help='Limit log lines')
parser.add_option('--natural', action='store_true',
help='Natural log sort')
elif cmd == 'set':
parser.disable_interspersed_args()
(options, args) = parser.parse_args()
if hasattr(options, 'conf') and options.conf:
conf_path = options.conf
else:
conf_path = default_conf
pritunl.set_conf_path(conf_path)
if cmd == 'version':
print '%s v%s' % (pritunl.__title__, pritunl.__version__)
sys.exit(0)
elif cmd == 'setup-key':
from pritunl import setup
from pritunl import settings
setup.setup_loc()
print settings.local.setup_key
sys.exit(0)
elif cmd == 'reset-version':
from pritunl.constants import MIN_DATABASE_VER
from pritunl import setup
from pritunl import utils
setup.setup_db()
utils.set_db_ver(pritunl.__version__, MIN_DATABASE_VER)
time.sleep(.2)
print 'Database version reset to %s' % pritunl.__version__
sys.exit(0)
elif cmd == 'reset-password':
from pritunl import setup
from pritunl import auth
setup.setup_db()
username, password = auth.reset_password()
print 'Administrator password successfully reset:\n' + \
' username: "%s"\n password: "%s"' % (username, password)
sys.exit(0)
elif cmd == 'default-password':
from pritunl import setup
from pritunl import auth
setup.setup_db()
username, password = auth.get_default_password()
if not password:
print 'No default password available, use reset-password'
else:
print 'Administrator default password:\n' + \
' username: "%s"\n password: "%s"' % (username, password)
sys.exit(0)
elif cmd == 'reconfigure':
from pritunl import setup
from pritunl import settings
setup.setup_loc()
settings.conf.mongodb_uri = None
settings.conf.commit()
time.sleep(.2)
print 'Database configuration successfully reset'
sys.exit(0)
elif cmd == 'get':
from pritunl import setup
from pritunl import settings
setup.setup_db_host()
if len(args) != 2:
raise ValueError('Invalid arguments')
split = args[1].split('.')
key_str = None
group_str = split[0]
if len(split) > 1:
key_str = split[1]
if group_str == 'host':
group = settings.local.host
else:
group = getattr(settings, group_str)
if key_str:
val = getattr(group, key_str)
print '%s.%s = %s' % (group_str, key_str,
json.dumps(val, default=lambda x: str(x)))
else:
for field in group.fields:
val = getattr(group, field)
print '%s.%s = %s' % (group_str, field,
json.dumps(val, default=lambda x: str(x)))
sys.exit(0)
elif cmd == 'set':
from pritunl.constants import HOSTS_UPDATED
from pritunl import setup
from pritunl import settings
from pritunl import event
from pritunl import messenger
setup.setup_db_host()
if len(args) != 3:
raise ValueError('Invalid arguments')
group_str, key_str = args[1].split('.')
if group_str == 'host':
group = settings.local.host
else:
group = getattr(settings, group_str)
val_str = args[2]
try:
val = json.loads(val_str)
except ValueError:
val = json.loads(json.JSONEncoder().encode(val_str))
setattr(group, key_str, val)
if group_str == 'host':
settings.local.host.commit()
event.Event(type=HOSTS_UPDATED)
messenger.publish('hosts', 'updated')
else:
settings.commit()
time.sleep(.2)
print '%s.%s = %s' % (group_str, key_str,
json.dumps(getattr(group, key_str), default=lambda x: str(x)))
print 'Successfully updated configuration. This change is ' \
'stored in the database and has been applied to all hosts ' \
'in the cluster.'
sys.exit(0)
elif cmd == 'unset':
from pritunl import setup
from pritunl import settings
setup.setup_db()
if len(args) != 2:
raise ValueError('Invalid arguments')
group_str, key_str = args[1].split('.')
group = getattr(settings, group_str)
group.unset(key_str)
settings.commit()
time.sleep(.2)
print '%s.%s = %s' % (group_str, key_str,
json.dumps(getattr(group, key_str), default=lambda x: str(x)))
print 'Successfully updated configuration. This change is ' \
'stored in the database and has been applied to all hosts ' \
'in the cluster.'
sys.exit(0)
elif cmd == 'set-mongodb':
from pritunl import setup
from pritunl import settings
setup.setup_loc()
if len(args) > 1:
mongodb_uri = args[1]
else:
mongodb_uri = None
settings.conf.mongodb_uri = mongodb_uri
settings.conf.commit()
time.sleep(.2)
print 'Database configuration successfully set'
sys.exit(0)
elif cmd == 'reset-ssl-cert':
from pritunl import setup
from pritunl import settings
setup.setup_db()
settings.app.server_cert = None
settings.app.server_key = None
settings.app.acme_timestamp = None
settings.app.acme_key = None
settings.app.acme_domain = None
settings.commit()
time.sleep(.2)
print 'Server ssl certificate successfully reset'
sys.exit(0)
elif cmd == 'destroy-secondary':
from pritunl import setup
from pritunl import logger
from pritunl import mongo
setup.setup_db()
print 'Destroying secondary database...'
mongo.get_collection('clients').drop()
mongo.get_collection('clients_pool').drop()
mongo.get_collection('transaction').drop()
mongo.get_collection('queue').drop()
mongo.get_collection('tasks').drop()
mongo.get_collection('messages').drop()
mongo.get_collection('users_key_link').drop()
mongo.get_collection('auth_sessions').drop()
mongo.get_collection('auth_csrf_tokens').drop()
mongo.get_collection('auth_limiter').drop()
mongo.get_collection('otp').drop()
mongo.get_collection('otp_cache').drop()
mongo.get_collection('sso_tokens').drop()
mongo.get_collection('sso_push_cache').drop()
mongo.get_collection('sso_client_cache').drop()
mongo.get_collection('sso_passcode_cache').drop()
setup.upsert_indexes()
server_coll = mongo.get_collection('servers')
server_coll.update_many({}, {
'$set': {
'status': 'offline',
'instances': [],
'instances_count': 0,
},
'$unset': {
'network_lock': '',
'network_lock_ttl': '',
},
})
print 'Secondary database destroyed'
sys.exit(0)
elif cmd == 'repair-database':
from pritunl import setup
from pritunl import logger
from pritunl import mongo
setup.setup_db()
print 'Repairing database...'
mongo.get_collection('clients').drop()
mongo.get_collection('clients_pool').drop()
mongo.get_collection('transaction').drop()
mongo.get_collection('queue').drop()
mongo.get_collection('tasks').drop()
mongo.get_collection('messages').drop()
mongo.get_collection('users_key_link').drop()
mongo.get_collection('auth_sessions').drop()
mongo.get_collection('auth_csrf_tokens').drop()
mongo.get_collection('auth_limiter').drop()
mongo.get_collection('otp').drop()
mongo.get_collection('otp_cache').drop()
mongo.get_collection('sso_tokens').drop()
mongo.get_collection('sso_push_cache').drop()
mongo.get_collection('sso_client_cache').drop()
mongo.get_collection('sso_passcode_cache').drop()
mongo.get_collection('logs').drop()
mongo.get_collection('log_entries').drop()
mongo.get_collection('servers_ip_pool').drop()
setup.upsert_indexes()
server_coll = mongo.get_collection('servers')
server_coll.update_many({}, {
'$set': {
'status': 'offline',
'instances': [],
'instances_count': 0,
},
'$unset': {
'network_lock': '',
'network_lock_ttl': '',
},
})
from pritunl import server
for svr in server.iter_servers():
try:
svr.ip_pool.sync_ip_pool()
except:
logger.exception('Failed to sync server IP pool', 'tasks',
server_id=svr.id,
)
server_coll.update_many({}, {
'$set': {
'status': 'offline',
'instances': [],
'instances_count': 0,
},
'$unset': {
'network_lock': '',
'network_lock_ttl': '',
},
})
print 'Database repair complete'
sys.exit(0)
elif cmd == 'logs':
from pritunl import setup
from pritunl import logger
setup.setup_db()
log_view = logger.LogView()
if options.archive:
if len(args) > 1:
archive_path = args[1]
else:
archive_path = './'
print 'Log archived to: ' + log_view.archive_log(archive_path,
options.natural, options.limit)
elif options.tail:
for msg in log_view.tail_log_lines():
print msg
else:
print log_view.get_log_lines(
natural=options.natural,
limit=options.limit,
)
sys.exit(0)
elif cmd == 'clear-logs':
from pritunl import setup
from pritunl import logger
from pritunl import mongo
from pritunl import settings
setup.setup_db()
mongo.get_collection('logs').drop()
mongo.get_collection('log_entries').drop()
prefix = settings.conf.mongodb_collection_prefix or ''
log_limit = settings.app.log_limit
mongo.database.create_collection(prefix + 'logs', capped=True,
size=log_limit * 1024, max=log_limit)
log_entry_limit = settings.app.log_entry_limit
mongo.database.create_collection(prefix + 'log_entries', capped=True,
size=log_entry_limit * 512, max=log_entry_limit)
sys.exit(0)
elif cmd != 'start':
raise ValueError('Invalid command')
from pritunl import settings
if options.quiet:
settings.local.quiet = True
if options.daemon:
pid = os.fork()
if pid > 0:
if options.pidfile:
with open(options.pidfile, 'w') as pid_file:
pid_file.write('%s' % pid)
sys.exit(0)
elif not options.quiet:
print '##############################################################'
print '# #'
print '# /$$ /$$ /$$ #'
print '# |__/ | $$ | $$ #'
print '# /$$$$$$ /$$$$$$ /$$ /$$$$$$ /$$ /$$ /$$$$$$$ | $$ #'
print '# /$$__ $$ /$$__ $$| $$|_ $$_/ | $$ | $$| $$__ $$| $$ #'
print '# | $$ \ $$| $$ \__/| $$ | $$ | $$ | $$| $$ \ $$| $$ #'
print '# | $$ | $$| $$ | $$ | $$ /$$| $$ | $$| $$ | $$| $$ #'
print '# | $$$$$$$/| $$ | $$ | $$$$/| $$$$$$/| $$ | $$| $$ #'
print '# | $$____/ |__/ |__/ \____/ \______/ |__/ |__/|__/ #'
print '# | $$ #'
print '# | $$ #'
print '# |__/ #'
print '# #'
print '##############################################################'
pritunl.init_server()
if __name__ == '__main__':
main()