How to use ns_type method in fMBT

Best Python code snippet using fMBT_python

__init__.py

Source:__init__.py Github

copy

Full Screen

1#!/usr/bin/env python2"""3nsenter - run program with namespaces of other processes4"""5import argparse6import ctypes7import ctypes.util8import errno9import os10import logging11from pathlib import Path12try:13 from contextlib import ExitStack14except ImportError:15 from contextlib2 import ExitStack16NAMESPACE_NAMES = frozenset(['mnt', 'ipc', 'net', 'pid', 'user', 'uts'])17class Namespace(object):18 """A context manager for entering namespaces19 Args:20 pid: The PID for the owner of the namespace to enter, or an absolute21 path to a file which represents a namespace handle.22 ns_type: The type of namespace to enter must be one of23 mnt ipc net pid user uts. If pid is an absolute path, this24 much match the type of namespace it represents25 proc: The path to the /proc file system. If running in a container26 the host proc file system may be binded mounted in a different27 location28 Raises:29 IOError: A non existent PID was provided30 ValueError: An improper ns_type was provided31 OSError: Unable to enter or exit the namespace32 Example:33 with Namespace(916, 'net'):34 #do something in the namespace35 pass36 with Namespace('/var/run/netns/foo', 'net'):37 #do something in the namespace38 pass39 """40 _log = logging.getLogger(__name__)41 _libc = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True)42 def __init__(self, pid, ns_type, proc='/proc'):43 if ns_type not in NAMESPACE_NAMES:44 raise ValueError('ns_type must be one of {0}'.format(45 ', '.join(NAMESPACE_NAMES)46 ))47 self.pid = pid48 self.ns_type = ns_type49 self.proc = proc50 # if it's numeric, then it's a pid, else assume it's a path51 try:52 pid = int(pid)53 self.target_fd = self._nsfd(pid, ns_type).open()54 except ValueError:55 self.target_fd = Path(pid).open()56 self.target_fileno = self.target_fd.fileno()57 self.parent_fd = self._nsfd('self', ns_type).open()58 self.parent_fileno = self.parent_fd.fileno()59 __init__.__annotations__ = {'pid': str, 'ns_type': str}60 def _nsfd(self, pid, ns_type):61 """Utility method to build a pathlib.Path instance pointing at the62 requested namespace entry63 Args:64 pid: The PID65 ns_type: The namespace type to enter66 Returns:67 pathlib.Path pointing to the /proc namespace entry68 """69 return Path(self.proc) / str(pid) / 'ns' / ns_type70 _nsfd.__annotations__ = {'process': str, 'ns_type': str, 'return': Path}71 def _close_files(self):72 """Utility method to close our open file handles"""73 try:74 self.target_fd.close()75 except:76 pass77 if self.parent_fd is not None:78 self.parent_fd.close()79 def __enter__(self):80 self._log.debug('Entering %s namespace %s', self.ns_type, self.pid)81 if self._libc.setns(self.target_fileno, 0) == -1:82 e = ctypes.get_errno()83 self._close_files()84 raise OSError(e, errno.errorcode[e])85 def __exit__(self, type, value, tb):86 self._log.debug('Leaving %s namespace %s', self.ns_type, self.pid)87 if self._libc.setns(self.parent_fileno, 0) == -1:88 e = ctypes.get_errno()89 self._close_files()90 raise OSError(e, errno.errorcode[e])91 self._close_files()92def main(): # pragma: no cover93 """Command line interface to the Namespace context manager"""94 parser = argparse.ArgumentParser(prog='nsenter', description=__doc__)95 parser.add_argument('--target', '-t', required=True, metavar='PID',96 help='A target process to get contexts from')97 parser.add_argument('--proc', '-p', metavar='PROCFS', default='/proc',98 help='The target proc file system')99 group = parser.add_argument_group('Namespaces')100 for ns in NAMESPACE_NAMES:101 group.add_argument('--{0}'.format(ns),102 action='store_true',103 help='Enter the {0} namespace'.format(ns)104 )105 parser.add_argument('--all',106 action='store_true',107 help='Enter all namespaces'108 )109 parser.add_argument('command', nargs='*', default=['/bin/sh'])110 args = parser.parse_args()111 # make sure we have --all or at least one namespace112 if True not in [getattr(args, ns) for ns in NAMESPACE_NAMES] and not args.all:113 parser.error('You must specify at least one namespace')114 try:115 with ExitStack() as stack:116 namespaces = []117 for ns in NAMESPACE_NAMES:118 if getattr(args, ns) or args.all:119 namespaces.append(Namespace(args.target, ns, proc=args.proc))120 for ns in namespaces:121 stack.enter_context(ns)122 os.execlp(args.command[0], *args.command)123 except IOError as exc:124 parser.error('Unable to access PID: {0}'.format(exc))125 except OSError as exc:126 parser.error('Unable to enter {0} namespace: {1}'.format(127 ns.ns_type, exc128 ))129if __name__ == '__main__': # pragma: no cover...

Full Screen

Full Screen

test_nsrel.py

Source:test_nsrel.py Github

copy

Full Screen

1# Copyright 2018 Harald Albrecht2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or12# implied. See the License for the specific language governing13# permissions and limitations under the License.14# pylint: disable=missing-module-docstring15# pylint: disable=missing-class-docstring,missing-function-docstring16import errno17import pytest18import linuxns_rel as nsr19from tests.linuxnsrel import LxNsRelationsTestHelper20class TestLxNsRelationsBase(LxNsRelationsTestHelper):21 def test_nstype_str(self):22 for ns_name, ns_type in self.NAMESPACES:23 assert nsr.nstype_str(ns_type) == ns_name, \24 'invalid name "%s" returned for ' \25 'namespace type value %d/%s' % (26 nsr.nstype_str(ns_type),27 ns_type,28 hex(ns_type)29 )30 def test_nstype_str_illegal_arg(self):31 with pytest.raises(ValueError):32 nsr.nstype_str(42)33 pytest.fail('accepts invalid namespace type value')34 def test_get_nstype(self):35 for ns_name, ns_type in self.NAMESPACES:36 # by path...37 assert nsr.get_nstype(self.nspath(ns_name)) == ns_type, \38 'invalid namespace type returned ' \39 'for "%s" namespace path' % ns_name40 with open(self.nspath(ns_name)) as f:41 # by file...42 assert nsr.get_nstype(f) == ns_type, \43 'invalid namespace type returned ' \44 'for "%s" file' % ns_name45 # by fd...46 assert nsr.get_nstype(f.fileno()) == ns_type, \47 'invalid namespace type returned ' \48 'for "%s" fd' % ns_name49 def test_get_nstype_illegal_arg(self):50 with pytest.raises(TypeError):51 nsr.get_nstype(42.0) # type: ignore52 pytest.fail('accepting float namespace reference parameter')53 with pytest.raises(TypeError):54 nsr.get_nstype(None) # type: ignore55 pytest.fail('accepting None namespace reference parameter')56 def test_get_userns(self):57 user_nsid = self.nsid('user')58 # by path...59 with nsr.get_userns(self.nspath('net')) as owner_ns:60 assert self.file_nsid(owner_ns) == user_nsid, \61 'invalid owning user namespace returned'62 with open(self.nspath('net')) as nsref:63 # by file...64 with nsr.get_userns(nsref) as owner_ns:65 assert self.file_nsid(owner_ns) == user_nsid, \66 'invalid owning user namespace returned'67 # by fd...68 with nsr.get_userns(nsref.fileno()) as owner_ns:69 assert self.file_nsid(owner_ns) == user_nsid, \70 'invalid owning user namespace returned'71 def test_get_userns_illegal_arg(self):72 with pytest.raises(TypeError):73 nsr.get_userns(42.0) # type: ignore74 pytest.fail('accepts invalid namespace value')75 def test_getparentns_in_root(self):76 with pytest.raises(PermissionError):77 nsr.get_parentns(self.nspath('user'))78 pytest.fail('parent of root user')79 def test_getparentns_nonhierarchical_namespace(self):80 with pytest.raises(OSError) as oserr:81 nsr.get_parentns(self.nspath('net'))82 pytest.fail('net namespace has a parent, seriously?')83 assert oserr.value.errno == errno.EINVAL, \84 'no parent for non-hierarchical namespace'85 def test_getparentns_illegal_arg(self):86 with pytest.raises(TypeError):87 nsr.get_parentns(42.0) # type: ignore88 pytest.fail('accepting float namespace reference parameter')89 with pytest.raises(TypeError):90 nsr.get_parentns(None) # type: ignore91 pytest.fail('accepting None namespace reference parameter')92 def test_owner_uid(self):93 # by path...94 # ...covers containerized CI test95 assert nsr.get_owner_uid(self.nspath('user')) in (0, 65534), \96 'owner ID of root user namespace not root'97 with open(self.nspath('user')) as nsref:98 # by file...99 assert nsr.get_owner_uid(nsref) == 0, \100 'owner ID of root user namespace not root'101 # by fd...102 assert nsr.get_owner_uid(nsref.fileno()) == 0, \103 'owner ID of root user namespace not root'104 def test_owner_uid_illegal_arg(self):105 with pytest.raises(TypeError):106 nsr.get_owner_uid(42.0) # type: ignore107 pytest.raises('accepting float namespace reference parameter')108 with pytest.raises(TypeError):109 nsr.get_owner_uid(None) # type: ignore...

Full Screen

Full Screen

hashing.py

Source:hashing.py Github

copy

Full Screen

1import hashlib2import uuid3from enum import Enum4from typing import Optional5from fastapi import APIRouter6from ted_sws.notice_transformer.entrypoints.api.digest_service.common import ResponseType, single_result_response, \7 unescape_value8from ted_sws.notice_transformer.entrypoints.api.digest_service.routes.xpath import sanitize_xpath9ROUTE_PREFIX = "/hashing"10route = APIRouter()11class UUIDInputProcessType(Enum):12 XPATH = "xpath"13 MD5 = "md5"14 RAW = "raw"15class UUIDNamespaceType(Enum):16 DNS = "DNS"17 URL = "URL"18 OID = "OID"19 X500 = "X500"20class UUIDVersion(Enum):21 UUID3 = "UUID3"22 UUID5 = "UUID5"23def string_md5(value: str):24 """25 Generates MD5 hash, based on provided value26 :param value:27 :return:28 """29 return hashlib.md5(value.encode('utf8')).hexdigest()30def uuid_ns_by_type(ns_type: UUIDNamespaceType) -> uuid.UUID:31 """32 Returns UUID Namespace Value to be used when generating the UUID string, based on provided Namespace Type33 :param ns_type:34 :return:35 """36 uuid_ns: uuid.UUID = uuid.NAMESPACE_DNS37 if ns_type == UUIDNamespaceType.URL:38 uuid_ns = uuid.NAMESPACE_URL39 elif ns_type == UUIDNamespaceType.OID:40 uuid_ns = uuid.NAMESPACE_OID41 elif ns_type == UUIDNamespaceType.X500:42 uuid_ns = uuid.NAMESPACE_X50043 return uuid_ns44@route.get("/fn/md5/{value:path}")45async def fn_md5(value: str, response_type: Optional[ResponseType] = ResponseType.RAW):46 """47 Returns a hash generated by the MD5 message digest algorithm, taking as arguments:48 - @value: string value to be hashed;49 - @response_type: response type/format to be returned;50 """51 value = unescape_value(value)52 result = string_md5(value)53 return single_result_response(result, response_type)54@route.get("/fn/uuid/{value:path}")55async def fn_uuid(56 value: str,57 process_type: Optional[UUIDInputProcessType] = UUIDInputProcessType.XPATH,58 version: Optional[UUIDVersion] = UUIDVersion.UUID3,59 ns_type: Optional[UUIDNamespaceType] = UUIDNamespaceType.URL,60 response_type: Optional[ResponseType] = ResponseType.RAW61):62 """63 Returns generated UUID, taking as arguments:64 - @value: string value to be hashed;65 - @process_type: algorithm used to process input @value before generating UUID string;66 - @version: UUID Version;67 - @ns_type: namespace type to be used when generating UUID string;68 - @response_type: response type/format to be returned;69 """70 value = unescape_value(value)71 if process_type == UUIDInputProcessType.XPATH:72 value = sanitize_xpath(value)73 elif process_type == UUIDInputProcessType.MD5:74 value = string_md5(value)75 uuid_ns = uuid_ns_by_type(ns_type)76 uuid_result: uuid.UUID77 if version == UUIDVersion.UUID5:78 uuid_result = uuid.uuid5(uuid_ns, value)79 else:80 uuid_result = uuid.uuid3(uuid_ns, value)81 result = str(uuid_result)...

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