How to use _drop_remote_namespace method in fMBT

Best Python code snippet using fMBT_python

server.py

Source:server.py Github

copy

Full Screen

...208 del _g_local_namespaces[ns]209 del _g_local_namespace_locks[ns]210 del _g_async_rvs[ns]211 # send notification to all connections in _g_namespace_exports[ns]?212def _drop_remote_namespace(ns):213 daemon_log('drop remote namespace "%s"' % (ns,))214 try:215 rns = _g_remote_namespaces[ns]216 del _g_remote_namespaces[ns]217 rns.__del__()218 except KeyError:219 pass # already dropped220 # send notification to all connections in _g_namespace_exports[ns]?221def _init_remote_namespace(ns, conn, to_remote, from_remote):222 if ns in _g_remote_namespaces:223 raise ValueError('Remote namespace "%s" already registered' % (224 ns,))225 daemon_log('added remote namespace "%s", origin "%s"' % (226 ns, conn.getpeername()))227 _g_remote_namespaces[ns] = Pythonshare_rns(conn, to_remote, from_remote)228def _register_exported_namespace(ns, conn):229 if not ns in _g_namespace_exports:230 _g_namespace_exports[ns] = []231 _g_namespace_exports[ns].append(conn)232def _local_execute(exec_msg, conn_id=None):233 global _g_executing_pythonshare_conn_id234 ns = exec_msg.namespace235 if not ns in _g_local_namespaces:236 code_exc = expr_exc = "no local namespace %s" % (ns,)237 return messages.Exec_rv(code_exc, expr_exc, None)238 if conn_id:239 if not conn_id in _g_namespace_users:240 _g_namespace_users[conn_id] = set([ns])241 else:242 _g_namespace_users[conn_id].add(ns)243 code_exc, expr_exc, expr_rv = None, None, None244 if not exec_msg.lock or _g_local_namespace_locks[ns].acquire():245 _g_executing_pythonshare_conn_id = conn_id246 try:247 if exec_msg.code not in [None, ""]:248 try:249 exec exec_msg.code in _g_local_namespaces[ns]250 except Exception, e:251 code_exc = exception2string(sys.exc_info())252 if exec_msg.expr not in [None, ""]:253 try:254 expr_rv = eval(exec_msg.expr, _g_local_namespaces[ns])255 except Exception, e:256 expr_exc = exception2string(sys.exc_info())257 finally:258 _g_executing_pythonshare_conn_id = None259 if exec_msg.lock:260 try:261 _g_local_namespace_locks[ns].release()262 except thread.error:263 pass # already unlocked namespace264 else:265 code_exc = expr_exc = 'locking namespace "%s" failed' % (ns,)266 if isinstance(expr_rv, pythonshare.messages.Exec_rv):267 return expr_rv268 else:269 return messages.Exec_rv(code_exc, expr_exc, expr_rv)270def _local_async_execute(async_rv, exec_msg):271 exec_rv = _local_execute(exec_msg)272 _g_async_rvs[exec_msg.namespace][async_rv.rvid] = exec_rv273def _remote_execute(ns, exec_msg):274 rns = _g_remote_namespaces[ns]275 pythonshare._send(exec_msg, rns.to_remote)276 # _recv raises EOFError() if disconnected,277 # let it raise through.278 return pythonshare._recv(rns.from_remote)279def _remote_execute_and_forward(ns, exec_msg, to_client, peername=None):280 """returns (forward_status, info)281 forward_status values:282 True: everything successfully forwarded,283 info contains pair (forwarded byte count, full length).284 False: not everything forwarded,285 info contains pair (forwarded byte count, full length).286 to_client file/socket is not functional.287 None: no forwarding,288 info contains Exec_rv that should be sent normally.289 Raises EOFError if connection to remote namespace is not functional.290 The peername parameter is used for logging only.291 """292 client_supports_rv_info = exec_msg.recv_cap_data_info()293 exec_msg.set_recv_cap_data_info(True)294 rns = _g_remote_namespaces[ns]295 pythonshare._send(exec_msg, rns.to_remote)296 from_remote = rns.from_remote297 # Must keep simultaneously two locks:298 # - send lock on to_client299 # - recv lock on from_remote300 pythonshare._acquire_recv_lock(from_remote)301 try:302 response = pythonshare._recv(from_remote, acquire_recv_lock=False)303 if not isinstance(response, messages.Data_info):304 # Got direct response without forward mode305 return (None, response)306 pythonshare._acquire_send_lock(to_client)307 if client_supports_rv_info:308 # send data_info to client309 pythonshare._send(response, to_client, acquire_send_lock=False)310 try:311 if opt_debug and peername:312 daemon_log("%s:%s <= Exec_rv([forwarding %s B])" % (peername + (response.data_length,)))313 forwarded_bytes = pythonshare._forward(314 from_remote, to_client, response.data_length,315 acquire_recv_lock=False,316 acquire_send_lock=False)317 if forwarded_bytes == response.data_length:318 return (True, (forwarded_bytes, response.data_length))319 else:320 return (False, (forwarded_bytes, response.data_length))321 finally:322 pythonshare._release_send_lock(to_client)323 finally:324 exec_msg.set_recv_cap_data_info(client_supports_rv_info)325 pythonshare._release_recv_lock(from_remote)326def _connection_lost(conn_id, *closables):327 if closables:328 pythonshare._close(*closables)329 try:330 for ns in _g_namespace_users[conn_id]:331 try:332 _g_local_namespaces[ns]["pythonshare_ns"].call_on_disconnect(conn_id)333 except KeyError:334 pass335 except KeyError:336 pass337def _serve_connection(conn, conn_opts):338 global _g_async_rv_counter339 global _g_server_shutdown340 if isinstance(conn, client.Connection):341 to_client = conn._to_server342 from_client = conn._from_server343 else: # conn is a connected socket344 to_client = conn.makefile("w")345 from_client = conn.makefile("r")346 try:347 peername = conn.getpeername()348 except socket.error:349 peername = ("unknown", "?")350 if opt_debug:351 daemon_log("connected %s:%s" % peername)352 conn_id = "%s-%s" % (timestamp(), id(conn))353 auth_ok = False354 passwords = [k for k in conn_opts.keys() if k.startswith("password.")]355 kill_server_on_close = conn_opts.get("kill-server-on-close", False)356 if passwords:357 # password authentication is required for this connection358 received_password = pythonshare._recv(from_client)359 for password_type in passwords:360 algorithm = password_type.split(".")[1]361 if type(received_password) == str:362 if (algorithm == "plaintext" and363 received_password == conn_opts[password_type]):364 auth_ok = True365 elif (hasattr(hashlib, algorithm) and366 getattr(hashlib, algorithm)(received_password).hexdigest() ==367 conn_opts[password_type]):368 auth_ok = True369 try:370 if auth_ok:371 pythonshare._send(messages.Auth_rv(True), to_client)372 if opt_debug:373 daemon_log("%s:%s authentication ok" % peername)374 else:375 pythonshare._send(messages.Auth_rv(False), to_client)376 if opt_debug:377 daemon_log("%s:%s authentication failed" % peername)378 except socket.error:379 daemon_log("authentication failed due to socket error")380 auth_ok = False381 else:382 auth_ok = True # no password required383 whitelist_local = conn_opts.get("whitelist_local", None)384 while auth_ok:385 try:386 obj = pythonshare._recv(from_client)387 if opt_debug:388 daemon_log("%s:%s => %s" % (peername + (obj,)))389 except (EOFError, pythonshare.socket.error):390 break391 if isinstance(obj, messages.Register_ns):392 try:393 _init_remote_namespace(obj.ns, conn, to_client, from_client)394 pythonshare._send(messages.Ns_rv(True), to_client)395 # from this point on, this connection is reserved for396 # sending remote namespace traffic. The connection will be397 # used by other threads, this thread stops here.398 return399 except Exception, e:400 pythonshare._send(messages.Ns_rv(False, exception2string(sys.exc_info())), to_client)401 elif isinstance(obj, messages.Drop_ns):402 try:403 if obj.ns in _g_local_namespaces:404 _drop_local_namespace(obj.ns)405 elif obj.ns in _g_remote_namespaces:406 _drop_remote_namespace(obj.ns)407 else:408 raise ValueError('Unknown namespace "%s"' % (obj.ns,))409 pythonshare._send(messages.Ns_rv(True), to_client)410 except Exception, e:411 if opt_debug:412 daemon_log("namespace drop error: %s" % (e,))413 pythonshare._send(messages.Ns_rv(False, exception2string(sys.exc_info())), to_client)414 elif isinstance(obj, messages.Request_ns):415 ns = obj.ns416 if (ns in _g_remote_namespaces or417 ns in _g_local_namespaces):418 _register_exported_namespace(ns, conn)419 pythonshare._send(messages.Ns_rv(True), to_client)420 # from this point on, this connection is reserved for421 # receiving executions on requested namespace. This422 # thread starts serving the connection.423 elif isinstance(obj, messages.Exec):424 ns = obj.namespace425 if ns in _g_remote_namespaces: # execute in remote namespace426 try:427 _fwd_status, _fwd_info = _remote_execute_and_forward(428 ns, obj, to_client, peername)429 if _fwd_status == True:430 # successfully forwarded431 if opt_debug:432 daemon_log("%s:%s forwarded %s B" % (peername + (_fwd_info[0],)))433 exec_rv = None # return value fully forwarded434 elif _fwd_status == False:435 # connection to client is broken436 if opt_debug:437 daemon_log("%s:%s error after forwarding %s/%s B" % (peername + _fwd_info))438 break439 elif _fwd_status is None:440 # nothing forwarded, send return value by normal means441 exec_rv = _fwd_info442 except EOFError:443 daemon_log('connection lost to "%s"' % (ns,))444 _drop_remote_namespace(ns)445 break446 else: # execute in local namespace447 if whitelist_local == None or ns in whitelist_local:448 _init_local_namespace(ns)449 if obj.async:450 # asynchronous execution, return handle (Async_rv)451 _g_async_rv_counter += 1452 rvid = datetime.datetime.now().strftime(453 "%s.%f") + str(_g_async_rv_counter)454 exec_rv = messages.Async_rv(ns, rvid)455 _g_async_rvs[ns][rvid] = pythonshare.InProgress()456 thread.start_new_thread(_local_async_execute, (exec_rv, obj))457 else:458 # synchronous execution, return true return value459 exec_rv = _local_execute(obj, conn_id)460 if not exec_rv is None:461 if opt_debug:462 daemon_log("%s:%s <= %s" % (peername + (exec_rv,)))463 try:464 try:465 if obj.recv_cap_data_info():466 info = pythonshare._send_opt(exec_rv, to_client, obj.recv_caps)467 if info:468 sent_info = " %s B, format:%s" % (469 info.data_length, info.data_format)470 else:471 sent_info = ""472 else:473 pythonshare._send(exec_rv, to_client)474 sent_info = ""475 if opt_debug:476 daemon_log("%s:%s sent%s" % (peername + (sent_info,)))477 except (EOFError, socket.error):478 break479 except (TypeError, ValueError, cPickle.PicklingError): # pickling rv fails480 exec_rv.expr_rv = messages.Unpicklable(exec_rv.expr_rv)481 try:482 pythonshare._send(exec_rv, to_client)483 except (EOFError, socket.error):484 break485 elif isinstance(obj, messages.Server_ctl):486 if obj.command == "die":487 ns = obj.args[0]488 if ns in _g_remote_namespaces:489 try:490 rv = _remote_execute(ns, obj)491 if opt_debug:492 daemon_log("%s:%s <= %s" % (peername + (rv,)))493 pythonshare._send(rv, to_client)494 except (EOFError, socket.error): # connection lost495 daemon_log('connection lost to "%s"' % (ns,))496 _drop_remote_namespace(ns)497 break498 else:499 _g_server_shutdown = True500 server_ctl_rv = messages.Server_ctl_rv(0, "shutting down")501 pythonshare._send(server_ctl_rv, to_client)502 if _g_wake_server_function:503 _g_wake_server_function()504 break505 elif obj.command == "unlock":506 try:507 ns = obj.args[0]508 if ns in _g_remote_namespaces:509 try:510 rv = _remote_execute(ns, obj)511 except (EOFError, socket.error): # connection lost512 daemon_log('connection lost to "%s"' % (ns,))513 _drop_remote_namespace(ns)514 break515 elif ns in _g_local_namespace_locks:516 try:517 _g_local_namespace_locks[ns].release()518 server_ctl_rv = messages.Server_ctl_rv(519 0, "%s unlocked" % (repr(ns),))520 except thread.error, e:521 server_ctl_rv = messages.Server_ctl_rv(522 1, "%s already unlocked" %523 (repr(ns),))524 elif ns in _g_local_namespaces:525 server_ctl_rv = messages.Server_ctl_rv(526 2, "namespace %s is not locked" % (repr(ns),))527 else:528 server_ctl_rv = messages.Server_ctl_rv(529 -1, "unknown namespace %s" % (repr(ns),))530 if opt_debug:531 daemon_log("%s:%s <= %s" % (peername + (server_ctl_rv,)))532 pythonshare._send(server_ctl_rv, to_client)533 except Exception, e:534 if opt_debug:535 daemon_log("Exception in handling %s: %s" % (obj, e))536 else:537 daemon_log("unknown message type: %s in %s" % (type(obj), obj))538 pythonshare._send(messages.Auth_rv(False), to_client)539 auth_ok = False540 if opt_debug:541 daemon_log("disconnected %s:%s" % peername)542 _connection_lost(conn_id, to_client, from_client, conn)543 if kill_server_on_close:544 _g_server_shutdown = True545 if _g_wake_server_function:546 _g_wake_server_function()547def start_server(host, port,548 ns_init_import_export=[],549 conn_opts={},550 listen_stdin=True):551 global _g_wake_server_function552 global _g_waker_lock553 daemon_log("pid: %s" % (os.getpid(),))554 # Initialise, import and export namespaces555 for task, ns, arg in ns_init_import_export:556 if task == "init":557 _init_local_namespace(ns, arg, force=True)558 elif task == "export":559 _init_local_namespace(ns, None, force=True)560 daemon_log('exporting "%s" to %s' % (ns, arg))561 try:562 c = pythonshare.connection(arg)563 except Exception, e:564 daemon_log('connecting to %s failed: %s' % (arg, e))565 return566 if c.export_ns(ns):567 _register_exported_namespace(ns, c)568 thread.start_new_thread(569 _serve_connection, (c, {"kill-server-on-close": True}))570 else:571 raise ValueError('Export namespace "%s" to "%s" failed'572 % (ns, arg))573 elif task == "import":574 if (ns in _g_local_namespaces or575 ns in _g_remote_namespaces):576 raise ValueError('Import failed, namespace "%s" already exists'577 % (ns,))578 c = pythonshare.connection(arg)579 if c.import_ns(ns):580 _init_remote_namespace(ns, c, c._to_server, c._from_server)581 try:582 addrinfos = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM)583 for addrinfo in addrinfos:584 daemon_log("listen: %s:%s" % (addrinfo[4][0], addrinfo[4][1]))585 except socket.error:586 daemon_log("listen: %s:%s" % (host, port))587 if isinstance(port, int):588 def wake_server_function():589 _g_waker_lock.release() # wake up server590 _g_wake_server_function = wake_server_function591 _g_waker_lock = thread.allocate_lock()592 _g_waker_lock.acquire() # unlocked593 # Start listening to the port594 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)595 try:596 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)597 except:598 pass599 s.bind((host, port))600 s.listen(4)601 event_queue = Queue.Queue()602 thread.start_new_thread(_store_return_value, (s.accept, event_queue))603 thread.start_new_thread(_store_return_value, (_g_waker_lock.acquire, event_queue))604 if not sys.stdin.closed and listen_stdin:605 daemon_log("listening to stdin")606 thread.start_new_thread(_store_return_value, (sys.stdin.readline, event_queue))607 else:608 daemon_log("not listening stdin")609 while 1:610 event = event_queue.get()611 if isinstance(event, tuple):612 # returned from s.accept613 conn, _ = event614 thread.start_new_thread(_serve_connection, (conn, conn_opts))615 elif event == True:616 # returned from _g_waker_lock.acquire617 daemon_log("shutting down.")618 break619 else:620 # returned from sys.stdin.readline621 pass622 elif port == "stdin":623 opt_debug_limit = 0624 if os.name == "nt":625 import msvcrt626 msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)627 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)628 conn = client.Connection(sys.stdin, sys.stdout)629 _serve_connection(conn, conn_opts)630 for ns in sorted(_g_remote_namespaces.keys()):631 _drop_remote_namespace(ns)632 for ns in sorted(_g_local_namespaces.keys()):633 _drop_local_namespace(ns)634def start_daemon(host="localhost", port=8089, debug=False,635 log_fd=None, ns_init_import_export=[], conn_opts={},636 debug_limit=None):637 global opt_log_fd, opt_debug, opt_debug_limit638 opt_log_fd = log_fd639 opt_debug = debug640 if debug_limit != None:641 opt_debug_limit = debug_limit642 if opt_debug_limit > 0:643 messages.MSG_STRING_FIELD_MAX_LEN = opt_debug_limit/2644 else:645 messages.MSG_STRING_FIELD_MAX_LEN = None...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run fMBT automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful