Search is not available for this dataset
text
stringlengths
75
104k
def get_serializer(name): ''' Return the serialize function. ''' try: log.debug('Using %s as serializer', name) return SERIALIZER_LOOKUP[name] except KeyError: msg = 'Serializer {} is not available'.format(name) log.error(msg, exc_info=True) raise InvalidSeria...
def _handshake(self, conn, addr): ''' Ensures that the client receives the AES key. ''' # waiting for the magic request message msg = conn.recv(len(MAGIC_REQ)) log.debug('Received message %s from %s', msg, addr) if msg != MAGIC_REQ: log.warning('%s is ...
def keep_alive(self, conn): ''' Maintains auth sessions ''' while self.__up: msg = conn.recv(len(AUTH_KEEP_ALIVE)) if msg != AUTH_KEEP_ALIVE: log.error('Received something other than %s', AUTH_KEEP_ALIVE) conn.close() ...
def verify_cert(self): ''' Checks that the provided cert and key are valid and usable ''' log.debug('Verifying the %s certificate, keyfile: %s', self.certificate, self.keyfile) try: ssl.create_default_context().load_cert_chain(self.certificate, keyfi...
def _create_skt(self): ''' Create the authentication socket. ''' log.debug('Creating the auth socket') if ':' in self.auth_address: self.socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) else: self.socket = socket.socket(socket.AF_INET, s...
def start(self): ''' Listen to auth requests and send the AES key. Each client connection starts a new thread. ''' # Start suicide polling thread log.debug('Starting the auth process') self.verify_cert() self._create_skt() log.debug('The auth proce...
def stop(self): ''' Stop the auth proc. ''' log.info('Stopping auth process') self.__up = False self.socket.close()
def get_interface(name): ''' Return the serialize function. ''' try: log.debug('Using %s as buffer interface', name) return BUFFER_LOOKUP[name] except KeyError: msg = 'Buffer interface {} is not available'.format(name) log.error(msg, exc_info=True) raise Inval...
def start(self): ''' Startup the kafka consumer. ''' log.debug('Creating the consumer using the bootstrap servers: %s and the group ID: %s', self.bootstrap_servers, self.group_id) try: self.consumer = kafka.KafkaConsumer(bootstrap_s...
def receive(self): ''' Return the message received and the address. ''' try: msg = next(self.consumer) except ValueError as error: log.error('Received kafka error: %s', error, exc_info=True) raise ListenerException(error) log_source = m...
def stop(self): ''' Shutdown kafka consumer. ''' log.info('Stopping te kafka listener class') self.consumer.unsubscribe() self.consumer.close()
def get_transport(name): ''' Return the transport class. ''' try: log.debug('Using %s as transport', name) return TRANSPORT_LOOKUP[name] except KeyError: msg = 'Transport {} is not available. Are the dependencies installed?'.format(name) log.error(msg, exc_info=True) ...
def start(self): ''' Startup the zmq consumer. ''' zmq_uri = '{protocol}://{address}:{port}'.format( protocol=self.protocol, address=self.address, port=self.port ) if self.port else\ ...
def receive(self): ''' Return the message received. ..note:: In ZMQ we are unable to get the address where we got the message from. ''' try: msg = self.sub.recv() except zmq.Again as error: log.error('Unable to receive messages: %s', e...
def stop(self): ''' Shutdown zmq listener. ''' log.info('Stopping the zmq listener class') self.sub.close() self.ctx.term()
def start(self): ''' Create the UDP listener socket. ''' if ':' in self.address: self.skt = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) else: self.skt = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if self.reuse_port: self.skt...
def receive(self): ''' Return the message received and the address. ''' try: msg, addr = self.skt.recvfrom(self.buffer_size) except socket.error as error: log.error('Received listener socket error: %s', error, exc_info=True) raise ListenerExcep...
def _suicide_when_without_parent(self, parent_pid): ''' Kill this process when the parent died. ''' while True: time.sleep(5) try: # Check pid alive os.kill(parent_pid, 0) except OSError: # Forcibly exit ...
def _setup_buffer(self): ''' Setup the buffer subsystem. ''' if not self._buffer_cfg or not isinstance(self._buffer_cfg, dict): return buffer_name = list(self._buffer_cfg.keys())[0] buffer_class = napalm_logs.buffer.get_interface(buffer_name) log.debug...
def _setup_metrics(self): """ Start metric exposition """ path = os.environ.get("prometheus_multiproc_dir") if not os.path.exists(self.metrics_dir): try: log.info("Creating metrics directory") os.makedirs(self.metrics_dir) e...
def _setup_log(self): ''' Setup the log object. ''' logging_level = CONFIG.LOGGING_LEVEL.get(self.log_level.lower()) logging.basicConfig(format=self.log_format, level=logging_level)
def _post_preparation(self): ''' The steps for post-preparation (when the logs, and everything is already setup). ''' self.opts['hwm'] = CONFIG.ZMQ_INTERNAL_HWM if self.hwm is None else self.hwm self.opts['_server_send_unknown'] = False for pub in self.publisher: ...
def _whitelist_blacklist(self, os_name): ''' Determines if the OS should be ignored, depending on the whitelist-blacklist logic configured by the user. ''' return napalm_logs.ext.check_whitelist_blacklist(os_name, w...
def _extract_yaml_docstring(stream): ''' Extract the comments at the top of the YAML file, from the stream handler. Return the extracted comment as string. ''' comment_lines = [] lines = stream.read().splitlines() for line in lines: line_strip ...
def _load_config(self, path): ''' Read the configuration under a specific path and return the object. ''' config = {} log.debug('Reading configuration from %s', path) if not os.path.isdir(path): msg = ( 'Unable to read from {path}: ' ...
def _verify_config_dict(self, valid, config, dev_os, key_path=None): ''' Verify if the config dict is valid. ''' if not key_path: key_path = [] for key, value in valid.items(): self._verify_config_key(key, value, valid, config, dev_os, key_path)
def _verify_config(self): ''' Verify that the config is correct ''' if not self.config_dict: self._raise_config_exception('No config found') # Check for device conifg, if there isn't anything then just log, do not raise an exception for dev_os, dev_config in s...
def _build_config(self): ''' Build the config of the napalm syslog parser. ''' if not self.config_dict: if not self.config_path: # No custom config path requested # Read the native config files self.config_path = os.path.join( ...
def _start_auth_proc(self): ''' Start the authenticator process. ''' log.debug('Computing the signing key hex') verify_key = self.__signing_key.verify_key sgn_verify_hex = verify_key.encode(encoder=nacl.encoding.HexEncoder) log.debug('Starting the authenticator su...
def _start_lst_proc(self, listener_type, listener_opts): ''' Start the listener process. ''' log.debug('Starting the listener process for %s', listener_type) listener = NapalmLogsListenerProc(self.opts, ...
def _start_srv_proc(self, started_os_proc): ''' Start the server process. ''' log.debug('Starting the server process') server = NapalmLogsServerProc(self.opts, self.config_dict, st...
def _start_pub_proc(self, publisher_type, publisher_opts, pub_id): ''' Start the publisher process. ''' log.debug('Starting the publisher process for %s', publisher_type) publisher = NapalmLogsPublisherProc(s...
def _start_dev_proc(self, device_os, device_config): ''' Start the device worker process. ''' log.info('Starting the child process for %s', device_os) dos = NapalmLogsDeviceProc(device_os, self.opt...
def start_engine(self): ''' Start the child processes (one per device OS) ''' if self.disable_security is True: log.warning('***Not starting the authenticator process due to disable_security being set to True***') else: log.debug('Generating the private ke...
def _check_children(self): ''' Check all of the child processes are still running ''' while self.up: time.sleep(1) for process in self._processes: if process.is_alive() is True: continue log.debug('%s is dead. St...
def _setup_ipc(self): ''' Setup the IPC PUB and SUB sockets for the proxy. ''' log.debug('Setting up the internal IPC proxy') self.ctx = zmq.Context() # Frontend self.sub = self.ctx.socket(zmq.SUB) self.sub.bind(PUB_PX_IPC_URL) self.sub.setsockopt(...
def start(self): ''' Listen to messages and publish them. ''' self._setup_ipc() # Start suicide polling thread thread = threading.Thread(target=self._suicide_when_without_parent, args=(os.getppid(),)) thread.start() signal.signal(signal.SIGTERM, self._exit...
def _setup_ipc(self): ''' Subscribe to the pub IPC and publish the messages on the right transport. ''' self.ctx = zmq.Context() log.debug('Setting up the %s publisher subscriber #%d', self._transport_type, self.pub_id) self.sub = self.ctx.socket(zmq.SUB) ...
def _setup_transport(self): ''' Setup the transport. ''' if 'RAW' in self.error_whitelist: log.info('%s %d will publish partially parsed messages', self._transport_type, self.pub_id) if 'UNKNOWN' in self.error_whitelist: log.info('%s %d will publish unknow...
def _prepare(self, serialized_obj): ''' Prepare the object to be sent over the untrusted channel. ''' # generating a nonce nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE) # encrypting using the nonce encrypted = self.__safe.encrypt(serialized_obj, nonc...
def start(self): ''' Listen to messages and publish them. ''' # metrics napalm_logs_publisher_received_messages = Counter( 'napalm_logs_publisher_received_messages', "Count of messages received by the publisher", ['publisher_type', 'address', '...
def get_listener(name): ''' Return the listener class. ''' try: log.debug('Using %s as listener', name) return LISTENER_LOOKUP[name] except KeyError: msg = 'Listener {} is not available. Are the dependencies installed?'.format(name) log.error(msg, exc_info=True) ...
def setval(key, val, dict_=None, delim=defaults.DEFAULT_DELIM): ''' Set a value under the dictionary hierarchy identified under the key. The target 'foo/bar/baz' returns the dictionary hierarchy {'foo': {'bar': {'baz': {}}}}. .. note:: Currently this doesn't work with integers, i.e. ...
def traverse(data, key, delim=defaults.DEFAULT_DELIM): ''' Traverse a dict or list using a slash delimiter target string. The target 'foo/bar/0' will return data['foo']['bar'][0] if this value exists, otherwise will return empty dict. Return None when not found. This can be used to verify if a c...
def _start_keep_alive(self): ''' Start the keep alive thread as a daemon ''' keep_alive_thread = threading.Thread(target=self.keep_alive) keep_alive_thread.daemon = True keep_alive_thread.start()
def keep_alive(self): ''' Send a keep alive request periodically to make sure that the server is still alive. If not then try to reconnect. ''' self.ssl_skt.settimeout(defaults.AUTH_KEEP_ALIVE_INTERVAL) while self.__up: try: log.debug('Sending ...
def reconnect(self): ''' Try to reconnect and re-authenticate with the server. ''' log.debug('Closing the SSH socket.') try: self.ssl_skt.close() except socket.error: log.error('The socket seems to be closed already.') log.debug('Re-opening...
def authenticate(self): ''' Authenticate the client and return the private and signature keys. Establish a connection through a secured socket, then do the handshake using the napalm-logs auth algorithm. ''' log.debug('Authenticate to %s:%d, using the cer...
def decrypt(self, binary): ''' Decrypt and unpack the original OpenConfig object, serialized using MessagePack. Raise BadSignatureException when the signature was forged or corrupted. ''' try: encrypted = self.verify_key.verify(binary) except B...
def _client_connection(self, conn, addr): ''' Handle the connecition with one client. ''' log.debug('Established connection with %s:%d', addr[0], addr[1]) conn.settimeout(self.socket_timeout) try: while self.__up: msg = conn.recv(self.buffer_si...
def _serve_clients(self): ''' Accept cients and serve, one separate thread per client. ''' self.__up = True while self.__up: log.debug('Waiting for a client to connect') try: conn, addr = self.skt.accept() log.debug('Receive...
def start(self): ''' Start listening for messages. ''' log.debug('Creating the TCP server') if ':' in self.address: self.skt = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) else: self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...
def receive(self): ''' Return one message dequeued from the listen buffer. ''' while self.buffer.empty() and self.__up: # This sequence is skipped when the buffer is not empty. sleep_ms = random.randint(0, 1000) # log.debug('The message queue is empty,...
def stop(self): ''' Closing the socket. ''' log.info('Stopping the TCP listener') self.__up = False try: self.skt.shutdown(socket.SHUT_RDWR) except socket.error: log.error('The following error may not be critical:', exc_info=True) s...
def _setup_listener(self): ''' Setup the transport. ''' listener_class = get_listener(self._listener_type) self.address = self.listener_opts.pop('address', self.address) self.port = self.listener_opts.pop('port', self.port) self.listener = listener_class(self.addr...
def _setup_ipc(self): ''' Setup the listener ICP pusher. ''' log.debug('Setting up the listener IPC pusher') self.ctx = zmq.Context() self.pub = self.ctx.socket(zmq.PUSH) self.pub.connect(LST_IPC_URL) log.debug('Setting HWM for the listener: %d', self.opts...
def start(self): ''' Listen to messages and publish them. ''' # counter metrics for messages c_logs_ingested = Counter( 'napalm_logs_listener_logs_ingested', 'Count of ingested log messages', ['listener_type', 'address', 'port'], ) ...
def emit(msg_dict): ''' Extracts the details from the syslog message and returns an object having the following structure: .. code-block:: python { u'users': { u'user': { u'luke': { u'action': { ...
def expr_match(line, expr): ''' Evaluate a line of text against an expression. First try a full-string match, next try globbing, and then try to match assuming expr is a regular expression. Originally designed to match minion IDs for whitelists/blacklists. ''' if line == expr: return...
def check_whitelist_blacklist(value, whitelist=None, blacklist=None): ''' Check a whitelist and/or blacklist to see if the value matches it. value The item to check the whitelist and/or blacklist against. whitelist The list of items that are white-listed. If ``value`` is found ...
def set_snap_server_variables(host, port, snap_extension='.xml', path=None): """ Change dynamically port and host variable in xml Snap! project file""" localdir = os.getcwd() if path is None: os.chdir(os.path.dirname(os.path.realpath(__file__))) else: os.chdir(path) xml_files = [f f...
def run(self, quiet=None, server=''): """ Start the tornado server, run forever. 'quiet' and 'server' arguments are no longer used, they are keep only for backward compatibility """ try: loop = IOLoop() http_server = HTTPServer(WSGIContainer(self.app)) ...
def make_update_loop(thread, update_func): """ Makes a run loop which calls an update function at a predefined frequency. """ while not thread.should_stop(): if thread.should_pause(): thread.wait_to_resume() start = time.time() if hasattr(thread, '_updated'): thr...
def start(self): """ Start the run method as a new thread. It will first stop the thread if it is already running. """ if self.running: self.stop() self._thread = threading.Thread(target=self._wrapped_target) self._thread.daemon = True self._thread....
def stop(self, wait=True): """ Stop the thread. More precisely, sends the stopping signal to the thread. It is then up to the run method to correctly responds. """ if self.started: self._running.clear() self._resume.set() # We cannot wait for oursel...
def wait_to_start(self, allow_failure=False): """ Wait for the thread to actually starts. """ self._started.wait() if self._crashed and not allow_failure: self._thread.join() raise RuntimeError('Setup failed, see {} Traceback' 'for details....
def from_vrep(config, vrep_host='127.0.0.1', vrep_port=19997, scene=None, tracked_objects=[], tracked_collisions=[], id=None, shared_vrep_io=None): """ Create a robot from a V-REP instance. :param config: robot configuration (either the path to the json or directly the dictionary) ...
def get_control_mode(self, ids): """ Gets the mode ('joint' or 'wheel') for the specified motors. """ to_get_ids = [id for id in ids if id not in self._known_mode] limits = self.get_angle_limit(to_get_ids, convert=False) modes = ['wheel' if limit == (0, 0) else 'joint' for limit in limit...
def set_wheel_mode(self, ids): """ Sets the specified motors to wheel mode. """ self.set_control_mode(dict(zip(ids, itertools.repeat('wheel'))))
def set_joint_mode(self, ids): """ Sets the specified motors to joint mode. """ self.set_control_mode(dict(zip(ids, itertools.repeat('joint'))))
def set_angle_limit(self, limit_for_id, **kwargs): """ Sets the angle limit to the specified motors. """ convert = kwargs['convert'] if 'convert' in kwargs else self._convert if 'wheel' in self.get_control_mode(limit_for_id.keys()): raise ValueError('can not change the angle limit o...
def close(self): """ Cleans the robot by stopping synchronization and all controllers.""" self.stop_sync() [c.io.close() for c in self._controllers if c.io is not None]
def start_sync(self): """ Starts all the synchonization loop (sensor/effector controllers). """ if self._syncing: return [c.start() for c in self._controllers] [c.wait_to_start() for c in self._controllers] self._primitive_manager.start() self._primitive_mana...
def stop_sync(self): """ Stops all the synchonization loop (sensor/effector controllers). """ if not self._syncing: return if self._primitive_manager.running: self._primitive_manager.stop() [c.stop() for c in self._controllers] [s.close() for s in self.s...
def goto_position(self, position_for_motors, duration, control=None, wait=False): """ Moves a subset of the motors to a position within a specific duration. :param dict position_for_motors: which motors you want to move {motor_name: pos, motor_name: pos,...} :param float duration: durat...
def power_up(self): """ Changes all settings to guarantee the motors will be used at their maximum power. """ for m in self.motors: m.compliant = False m.moving_speed = 0 m.torque_limit = 100.0
def to_config(self): """ Generates the config for the current robot. .. note:: The generated config should be used as a basis and must probably be modified. """ from ..dynamixel.controller import DxlController dxl_controllers = [c for c in self._controllers ...
def detect_blob(self, img, filters): """ "filters" must be something similar to: filters = { 'R': (150, 255), # (min, max) 'S': (150, 255), } """ acc_mask = ones(img.shape[:2], dtype=uint8) * 255 rgb = img.copy() ...
def setup(self): """ Setups the controller by reading/setting position for all motors. """ self._init_vrep_streaming() # Init lifo for temperature spoofing for m in self.motors: m.__dict__['_load_fifo'] = deque(200 * [1], maxlen=200) self.update()
def update(self): """ Synchronization update loop. At each update all motor position are read from vrep and set to the motors. The motors target position are also send to v-rep. """ # Read all the angle limits h, _, l, _ = self.io.call_remote_api('simxGetObjectGroupData', ...
def update(self): """ Updates the position and orientation of the tracked objects. """ for s in self.sensors: s.position = self.io.get_object_position(object_name=s.name) s.orientation = self.io.get_object_orientation(object_name=s.name)
def update(self): """ Update the state of the collision detectors. """ for s in self.sensors: s.colliding = self.io.get_collision_state(collision_name=s.name)
def get_transformation_matrix(self, theta): """ Computes the homogeneous transformation matrix for this link. """ ct = numpy.cos(theta + self.theta) st = numpy.sin(theta + self.theta) ca = numpy.cos(self.alpha) sa = numpy.sin(self.alpha) return numpy.matrix(((ct, -st * c...
def forward_kinematics(self, q): """ Computes the homogeneous transformation matrix of the end effector of the chain. :param vector q: vector of the joint angles (theta 1, theta 2, ..., theta n) """ q = numpy.array(q).flatten() if len(q) != len(self.links): raise V...
def inverse_kinematics(self, end_effector_transformation, q=None, max_iter=1000, tolerance=0.05, mask=numpy.ones(6), use_pinv=False): """ Computes the joint angles corresponding to the end effector transf...
def update(self): """ Compute the sin(t) where t is the elapsed time since the primitive has been started. """ pos = self._amp * numpy.sin(self._freq * 2.0 * numpy.pi * self.elapsed_time + self._phase * numpy.pi / 180.0) + self._offset for m in self.motor_lis...
def _get_available_ports(): """ Tries to find the available serial ports on your system. """ if platform.system() == 'Darwin': return glob.glob('/dev/tty.usb*') elif platform.system() == 'Linux': return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyAMA*') e...
def get_port_vendor_info(port=None): """ Return vendor informations of a usb2serial device. It may depends on the Operating System. :param string port: port of the usb2serial device :Example: Result with a USB2Dynamixel on Linux: In [1]: import pypot.dynamixel In [2...
def find_port(ids, strict=True): """ Find the port with the specified attached motor ids. :param list ids: list of motor ids to find :param bool strict: specify if all ids should be find (when set to False, only half motor must be found) .. warning:: If two (or more) ports are attached to ...
def autodetect_robot(): """ Creates a :class:`~pypot.robot.robot.Robot` by detecting dynamixel motors on all available ports. """ motor_controllers = [] for port in get_available_ports(): for DxlIOCls in (DxlIO, Dxl320IO): dxl_io = DxlIOCls(port) ids = dxl_io.scan() ...
def get_register(self, motors, disable_sync_read=False): """ Gets the value from the specified register and sets it to the :class:`~pypot.dynamixel.motor.DxlMotor`. """ if not motors: return False ids = [m.id for m in motors] getter = getattr(self.io, 'get_{}'.format(self.re...
def set_register(self, motors): """ Gets the value from :class:`~pypot.dynamixel.motor.DxlMotor` and sets it to the specified register. """ if not motors: return ids = [m.id for m in motors] values = (m.__dict__[self.varname] for m in motors) getattr(self.io, 'set_{}...
def _filter(self, data): """ Apply a filter to reduce noisy data. Return the median value of a heap of data. """ filtered_data = [] for queue, data in zip(self._raw_data_queues, data): queue.append(data) filtered_data.append(numpy.median(queue)) ...
def simxGetJointPosition(clientID, jointHandle, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' position = ct.c_float() return c_GetJointPosition(clientID, jointHandle, ct.byref(position), operationMode), position.value
def simxSetJointPosition(clientID, jointHandle, position, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' return c_SetJointPosition(clientID, jointHandle, position, operationMode)
def simxGetJointMatrix(clientID, jointHandle, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' matrix = (ct.c_float*12)() ret = c_GetJointMatrix(clientID, jointHandle, matrix, operationMode) arr = [] for i in range(12): arr...
def simxSetSphericalJointMatrix(clientID, jointHandle, matrix, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' matrix = (ct.c_float*12)(*matrix) return c_SetSphericalJointMatrix(clientID, jointHandle, matrix, operationMode)
def simxSetJointTargetVelocity(clientID, jointHandle, targetVelocity, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' return c_SetJointTargetVelocity(clientID, jointHandle, targetVelocity, operationMode)
def simxSetJointTargetPosition(clientID, jointHandle, targetPosition, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' return c_SetJointTargetPosition(clientID, jointHandle, targetPosition, operationMode)
def simxJointGetForce(clientID, jointHandle, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' force = ct.c_float() return c_GetJointForce(clientID, jointHandle, ct.byref(force), operationMode), force.value