Create an out-of-process channel communicating to local jaeger-agent.
        Spans are submitted as SOCK_DGRAM Thrift, sampling strategy is polled
        via JSON HTTP.

        :param self: instance of Config
438845
def _create_local_agent_channel(self, io_loop):
        
        logger.info('Initializing Jaeger Tracer with UDP reporter')
        return LocalAgentSender(
            host=self.local_agent_reporting_host,
            sampling_port=self.local_agent_sampling_port,
            reporting_port=self.local_agent_reporting_port,
            throttling_port=self.throttler_port,
            io_loop=io_loop
        )
1340043
def process_request(self, request):
        
        # Initialize thread local storage
        threadlocal.auditlog = {
            'signal_duid': (self.__class__, time.time()),
            'remote_addr': request.META.get('REMOTE_ADDR'),
        }

        # In case of proxy, set 'original' address
        if request.META.get('HTTP_X_FORWARDED_FOR'):
            threadlocal.auditlog['remote_addr'] = request.META.get('HTTP_X_FORWARDED_FOR').split(',')[0]

        # Connect signal for automatic logging
        if hasattr(request, 'user') and is_authenticated(request.user):
            set_actor = curry(self.set_actor, user=request.user, signal_duid=threadlocal.auditlog['signal_duid'])
            pre_save.connect(set_actor, sender=LogEntry, dispatch_uid=threadlocal.auditlog['signal_duid'], weak=False)
276415
def _create_listening_stream(self, pull_addr):
        
        sock = self._zmq_context.socket(zmq.PULL)
        sock.connect(pull_addr)
        stream = ZMQStream(sock, io_loop=self.io_loop)

        return stream
890632
def construct_channel(self, *args, **kwargs):
        
        channel = self.get_channel(*args, **kwargs)   # creates ChannelNode from data in self.channel_info
        _build_tree(channel, SAMPLE_TREE)
        raise_for_invalid_channel(channel)

        return channel
775790
def do_threaded_dispatch(participant, msg)

      msg = Rufus::Json.dup(msg)
        #
        # the thread gets its own copy of the message
        # (especially important if the main thread does something with
        # the message 'during' the dispatch)

      # Maybe at some point a limit on the number of dispatch threads
      # would be OK.
      # Or maybe it's the job of an extension / subclass

      Thread.new { do_dispatch(participant, msg) }
    end
544263
function createLogger(name) {
    return (bunyan.createLogger({
        name: name,
        serializers: SERIALIZERS,
        streams: [
            {
                level: 'warn',
                stream: process.stderr
            },
            {
                level: 'debug',
                type: 'raw',
                stream: new RequestCaptureStream({
                    stream: process.stderr
                })
            }
        ]
    }));
}
1228489
def open_channel(self):
        
        logger.info('Creating a new channel')
        self._connection.channel(on_open_callback=self.on_channel_open)
992576
private static ChannelFuture socksConnect(Channel channel, InetSocketAddress remoteAddress)
    {
        channel.write(createHandshake(remoteAddress));
        return ((Socks4HandshakeHandler) channel.getPipeline().get("handshake")).getChannelFuture();
    }
114738
def _write_channel(self, out_data):
        
        if self.protocol == "ssh":
            self.remote_conn.sendall(write_bytes(out_data, encoding=self.encoding))
        elif self.protocol == "telnet":
            self.remote_conn.write(write_bytes(out_data, encoding=self.encoding))
        elif self.protocol == "serial":
            self.remote_conn.write(write_bytes(out_data, encoding=self.encoding))
            self.remote_conn.flush()
        else:
            raise ValueError("Invalid protocol specified")
        try:
            log.debug(
                "write_channel: {}".format(
                    write_bytes(out_data, encoding=self.encoding)
                )
            )
            if self._session_log_fin or self.session_log_record_writes:
                self._write_session_log(out_data)
        except UnicodeDecodeError:
            # Don't log non-ASCII characters; this is null characters and telnet IAC (PY2)
            pass
93913
def create(channel, body, properties=None):
        
        properties = properties or {}
        if 'correlation_id' not in properties:
            properties['correlation_id'] = str(uuid.uuid4())
        if 'message_id' not in properties:
            properties['message_id'] = str(uuid.uuid4())
        if 'timestamp' not in properties:
            properties['timestamp'] = datetime.utcnow()

        return Message(channel, auto_decode=False,
                       body=body, properties=properties)
637415
def open_channel(self):
        
        _logger.info('Creating a new channel')
        self._connection.channel(on_open_callback=self.on_channel_open)
332431
def emit(self, span_datas):
        
        jaeger_spans = self.translate_to_jaeger(span_datas)

        batch = jaeger.Batch(
            spans=jaeger_spans,
            process=jaeger.Process(serviceName=self.service_name))

        if self.collector is not None:
            self.collector.export(batch)
        self.agent_client.export(batch)
814005
def publish(self, channel, message):
        
        if self.cfg.jsonpickle:
            message = jsonpickle.encode(message)
        return self.conn.publish(channel, message)
1152467
def create_datagram_endpoint(loop, protocol_factory, local_addr=None, remote_addr=None, family=0, proto=0, flags=0):
        '''
        
        '''
        if not (local_addr or remote_addr):
            if not family:
                raise ValueError('unexpected address family')
            addr_pairs_info = (((family, proto), (None, None)),)
        else:
            addr_infos = OrderedDict()
            for idx, addr in ((0, local_addr), (1, remote_addr)):
                if addr is not None:
                    assert isinstance(addr, tuple) and len(addr) == 2, '2-tuple is expected'
                    infos = yield asyncio.coroutines.From(loop.getaddrinfo(
                        *addr, family=family, type=socket.SOCK_DGRAM, proto=proto, flags=flags))
                    if not infos:
                        raise socket.error('getaddrinfo() returned empty list')
                    for fam, _, pro, _, address in infos:
                        key = (fam, pro)
                        if key not in addr_infos:
                            addr_infos[key] = [None, None]
                        addr_infos[key][idx] = address
            addr_pairs_info = [
                (key, addr_pair) for key, addr_pair in addr_infos.items()
                if not ((local_addr and addr_pair[0] is None) or
                        (remote_addr and addr_pair[1] is None))]
            if not addr_pairs_info:
                raise ValueError('can not get address information')
        exceptions = []
        for ((family, proto),
             (local_address, remote_address)) in addr_pairs_info:
            sock = r_addr = None
            try:
                sock = socket.socket(family=family, type=socket.SOCK_DGRAM, proto=proto)
                for opt in [socket.SO_REUSEADDR, socket.SO_BROADCAST]:
                    sock.setsockopt(socket.SOL_SOCKET, opt, 1)
                sock.setblocking(False)
                if local_addr:
                    sock.bind(local_address)
                if remote_addr:
                    yield asyncio.coroutines.From(loop.sock_connect(sock, remote_address))
                    r_addr = remote_address
            except socket.error as exc:
                if sock is not None:
                    sock.close()
                exceptions.append(exc)
            except Exception:
                if sock is not None:
                    sock.close()
                raise
            else:
                break
        else:
            raise exceptions[0]

        protocol = protocol_factory()
        waiter = asyncio.futures.Future(loop=loop)
        transport = loop._make_datagram_transport(sock, protocol, r_addr, waiter)
        try:
            yield asyncio.coroutines.From(waiter)
        except Exception:
            transport.close()
            raise
        raise asyncio.coroutines.Return(transport, protocol)
709351
async def createOffer(self):
        
        # check state is valid
        self.__assertNotClosed()

        if not self.__sctp and not self.__transceivers:
            raise InternalError('Cannot create an offer with no media and no data channels')

        # offer codecs
        for transceiver in self.__transceivers:
            transceiver._codecs = filter_preferred_codecs(
                CODECS[transceiver.kind][:],
                transceiver._preferred_codecs,
            )
            transceiver._headerExtensions = HEADER_EXTENSIONS[transceiver.kind][:]

        mids = self.__seenMids.copy()

        # create description
        ntp_seconds = clock.current_ntp_time() >> 32
        description = sdp.SessionDescription()
        description.origin = '- %d %d IN IP4 0.0.0.0' % (ntp_seconds, ntp_seconds)
        description.msid_semantic.append(sdp.GroupDescription(
            semantic='WMS',
            items=['*']))
        description.type = 'offer'

        def get_media(description):
            return description.media if description else []

        def get_media_section(media, i):
            return media[i] if i < len(media) else None

        # handle existing transceivers / sctp
        local_media = get_media(self.__localDescription())
        remote_media = get_media(self.__remoteDescription())
        for i in range(max(len(local_media), len(remote_media))):
            local_m = get_media_section(local_media, i)
            remote_m = get_media_section(remote_media, i)
            media_kind = local_m.kind if local_m else remote_m.kind
            mid = local_m.rtp.muxId if local_m else remote_m.rtp.muxId
            if media_kind in ['audio', 'video']:
                transceiver = self.__getTransceiverByMid(mid)
                transceiver._set_mline_index(i)
                description.media.append(create_media_description_for_transceiver(
                    transceiver,
                    cname=self.__cname,
                    direction=transceiver.direction,
                    mid=mid))
            elif media_kind == 'application':
                self.__sctp_mline_index = i
                description.media.append(create_media_description_for_sctp(
                    self.__sctp, legacy=self._sctpLegacySdp, mid=mid))

        # handle new transceivers / sctp
        def next_mline_index():
            return len(description.media)

        for transceiver in filter(lambda x: x.mid is None and not x.stopped, self.__transceivers):
            transceiver._set_mline_index(next_mline_index())
            description.media.append(create_media_description_for_transceiver(
                transceiver,
                cname=self.__cname,
                direction=transceiver.direction,
                mid=allocate_mid(mids)))
        if self.__sctp and self.__sctp.mid is None:
            self.__sctp_mline_index = next_mline_index()
            description.media.append(create_media_description_for_sctp(
                self.__sctp, legacy=self._sctpLegacySdp, mid=allocate_mid(mids)))

        bundle = sdp.GroupDescription(semantic='BUNDLE', items=[])
        for media in description.media:
            bundle.items.append(media.rtp.muxId)
        description.group.append(bundle)

        return wrap_session_description(description)
1248831
def start_proxy(self):
        

        self.runner.info_log("Starting proxy...")

        self.proxy_port = self.browser_config.get('proxy_port', 8080)

        self.network_data_path = os.path.join(
            self.runner.runner_dir,
            'network_capture'
        )
        create_dir_if_doesnt_exist(self.network_data_path)

        self.local_proxy_output_path = os.path.join(
            self.network_data_path,
            string_to_filename('%s.data' % self.testname)
        )
        self.local_proxy_log_path = os.path.join(
            self.network_data_path,
            string_to_filename('%s.mitm' % self.testname)
        )

        self.remote_proxy_output_path = string_to_filename(
            '%s.data' % self.testname
        )
        self.remote_proxy_log_path = string_to_filename(
            '%s.mitm' % self.testname
        )

        path_to_mitmproxy = self.browser_config.get(
            "mitmproxy:path",
            'mitmdump'
        )

        filter_ = self.browser_config.get("mitmproxy:filter")
        command = [
            'DISPLAY=:0',
            'nohup',
            path_to_mitmproxy,
            "-p",
            "%s" % str(self.proxy_port),
            "-w",
            "'%s'" % self.remote_proxy_output_path
        ]

        if filter_:
            command.append(filter_)

        command.extend(['>', "'%s'" % self.remote_proxy_log_path, '2>&1'])
        command.append('&')

        self.execute_command(' '.join(command))
457900
def request_samples(network_id, channel_id)
      @logger.info("Requesting samples")
      @serial.transmit(SamplesRequest.new(:network_id => network_id, :channel_id => channel_id))
      AckResponse.read(@serial.receive(6))
      buffer = @serial.receive(4)
      remaining_bytes = buffer.bytes.to_a[3] + 1
      buffer += @serial.receive(remaining_bytes)
      response = SamplesResponse.read(buffer)

      response.converted_samples.each do |time, wattage|
        @logger.info("#{wattage}w at #{time}")
      end
      @logger.info("#{response.sample_count} returned, #{response.stored_sample_count} remaining")

      response
    end