def test_start_openport_process(self): os.chdir(os.path.dirname(os.path.dirname(__file__))) command = [ 'sudo', '-u', 'pi', '/usr/bin/openport', '2025', '--restart-on-reboot', '--request-port', '31261', '--request-token', 'WkSXfYyksNy4vN2h', '--start-manager', 'False' ] share = Share() share.restart_command = command method = self.os_interaction.start_process self.os_interaction.start_process = Mock(return_value='') try: self.os_interaction.start_openport_process(share) self.os_interaction.start_process.assert_has_calls([ call([ 'env/bin/python', 'apps/openport_app.py', '2025', '--restart-on-reboot', '--request-port', '31261', '--request-token', 'WkSXfYyksNy4vN2h', '--start-manager', 'False' ]) ]) finally: self.os_interaction.start_process = method
def test_double_add_share(self): share = Share(active=True, local_port=444) self.dbhandler.add_share(share) share2 = Share(active=True, local_port=444) self.dbhandler.add_share(share2) self.assertEqual(1, len(self.dbhandler.get_active_shares()))
def test_add_share_other_properties(self): share = Share(local_port=22, restart_command='22 --restart-on-reboot', active=True) self.dbhandler.add_share(share) new_share = Share(local_port=22, active=True) self.dbhandler.add_share(new_share) self.assertEqual(1, len(self.dbhandler.get_active_shares())) self.assertEqual(0, len(self.dbhandler.get_shares_to_restart()))
def test_get_active_shares(self): share1 = Share(active=False) share2 = Share(active=True, local_port=123) self.dbhandler.add_share(share1) self.dbhandler.add_share(share2) active_shares = self.dbhandler.get_active_shares() self.assertEqual(1, len(active_shares)) self.assertEqual(share2.id, active_shares[0].id)
def startOpenportItProcess (self, path): share = Share() share.filePath = path app_dir = self.os_interaction.get_application_dir() if self.os_interaction.is_compiled(): share.restart_command = [os.path.join(app_dir, 'openportit.exe'), path] else: share.restart_command = ['python', os.path.join(app_dir, 'apps/openportit.py'), path] self.os_interaction.start_openport_process(share, hide_message=False, no_clipboard=False)
def test_get_shares_to_restart(self): share1 = Share(active=False) share2 = Share(active=True, local_port=123, restart_command=['sleep', '5']) share3 = Share(active=True, local_port=124, restart_command='') self.dbhandler.add_share(share1) self.dbhandler.add_share(share2) self.dbhandler.add_share(share3) active_shares = self.dbhandler.get_shares_to_restart() self.assertEqual(1, len(active_shares)) self.assertEqual(share2.id, active_shares[0].id)
def test_concurrency(self): dbhandler2 = dbhandler.DBHandler(self.test_db) share = Share() share.local_port = 2224 saved_share = self.dbhandler.add_share(share) retrieved_share = dbhandler2.get_share(saved_share.id) try: self.assertEqual(retrieved_share.local_port, share.local_port) finally: dbhandler2.close()
def test_get_share_by_local_port(self): share1 = Share(active=False, local_port=123) share2 = Share(active=True, local_port=123) self.assertEqual(share2.local_port, 123) share3 = Share(active=True, local_port=1111) self.dbhandler.add_share(share1) self.dbhandler.add_share(share2) self.dbhandler.add_share(share3) share = self.dbhandler.get_share_by_local_port(123) self.assertNotEqual(None, share) self.assertEqual(share2.id, share.id)
def testSaveShare(self): share = Share() share.account_id = 6 share.key_id = 14 share.local_port = 2022 share.id = -1 self.dbhandler.add_share(share) self.assertNotEqual(-1, share.id) share2 = self.dbhandler.get_share(share.id) self.assertEquals(2022, share2.local_port)
def test_remove_doubles(self): old_db = os.path.join(os.path.dirname(__file__), 'testfiles/openport-0.9.1.db') old_db_tmp = os.path.join(os.path.dirname(__file__), 'testfiles/tmp/openport-0.9.1.db') shutil.copy(old_db, old_db_tmp) db_handler = dbhandler.DBHandler(old_db_tmp) def filter_shares_by_local_port(shares, local_port): return [share for share in shares if share.local_port==local_port] all_shares = db_handler.get_all_shares() filtered = filter_shares_by_local_port(all_shares, 22) self.assertTrue(len(filtered) > 1) self.assertEqual(2, len(filtered)) new_share = Share(local_port=22, active=True) db_handler.add_share(new_share) all_shares = db_handler.get_all_shares() filtered = filter_shares_by_local_port(all_shares, 22) self.assertEqual(1, len(filtered)) session = db_handler.get_share_by_local_port(22) self.assertNotEqual(None, session)
def _load_provisioner(self, **arguments): body_string = self._me.__request.body.decode("utf-8") body_data = json.loads(body_string) template = Share().generator_path(filepath=__file__, file="provisioner" + CC.path.sep + body_data["name"] + ".html") return render(request=self._me.__request, template_name=template)
def test_stress_test(self): share = Share() dbhandler2 = dbhandler.DBHandler(self.test_db) try: errors = [] for i in range(100): try: share.local_port = i saved_share = self.dbhandler.add_share(share) retrieved_share = dbhandler2.get_share(saved_share.id) self.assertEqual(retrieved_share.local_port, share.local_port) saved_share = dbhandler2.add_share(share) retrieved_share = self.dbhandler.get_share(saved_share.id) self.assertEqual(retrieved_share.local_port, share.local_port) except AssertionError: print 'error on i:%s' % i errors.append(i) self.assertEqual([], errors) finally: dbhandler2.close()
def test_multi_thread(self): share = Share(local_port=22) self.dbhandler.add_share(share) self.share2 = None def get_share(): self.share2 = self.dbhandler.get_share(share.id) thr = threading.Thread(target=get_share) thr.setDaemon(True) thr.start() sleep(0.3) self.assertNotEqual(None, self.share2) self.assertEqual(share.local_port, self.share2.local_port)
def test_multi_thread_2(self): share = Share(local_port=22, active=True) self.dbhandler.add_share(share) def get_share(): share2 = Share(local_port=23, active=True) self.dbhandler.add_share(share2) # It is super important that the session is closed on the end of the thread, otherwise this will result in # an error when the current thread is trying to close it. self.dbhandler.Session.remove() thr = threading.Thread(target=get_share) thr.setDaemon(True) thr.start() sleep(2) self.assertEqual(2, len(self.dbhandler.get_active_shares()))
def __new__(cls): """ 새로운 instance 생성을 요청할 시, 자신이 소유하고 있는 instance를 반환한다.\n 없을시, 새로 생성하여 반환한다. """ if not hasattr(cls, "_me"): # instance 생성. cls._me = super(CreateMapper, cls).__new__(cls) # 해당 instance의 필수 요구 member 생성. cls._me.__share = Share() cls._me.__u_service = CreateService() # 해당 instance의 필수 요구 변수를 생성. cls._me.__request = None cls._me.__filepath = None return cls._me
def __new__(cls): """ 새로운 instance 생성을 요청할 시, 자신이 소유하고 있는 instance를 반환한다.\n 없을시, 새로 생성하여 반환한다. """ if not hasattr(cls, "_me"): # instance 생성. cls._me = super(PersistentVolumesMapper, cls).__new__(cls) # 해당 instance의 필수 요구 member 생성. cls._me.__share = Share() cls._me.__pv_service = PersistentVolumesService() # 해당 instance의 필수 요구 변수를 생성. cls._me.__request = None cls._me.__cluster_id = None cls._me.__filepath = None return cls._me
def ssh_command_execute_test(request): client = SshClientSample(server="10.0.0.154", username="******", password="******") command = "sudo docker run -d --privileged --restart=unless-stopped --net=host -v " \ "/etc/kubernetes:/etc/kubernetes " \ "-v /var/run:/var/run rancher/rancher-agent:v2.4.11-rc3 --server https://10.0.0.154 --token " \ "qx59tzhkkhcxqbh4zr2gwv9kzqksf46hfxrd2sjzfp45q96r52vp2s --ca-checksum " \ "d4738f1d0dc1266d31103023790974ef316ad78f7df2d11bca3307b72b0e4ebd --worker " print(client.execute(command)) return render(request=request, template_name=Share().generator_path( filepath=__file__, file="developTest.html"), context={"model": "success"})
def test_gc_in_thread(self): str1 = StringIO() ch = logging.StreamHandler(str1) logging.getLogger('sqlalchemy').addHandler(ch) def do_gc(): gc.collect() share = Share(active=True, local_port=444) self.dbhandler.add_share(share) self.assertEqual(1, len(self.dbhandler.get_active_shares())) self.assertEqual(share.id, self.dbhandler.get_share(1).id) self.assertEqual(0, len(self.dbhandler.get_shares_to_restart())) t = threading.Thread(target=do_gc) t.setDaemon(True) t.start() t.join() self.assertTrue(not 'ProgrammingError' in str1.getvalue())
def test_concurrency_2(self): dbhandler2 = dbhandler.DBHandler(self.test_db) try: share = Share(active=True) share.local_port = 2224 share2 = Share(active=True) share2.local_port = 2225 saved_share = self.dbhandler.add_share(share) saved_share2 = dbhandler2.add_share(share2) retrieved_share2 = self.dbhandler.get_share_by_local_port(2225) retrieved_share = self.dbhandler.get_share_by_local_port(2224) self.assertEqual(retrieved_share.local_port, share.local_port) self.assertEqual(retrieved_share2.local_port, share2.local_port) finally: dbhandler2.close()
def do_POST(self): logger.debug('got post on path:%s'%self.path) try: ctype, pdict = cgi.parse_header(self.headers.getheader('content-type')) if ctype == 'multipart/form-data': postvars = cgi.parse_multipart(self.rfile, pdict) elif ctype == 'application/x-www-form-urlencoded': length = int(self.headers.getheader('content-length')) postvars = urlparse.parse_qs(self.rfile.read(length), keep_blank_values=1) else: postvars = {} dict = {} for key in postvars: dict[key] = postvars[key][0] logger.debug('got dict %s on path %s' % (dict, self.path)) logger.debug('known shares: %s' %shares) if self.path.endswith('newShare'): if dict['local_port'] in shares: #update existing share share = shares[dict['local_port']] share.from_dict(dict) else: if dict['type'] == 'Share': share = Share() else: share = Session() share.from_dict(dict) globals = Globals() globals.account_id = share.account_id globals.key_id = share.key_id # logger.debug( 'path: <%s>' % share.filePath ) save_request(share) if onNewShare: onNewShare(share) global shares shares[share.local_port] = share logger.debug('added new share') logger.debug(shares) self.write_response('ok') elif self.path.endswith('successShare'): logger.debug('success') if not dict['local_port'] in shares: logger.error('unknown key: %s in shares %s' % (dict['local_port'], shares)) self.write_response('unknown') else: shares[dict['local_port']].notify_success() self.write_response('ok') elif self.path.endswith('errorShare'): logger.debug('error') if not dict['local_port'] in shares: logger.error('unknown key: %s in shares %s' % (dict['local_port'], shares)) self.write_response('unknown') else: shares[dict['local_port']].notify_error() self.write_response('ok') elif self.path.endswith('stopShare'): logger.debug('stopShare') if not dict['local_port'] in shares: logger.error('unknown key: %s in shares %s' % (dict['local_port'], shares)) self.write_response('unknown') else: shares[dict['local_port']].notify_stop() #self.write_response('ok') # no need to answer except Exception, e: logger.exception(e) self.write_response('an error has occurred')
def test_stop_share(self): share = Share(active=True, local_port=444) self.dbhandler.add_share(share) self.assertEqual(1, share.id) self.dbhandler.stop_share(share) self.assertEqual(False, self.dbhandler.get_share(share.id).active)
def test_as_dict(self): share = Share() share.account_id = 6 share.key_id = 14 share.local_port = 2022 share.id = -1 share.server_session_token = 'abcd' share.server = 'a.openport.io' share.server_port = 1234 share.pid = 234 share.active = True share.restart_command = ['restart', 'command'] share.http_forward = True share.http_forward_address = 'http://jan.u.openport.io' share.open_port_for_ip_link = 'http//openport.io/l/1234/zerazer' share2 = Share().from_dict(share.as_dict()) self.assertEquals(share.id, share2.id) self.assertEquals(share.server, share2.server) self.assertEquals(share.server_port, share2.server_port) self.assertEquals(share.pid, share2.pid) self.assertEquals(share.active, share2.active) self.assertEquals(share.account_id, share2.account_id) self.assertEquals(share.key_id, share2.key_id) self.assertEquals(share.local_port, share2.local_port) self.assertEquals(share.server_session_token, share2.server_session_token) self.assertEquals(share.restart_command, share2.restart_command) self.assertEquals(share.http_forward, share2.http_forward) self.assertEquals(share.http_forward_address, share2.http_forward_address) self.assertEquals(share.open_port_for_ip_link, share2.open_port_for_ip_link)
def run_cis_scan_cluster_test(request): return render(request=request, template_name=Share().generator_path( filepath=__file__, file="clusterTest/runCisScanCluster.html"))
def save_as_rke_templates_cluster_test(request): return render(request=request, template_name=Share().generator_path( filepath=__file__, file="clusterTest/saveAsRkeTemplatesCluster.html"))
def rotate_certificates_cluster_test(request): return render(request=request, template_name=Share().generator_path( filepath=__file__, file="clusterTest/rotateCertificatesCluster.html"))
def restore_snapshot_cluster_test(request): return render(request=request, template_name=Share().generator_path( filepath=__file__, file="clusterTest/restoreSnapshotCluster.html"))
def delete_cluster_test(request): return render(request=request, template_name=Share().generator_path( filepath=__file__, file="clusterTest/deleteCluster.html"))
from core.ssh.ssh_client_sample import SshClientSample from django.shortcuts import render from common import constants as CC from common.share import Share mapper_path = CC.APPLICATION_ROOTDIR + CC.path.sep + Share().generator_path( __file__, CC.APPLICATION_MAPPERDIR) def ssh_command_execute_test(request): client = SshClientSample(server="10.0.0.154", username="******", password="******") command = "sudo docker run -d --privileged --restart=unless-stopped --net=host -v " \ "/etc/kubernetes:/etc/kubernetes " \ "-v /var/run:/var/run rancher/rancher-agent:v2.4.11-rc3 --server https://10.0.0.154 --token " \ "qx59tzhkkhcxqbh4zr2gwv9kzqksf46hfxrd2sjzfp45q96r52vp2s --ca-checksum " \ "d4738f1d0dc1266d31103023790974ef316ad78f7df2d11bca3307b72b0e4ebd --worker " print(client.execute(command)) return render(request=request, template_name=Share().generator_path( filepath=__file__, file="developTest.html"), context={"model": "success"}) def create_cluster_test(request):
def get_share(): share2 = Share(local_port=23, active=True) self.dbhandler.add_share(share2) # It is super important that the session is closed on the end of the thread, otherwise this will result in # an error when the current thread is trying to close it. self.dbhandler.Session.remove()
def test_save_share(self): share = Share() share.account_id = 6 share.key_id = 14 share.local_port = 2022 share.id = -1 share.server_session_token = 'abcd' share.server = 'a.openport.io' share.server_port = 1234 share.pid = 234 share.active = True share.restart_command = ['restart', 'command'] share.http_forward = True share.http_forward_address = 'http://jan.u.openport.io' share.app_management_port = 43122 share.open_port_for_ip_link = 'http//openport.io/l/1234/zerazer' self.dbhandler.add_share(share) self.assertNotEqual(-1, share.id) share2 = self.dbhandler.get_share(share.id) self.assertEquals(share.id, share2.id) self.assertEquals(share.server, share2.server) self.assertEquals(share.server_port, share2.server_port) self.assertEquals(share.pid, share2.pid) self.assertEquals(share.active, share2.active) self.assertEquals(share.account_id, share2.account_id) self.assertEquals(share.key_id, share2.key_id) self.assertEquals(share.local_port, share2.local_port) self.assertEquals(share.server_session_token, share2.server_session_token) self.assertEquals(share.restart_command, share2.restart_command) self.assertEquals(share.http_forward, share2.http_forward) self.assertEquals(share.http_forward_address, share2.http_forward_address) self.assertEquals(share.app_management_port, share2.app_management_port) self.assertEquals(share.open_port_for_ip_link, share2.open_port_for_ip_link)
def test_save(self): share = Share() self.dbhandler.add_share(share) id = share.id self.dbhandler.add_share(share) self.assertEqual(id, share.id)
def start(self): logger.debug("client pid:%s" % os.getpid()) import argparse parser = argparse.ArgumentParser() self.add_default_arguments(parser, local_port_required=False) parser.add_argument("--file-token", default="", help="The token needed to download the file.") parser.add_argument("filename", help="The file you want to openport.") args = parser.parse_args() if args.no_gui: args.hide_message = True args.no_clipboard = True self.args = args def show_message_box(share): import wx wx.MessageBox( "You can now download your file(s) from %s\nThis link has been copied to your clipboard." % (share.get_link()), "Info", wx.OK | wx.ICON_INFORMATION, ) def get_restart_command_for_share(share): command = self.get_restart_command(share) if not "--file-token" in command: command.extend(["--file-token", share.token]) return command self.first_time = True def callback(ignore): # global first_time if not self.first_time: return self.first_time = False share.restart_command = get_restart_command_for_share(share) if args.tray_port > 0: self.inform_tray_app_new(share, args.tray_port, start_tray=(not args.no_tray)) share.error_observers.append(self.error_callback) share.success_observers.append(self.success_callback) if not args.no_clipboard: self.copy_share_to_clipboard(share) if args.hide_message: logger.info("Your file can be downloaded from %s" % share.get_link()) else: self.show_message_box(share) share = Share() if args.file_token == "": share.token = crypt_service.get_token() else: share.token = args.file_token share.filePath = os.path.join(os.getcwd(), args.filename) share.server_port = args.request_port share.local_port = args.local_port share.server_session_token = args.request_token self.session = share self.open_port_file(share, callback) while True: sleep(1)
def get_share(self, path): share = Share() share.filePath = path share.token = TOKEN return share