示例#1
0
int LsapiConn::processRespHeader()
{
    register HttpExtConnector * pHEC = getConnector();
    int ret;
    int len = 0;
    if ( !pHEC )
        return -1;
    int &respState = pHEC->getRespState();
    if ( !(respState & 0xff) )
    {        
        while( m_iPacketLeft > 0 )
        {
            len = ExtConn::read( m_pRespHeader, m_pRespHeaderBufEnd - m_pRespHeader );
            if ( D_ENABLED( DL_MEDIUM ) )
                LOG_D(( getLogger(), "[%s] process response header %d bytes",
                    getLogId(), len ));
            if ( len > 0 )
            {
                m_iPacketLeft -= len;
                ret = processRespHeader( m_pRespHeader + len, respState ); 
                switch( ret )
                {
                case -2:
                    LOG_WARN(( getLogger(), "[%s] Invalid Http response header, retry!",
                            getLogId() ));
                    //debug code
                    //::write( 1, pBuf, len );
                    errno = ECONNRESET;
                case -1:
                    return -1;
                }
                
                if ( m_iPacketLeft > 0 )
                {
                    m_pRespHeader += len;
                    if (( m_pRespHeader > m_pRespHeaderProcess )&&
                        ( m_pRespHeader != &m_respBuf[ m_respInfo.m_cntHeaders * sizeof(short) ] ))
                    {
                        len = m_pRespHeader - m_pRespHeaderProcess;
                        memmove( &m_respBuf[ m_respInfo.m_cntHeaders * sizeof(short) ],
                                m_pRespHeaderProcess, m_pRespHeader - m_pRespHeaderProcess );
                        m_pRespHeaderProcess = &m_respBuf[ m_respInfo.m_cntHeaders * sizeof(short) ];
                        m_pRespHeader = m_pRespHeaderProcess + len;
                    }    
                    else
                        m_pRespHeader = m_pRespHeaderProcess = 
                                    &m_respBuf[ m_respInfo.m_cntHeaders * sizeof(short) ];
                    setRespBuf( m_pRespHeader );
                }
                
            }
            else
                return len;
        }
        if ( m_iPacketLeft == 0 )
        {
            m_iPacketHeaderLeft = LSAPI_PACKET_HEADER_LEN;
            len = 1;
        }
        return len;        
    }
    else
    {
        //error: protocol error, header received already.
		errno = EIO;
        return -1;
    }    
}
示例#2
0
void _pa_open(void) {
	PaStreamParameters outputParameters;
	PaError err = paNoError;
	int device_id;

	if (pa.stream) {
		if ((err = Pa_CloseStream(pa.stream)) != paNoError) {
			LOG_WARN("error closing stream: %s", Pa_GetErrorText(err));
		}
	}

	if (output.state == OUTPUT_OFF) {
		// we get called when transitioning to OUTPUT_OFF to create the probe thread
		// set err to avoid opening device and logging messages
		err = 1;

	} else if ((device_id = pa_device_id(output.device)) == -1) {
		LOG_INFO("device %s not found", output.device);
		err = 1;

	} else {

		outputParameters.device = device_id;
		outputParameters.channelCount = 2;
		outputParameters.sampleFormat = paInt32;
#ifndef PA18API
		outputParameters.suggestedLatency =
			output.latency ? (double)output.latency/(double)1000 : Pa_GetDeviceInfo(outputParameters.device)->defaultHighOutputLatency;
		outputParameters.hostApiSpecificStreamInfo = NULL;
		
#endif
#if OSX && !defined(OSXPPC)
		// enable pro mode which aims to avoid resampling if possible
		// see http://code.google.com/p/squeezelite/issues/detail?id=11 & http://code.google.com/p/squeezelite/issues/detail?id=37
		// command line controls osx_playnice which is -1 if not specified, 0 or 1 - choose playnice if -1 or 1
		PaMacCoreStreamInfo macInfo;
		unsigned long streamInfoFlags;
	 	if (output.osx_playnice) {
			LOG_INFO("opening device in PlayNice mode");
			streamInfoFlags = paMacCorePlayNice;
		} else {
			LOG_INFO("opening device in Pro mode");
			streamInfoFlags = paMacCorePro;
		}
		PaMacCore_SetupStreamInfo(&macInfo, streamInfoFlags);
		outputParameters.hostApiSpecificStreamInfo = &macInfo;
#endif
	}

	if (!err &&
#ifndef PA18API
		(err = Pa_OpenStream(&pa.stream, NULL, &outputParameters, (double)output.current_sample_rate, paFramesPerBufferUnspecified,
							 paPrimeOutputBuffersUsingStreamCallback | paDitherOff, pa_callback, NULL)) != paNoError) {
#else
		(err = Pa_OpenStream(&pa.stream, paNoDevice, 0, 0, NULL, outputParameters.device, outputParameters.channelCount,
							outputParameters.sampleFormat, NULL, (double)output.current_sample_rate, paFramesPerBuffer,
							paNumberOfBuffers, paDitherOff, pa_callback, NULL)) != paNoError) {

#endif
		LOG_WARN("error opening device %i - %s : %s", outputParameters.device, Pa_GetDeviceInfo(outputParameters.device)->name, 
				 Pa_GetErrorText(err));
	}

	if (!err) {
#ifndef PA18API
		LOG_INFO("opened device %i - %s at %u latency %u ms", outputParameters.device, Pa_GetDeviceInfo(outputParameters.device)->name,
				 (unsigned int)Pa_GetStreamInfo(pa.stream)->sampleRate, (unsigned int)(Pa_GetStreamInfo(pa.stream)->outputLatency * 1000));
#else
		LOG_INFO("opened device %i - %s at %u fpb %u nbf %u", outputParameters.device, Pa_GetDeviceInfo(outputParameters.device)->name,
				 (unsigned int)output.current_sample_rate, paFramesPerBuffer, paNumberOfBuffers);

#endif
		pa.rate = output.current_sample_rate;

#ifndef PA18API
		if ((err = Pa_SetStreamFinishedCallback(pa.stream, pa_stream_finished)) != paNoError) {
			LOG_WARN("error setting finish callback: %s", Pa_GetErrorText(err));
		}
	
		UNLOCK; // StartStream can call pa_callback in a sychronised thread on freebsd, remove lock while it is called

#endif
		if ((err = Pa_StartStream(pa.stream)) != paNoError) {
			LOG_WARN("error starting stream: %s", Pa_GetErrorText(err));
		}

#ifndef PA18API
		LOCK;
#endif
	}

	if (err && !monitor_thread_running) {
		vis_stop();

		// create a thread to check for output state change or device return
#if LINUX || OSX || FREEBSD
		pthread_create(&monitor_thread, NULL, pa_monitor, NULL);
#endif
#if WIN
		monitor_thread = CreateThread(NULL, OUTPUT_THREAD_STACK_SIZE, (LPTHREAD_START_ROUTINE)&pa_monitor, NULL, 0, NULL);
#endif
	}

	output.error_opening = !!err;
}
template < typename IN_PORT_TYPE > int tagged_file_sink_b_base::_analyzerServiceFunction( typename  std::vector< gr_istream< IN_PORT_TYPE > > &istreams )
{
    typedef typename std::vector< gr_istream< IN_PORT_TYPE > > _IStreamList;

    boost::mutex::scoped_lock lock(serviceThreadLock);

    if ( validGRBlock() == false ) {
        // create our processing block
        createBlock();

        LOG_DEBUG( tagged_file_sink_b_base, " FINISHED BUILDING  GNU RADIO BLOCK");
    }
   
    // process any Stream ID changes this could affect number of io streams
    processStreamIdChanges();
    
    if ( !validGRBlock() || istreams.size() == 0 ) {
        LOG_WARN( tagged_file_sink_b_base, "NO STREAMS ATTACHED TO BLOCK..." );
        return NOOP;
    }

    // resize data vectors for passing data to GR_BLOCK object
    _input_ready.resize( istreams.size() );
    _ninput_items_required.resize( istreams.size());
    _ninput_items.resize( istreams.size());
    _input_items.resize(istreams.size());
    _output_items.resize(0);
  
    //
    // RESOLVE: need to look at forecast strategy, 
    //    1)  see how many read items are necessary for N number of outputs
    //    2)  read input data and see how much output we can produce
    //
  
    //
    // Grab available data from input streams
    //
    typename _IStreamList::iterator istream = istreams.begin();
    int nitems=0;
    for ( int idx=0 ; istream != istreams.end() && serviceThread->threadRunning() ; idx++, istream++ ) {
        // note this a blocking read that can cause deadlocks
        nitems = istream->read();

        if ( istream->overrun() ) {
            LOG_WARN( tagged_file_sink_b_base, " NOT KEEPING UP WITH STREAM ID:" << istream->streamID );
        }
    
        // RESOLVE issue when SRI changes that could affect the GNU Radio BLOCK
        if ( istream->sriChanged() ) {
            LOG_DEBUG( tagged_file_sink_b_base, "SRI CHANGED, STREAMD IDX/ID: " 
                   << idx << "/" << istream->pkt->streamID );
        }
    }

    LOG_TRACE( tagged_file_sink_b_base, "READ NITEMS: "  << nitems );
    if ( nitems <= 0 && !_istreams[0].eos() ) return NOOP;

    bool eos = false;
    int  nout = 0;
    while ( nout > -1 && serviceThread->threadRunning() ) {
        eos = false;
        nout = _forecastAndProcess( eos, istreams );
        if ( nout > -1  ) {
            // we chunked on data so move read pointer..
            istream = istreams.begin();
            for ( ; istream != istreams.end(); istream++ ) {

                int idx=std::distance( istreams.begin(), istream );
                // if we processed data for this stream
                if ( _input_ready[idx] ) {
                    size_t nitems = 0;
                    try {
                        nitems = gr_sptr->nitems_read( idx );
                    } catch(...){}
      
                    if ( nitems > istream->nitems() ) {
                        LOG_WARN( tagged_file_sink_b_base,  "WORK CONSUMED MORE DATA THAN AVAILABLE,  READ/AVAILABLE " 
                                 << nitems << "/" << istream->nitems() );
                        nitems = istream->nitems();
                    }
                    istream->consume( nitems );
                    LOG_TRACE( tagged_file_sink_b_base, " CONSUME READ DATA  ITEMS/REMAIN " << nitems << "/" << istream->nitems());
                }
            }
            gr_sptr->reset_read_index();
        }

        // check for not enough data return
        if ( nout == -1 ) {

            // check for  end of stream
            istream = istreams.begin();
            for ( ; istream != istreams.end() ; istream++) {
                if ( istream->eos() ) {
                    eos=true;
                }
            }

            if ( eos ) {
                LOG_TRACE( tagged_file_sink_b_base, " DATA NOT READY, EOS:" << eos );
                _forecastAndProcess( eos, istreams );
            }
        }
    }

    if ( eos ) {
        istream = istreams.begin();
        for ( ; istream != istreams.end() ; istream++) {
            int idx=std::distance( istreams.begin(), istream );
            LOG_TRACE( tagged_file_sink_b_base, " CLOSING INPUT STREAM IDX:" << idx );
            istream->close();
        }
    }

    //
    // set the read pointers of the GNU Radio Block to start at the beginning of the 
    // supplied buffers
    //
    gr_sptr->reset_read_index();

    LOG_TRACE( tagged_file_sink_b_base, " END OF ANALYZER SERVICE FUNCTION....." << noutput_items );

    if ( nout == -1 && eos == false ) {
        return NOOP; 
    } else {
        return NORMAL;
    }
}
int deinterleave_bb_2o_base::_transformerServiceFunction( std::vector< gr_istream_base * > &istreams ,
        std::vector< gr_ostream_base * > &ostreams  )
{
    typedef std::vector< gr_istream_base * >   _IStreamList;
    typedef std::vector< gr_ostream_base * >  _OStreamList;

    boost::mutex::scoped_lock lock(serviceThreadLock);

    if ( validGRBlock() == false ) {

        // create our processing block, and setup  property notifiers
        createBlock();

        LOG_DEBUG( deinterleave_bb_2o_base, " FINISHED BUILDING  GNU RADIO BLOCK");
    }

    //process any Stream ID changes this could affect number of io streams
    processStreamIdChanges();

    if ( !validGRBlock() || istreams.size() == 0 || ostreams.size() == 0  ) {
        LOG_WARN( deinterleave_bb_2o_base, "NO STREAMS ATTACHED TO BLOCK..." );
        return NOOP;
    }

    _input_ready.resize( istreams.size() );
    _ninput_items_required.resize( istreams.size() );
    _ninput_items.resize( istreams.size() );
    _input_items.resize( istreams.size() );
    _output_items.resize( ostreams.size() );

    //
    // RESOLVE: need to look at forecast strategy,
    //    1)  see how many read items are necessary for N number of outputs
    //    2)  read input data and see how much output we can produce
    //

    //
    // Grab available data from input streams
    //
    _OStreamList::iterator ostream;
    _IStreamList::iterator istream = istreams.begin();
    int nitems=0;
    for ( int idx=0 ; istream != istreams.end() && serviceThread->threadRunning() ; idx++, istream++ ) {
        // note this a blocking read that can cause deadlocks
        nitems = (*istream)->read();

        if ( (*istream)->overrun() ) {
            LOG_WARN( deinterleave_bb_2o_base, " NOT KEEPING UP WITH STREAM ID:" << (*istream)->streamID );
        }

        if ( (*istream)->sriChanged() ) {
            // RESOLVE - need to look at how SRI changes can affect Gnu Radio BLOCK state
            LOG_DEBUG( deinterleave_bb_2o_base, "SRI CHANGED, STREAMD IDX/ID: "
                       << idx << "/" << (*istream)->getPktStreamId() );
            setOutputStreamSRI( idx, (*istream)->getPktSri() );
        }
    }

    LOG_TRACE( deinterleave_bb_2o_base, "READ NITEMS: "  << nitems );
    if ( nitems <= 0 && !_istreams[0]->eos() ) {
        return NOOP;
    }

    bool eos = false;
    int  nout = 0;
    bool workDone = false;

    while ( nout > -1 && serviceThread->threadRunning() ) {
        eos = false;
        nout = _forecastAndProcess( eos, istreams, ostreams );
        if ( nout > -1  ) {
            workDone = true;

            // we chunked on data so move read pointer..
            istream = istreams.begin();
            for ( ; istream != istreams.end(); istream++ ) {
                int idx=std::distance( istreams.begin(), istream );
                // if we processed data for this stream
                if ( _input_ready[idx] ) {
                    size_t nitems = 0;
                    try {
                        nitems = gr_sptr->nitems_read( idx );
                    } catch(...) {}

                    if ( nitems > (*istream)->nitems() ) {
                        LOG_WARN( deinterleave_bb_2o_base,  "WORK CONSUMED MORE DATA THAN AVAILABLE,  READ/AVAILABLE "
                                  << nitems << "/" << (*istream)->nitems() );
                        nitems = (*istream)->nitems();
                    }
                    (*istream)->consume( nitems );
                    LOG_TRACE( deinterleave_bb_2o_base, " CONSUME READ DATA  ITEMS/REMAIN " << nitems << "/" << (*istream)->nitems());
                }
            }
            gr_sptr->reset_read_index();
        }

        // check for not enough data return
        if ( nout == -1 ) {

            // check for  end of stream
            istream = istreams.begin();
            for ( ; istream != istreams.end() ; istream++) {
                if ( (*istream)->eos() ) {
                    eos=true;
                }
            }
            if ( eos ) {
                LOG_TRACE(  deinterleave_bb_2o_base, "EOS SEEN, SENDING DOWNSTREAM " );
                _forecastAndProcess( eos, istreams, ostreams);
            }
        }
    }

    if ( eos ) {
        istream = istreams.begin();
        for ( ; istream != istreams.end() ; istream++ ) {
            int idx=std::distance( istreams.begin(), istream );
            LOG_DEBUG( deinterleave_bb_2o_base, " CLOSING INPUT STREAM IDX:" << idx );
            (*istream)->close();
        }

        // close remaining output streams
        ostream = ostreams.begin();
        for ( ; eos && ostream != ostreams.end(); ostream++ ) {
            int idx=std::distance( ostreams.begin(), ostream );
            LOG_DEBUG( deinterleave_bb_2o_base, " CLOSING OUTPUT STREAM IDX:" << idx );
            (*ostream)->close();
        }
    }

    //
    // set the read pointers of the GNU Radio Block to start at the beginning of the
    // supplied buffers
    //
    gr_sptr->reset_read_index();

    LOG_TRACE( deinterleave_bb_2o_base, " END OF TRANSFORM SERVICE FUNCTION....." << noutput_items );

    if ( nout == -1 && eos == false && !workDone ) {
        return NOOP;
    } else {
        return NORMAL;
    }
}
示例#5
0
void RedChannel::run()
{
    for (;;) {
        Lock lock(_action_lock);
        if (_action == WAIT_ACTION) {
            _action_cond.wait(lock);
        }
        int action = _action;
        _action = WAIT_ACTION;
        lock.unlock();
        switch (action) {
        case CONNECT_ACTION:
            try {
                get_client().get_sync_info(get_type(), get_id(), _sync_info);
                on_connecting();
                set_state(CONNECTING_STATE);
                ConnectionOptions con_options(_client.get_connection_options(get_type()),
                                              _client.get_port(),
                                              _client.get_sport(),
                                              _client.get_protocol(),
                                              _client.get_host_auth_options(),
                                              _client.get_connection_ciphers());
                RedChannelBase::connect(con_options, _client.get_connection_id(),
                                        _client.get_host().c_str(),
                                        _client.get_password().c_str());
                /* If automatic protocol, remember the first connect protocol type */
                if (_client.get_protocol() == 0) {
                    if (get_peer_major() == 1) {
                        _client.set_protocol(1);
                    } else {
                        /* Major is 2 or unstable high value, use 2 */
                        _client.set_protocol(2);
                    }
                }
                /* Initialize when we know the remote major version */
                if (_client.get_peer_major() == 1) {
                    _marshallers = spice_message_marshallers_get1();
                } else {
                    _marshallers = spice_message_marshallers_get();
                }
                on_connect();
                set_state(CONNECTED_STATE);
                _loop.add_socket(*this);
                _socket_in_loop = true;
                on_event();
                _loop.run();
            } catch (RedPeer::DisconnectedException&) {
                _error = SPICEC_ERROR_CODE_SUCCESS;
            } catch (Exception& e) {
                LOG_WARN("%s", e.what());
                _error = e.get_error_code();
            } catch (std::exception& e) {
                LOG_WARN("%s", e.what());
                _error = SPICEC_ERROR_CODE_ERROR;
            }
            if (_socket_in_loop) {
                _socket_in_loop = false;
                _loop.remove_socket(*this);
            }
            if (_outgoing_message) {
                _outgoing_message->release();
                _outgoing_message = NULL;
            }
            _incomming_header_pos = 0;
            if (_incomming_message) {
                _incomming_message->unref();
                _incomming_message = NULL;
            }
        case DISCONNECT_ACTION:
            close();
            on_disconnect();
            set_state(DISCONNECTED_STATE);
            _client.on_channel_disconnected(*this);
            continue;
        case QUIT_ACTION:
            set_state(TERMINATED_STATE);
            return;
        }
    }
}
示例#6
0
void ChatHandler::processMessage(NetComputer *comp, MessageIn &message)
{
    ChatClient &computer = *static_cast< ChatClient * >(comp);
    MessageOut result;

    if (computer.characterName.empty())
    {
        if (message.getId() != PCMSG_CONNECT) return;

        std::string magic_token = message.readString(MAGIC_TOKEN_LENGTH);
        mTokenCollector.addPendingClient(magic_token, &computer);
        sendGuildRejoin(computer);
        return;
    }

    switch (message.getId())
    {
        case PCMSG_CHAT:
            handleChatMessage(computer, message);
            break;

        case PCMSG_ANNOUNCE:
            handleAnnounceMessage(computer, message);
            break;

        case PCMSG_PRIVMSG:
            handlePrivMsgMessage(computer, message);
            break;

        case PCMSG_WHO:
            handleWhoMessage(computer);
            break;

        case PCMSG_ENTER_CHANNEL:
            handleEnterChannelMessage(computer, message);
            break;

        case PCMSG_USER_MODE:
            handleModeChangeMessage(computer, message);
            break;

        case PCMSG_KICK_USER:
            handleKickUserMessage(computer, message);

        case PCMSG_QUIT_CHANNEL:
            handleQuitChannelMessage(computer, message);
            break;

        case PCMSG_LIST_CHANNELS:
            handleListChannelsMessage(computer, message);
            break;

        case PCMSG_LIST_CHANNELUSERS:
            handleListChannelUsersMessage(computer, message);
            break;

        case PCMSG_TOPIC_CHANGE:
            handleTopicChange(computer, message);
            break;

        case PCMSG_DISCONNECT:
            handleDisconnectMessage(computer, message);
            break;

        case PCMSG_GUILD_CREATE:
            handleGuildCreation(computer, message);
            break;

        case PCMSG_GUILD_INVITE:
            handleGuildInvitation(computer, message);
            break;

        case PCMSG_GUILD_ACCEPT:
            handleGuildAcceptInvite(computer, message);
            break;

        case PCMSG_GUILD_GET_MEMBERS:
            handleGuildRetrieveMembers(computer, message);
            break;

        case PCMSG_GUILD_PROMOTE_MEMBER:
            handleGuildMemberLevelChange(computer, message);
            break;

        case PCMSG_GUILD_KICK_MEMBER:
            handleGuildMemberKick(computer, message);

        case PCMSG_GUILD_QUIT:
            handleGuildQuit(computer, message);
            break;

        case PCMSG_PARTY_INVITE:
            handlePartyInvite(computer, message);
            break;

        case PCMSG_PARTY_ACCEPT_INVITE:
            handlePartyAcceptInvite(computer, message);
            break;

        case PCMSG_PARTY_QUIT:
            handlePartyQuit(computer);
            break;

        case PCMSG_PARTY_REJECT_INVITE:
            handlePartyRejection(computer, message);
            break;

        default:
            LOG_WARN("ChatHandler::processMessage, Invalid message type"
                     << message.getId());
            result.writeShort(XXMSG_INVALID);
            break;
    }

    if (result.getLength() > 0)
        computer.send(result);
}
    void
    readClusters(int n,
                 uint32_t pattern,
                 const ClusterLocation *loc,
                 bool verify = true,
                 int retries = 7)
    {
        uint64_t bufsz = dStore_->getClusterSize() * n;
        std::vector<uint8_t> buf(bufsz);
        //        uint64_t off;

        std::vector<ClusterReadDescriptor> descs;
        descs.reserve(n);

        // DataStoreNG::readClusters (more precisely, the partial backend read path)
        // asserts that it is not passed duplicate ClusterLocations. Intercept these
        // here and fail the test instead of taking down the whole process.
        std::set<std::string> locs;

        for (int i = 0; i < n; ++i)
        {
            const ClusterSize csize(dStore_->getClusterSize());
            ClusterLocationAndHash loc_and_hash(loc[i],
                                                &buf[0] + (i * csize),
                                                csize);
            BackendInterfacePtr bi = vol_->getBackendInterface(loc[i].cloneID())->clone();
            VERIFY(bi);
            descs.push_back(ClusterReadDescriptor(loc_and_hash,
                                                  i * csize,
                                                  &buf[i * csize],
                                                  std::move(bi)));

            const ClusterLocation& loc = loc_and_hash.clusterLocation;
            ASSERT_TRUE(locs.emplace(boost::lexical_cast<std::string>(loc)).second) <<
                "duplicate detected: " << loc_and_hash;
        }

        while (true)
        {
            try
            {
                dStore_->readClusters(descs);
            }
            catch (TransientException &)
            {
                LOG_WARN("backend congestion detected, retrying");
                if (--retries < 0)
                    throw;
                sleep(1);
                continue;
            }
            break;
        }

        if (verify)
        {
            for (uint32_t* p = (uint32_t *) buf.data(), off = 0; off < bufsz;
                 off += sizeof(*p), ++p)
            {
                ASSERT_EQ(pattern, *p) << "p: " << p <<
                    " off: " << off;
            }
        }
    }
示例#8
0
/***********************************************************************************************

    Basic functionality:

        The service function is called by the serviceThread object (of type ProcessThread).
        This call happens immediately after the previous call if the return value for
        the previous call was NORMAL.
        If the return value for the previous call was NOOP, then the serviceThread waits
        an amount of time defined in the serviceThread's constructor.
        
    SRI:
        To create a StreamSRI object, use the following code:
                std::string stream_id = "testStream";
                BULKIO::StreamSRI sri = bulkio::sri::create(stream_id);

	Time:
	    To create a PrecisionUTCTime object, use the following code:
                BULKIO::PrecisionUTCTime tstamp = bulkio::time::utils::now();

        
    Ports:

        Data is passed to the serviceFunction through the getPacket call (BULKIO only).
        The dataTransfer class is a port-specific class, so each port implementing the
        BULKIO interface will have its own type-specific dataTransfer.

        The argument to the getPacket function is a floating point number that specifies
        the time to wait in seconds. A zero value is non-blocking. A negative value
        is blocking.  Constants have been defined for these values, bulkio::Const::BLOCKING and
        bulkio::Const::NON_BLOCKING.

        Each received dataTransfer is owned by serviceFunction and *MUST* be
        explicitly deallocated.

        To send data using a BULKIO interface, a convenience interface has been added 
        that takes a std::vector as the data input

        NOTE: If you have a BULKIO dataSDDS port, you must manually call 
              "port->updateStats()" to update the port statistics when appropriate.

        Example:
            // this example assumes that the component has two ports:
            //  A provides (input) port of type bulkio::InShortPort called short_in
            //  A uses (output) port of type bulkio::OutFloatPort called float_out
            // The mapping between the port and the class is found
            // in the component base class header file

            bulkio::InShortPort::dataTransfer *tmp = short_in->getPacket(bulkio::Const::BLOCKING);
            if (not tmp) { // No data is available
                return NOOP;
            }

            std::vector<float> outputData;
            outputData.resize(tmp->dataBuffer.size());
            for (unsigned int i=0; i<tmp->dataBuffer.size(); i++) {
                outputData[i] = (float)tmp->dataBuffer[i];
            }

            // NOTE: You must make at least one valid pushSRI call
            if (tmp->sriChanged) {
                float_out->pushSRI(tmp->SRI);
            }
            float_out->pushPacket(outputData, tmp->T, tmp->EOS, tmp->streamID);

            delete tmp; // IMPORTANT: MUST RELEASE THE RECEIVED DATA BLOCK
            return NORMAL;

        If working with complex data (i.e., the "mode" on the SRI is set to
        true), the std::vector passed from/to BulkIO can be typecast to/from
        std::vector< std::complex<dataType> >.  For example, for short data:

            bulkio::InShortPort::dataTransfer *tmp = myInput->getPacket(bulkio::Const::BLOCKING);
            std::vector<std::complex<short> >* intermediate = (std::vector<std::complex<short> >*) &(tmp->dataBuffer);
            // do work here
            std::vector<short>* output = (std::vector<short>*) intermediate;
            myOutput->pushPacket(*output, tmp->T, tmp->EOS, tmp->streamID);

        Interactions with non-BULKIO ports are left up to the component developer's discretion

    Properties:
        
        Properties are accessed directly as member variables. For example, if the
        property name is "baudRate", it may be accessed within member functions as
        "baudRate". Unnamed properties are given a generated name of the form
        "prop_n", where "n" is the ordinal number of the property in the PRF file.
        Property types are mapped to the nearest C++ type, (e.g. "string" becomes
        "std::string"). All generated properties are declared in the base class
        (fastfilter_base).
    
        Simple sequence properties are mapped to "std::vector" of the simple type.
        Struct properties, if used, are mapped to C++ structs defined in the
        generated file "struct_props.h". Field names are taken from the name in
        the properties file; if no name is given, a generated name of the form
        "field_n" is used, where "n" is the ordinal number of the field.
        
        Example:
            // This example makes use of the following Properties:
            //  - A float value called scaleValue
            //  - A boolean called scaleInput
              
            if (scaleInput) {
                dataOut[i] = dataIn[i] * scaleValue;
            } else {
                dataOut[i] = dataIn[i];
            }
            
        A callback method can be associated with a property so that the method is
        called each time the property value changes.  This is done by calling 
        setPropertyChangeListener(<property name>, this, &fastfilter_i::<callback method>)
        in the constructor.
            
        Example:
            // This example makes use of the following Properties:
            //  - A float value called scaleValue
            
        //Add to fastfilter.cpp
        fastfilter_i::fastfilter_i(const char *uuid, const char *label) :
            fastfilter_base(uuid, label)
        {
            setPropertyChangeListener("scaleValue", this, &fastfilter_i::scaleChanged);
        }

        void fastfilter_i::scaleChanged(const std::string& id){
            std::cout << "scaleChanged scaleValue " << scaleValue << std::endl;
        }
            
        //Add to fastfilter.h
        void scaleChanged(const std::string&);
        
        
************************************************************************************************/
int fastfilter_i::serviceFunction()
{
    bulkio::InFloatPort::dataTransfer *tmp = dataFloat_in->getPacket(bulkio::Const::BLOCKING);
	if (not tmp) { // No data is available
		return NOOP;
	}

	if (tmp->inputQueueFlushed)
	{
		LOG_WARN(fastfilter_i, "input queue flushed - data has been thrown on the floor.  flushing internal buffers");
		//flush all our processor states if the queue flushed
		boost::mutex::scoped_lock lock(filterLock_);
		for (map_type::iterator i = filters_.begin(); i!=filters_.end(); i++)
			i->second.filter->flush();
	}
	bool updateSRI = tmp->sriChanged;
    float fs = 1.0/tmp->SRI.xdelta;
	{
		boost::mutex::scoped_lock lock(filterLock_);
		map_type::iterator i = filters_.find(tmp->streamID);
		firfilter* filter;
		if (i==filters_.end())
		{
			//this is a new stream - need to create a new filter & wrapper
			LOG_DEBUG(fastfilter_i, "creating new filter for streamID "<<tmp->streamID);
			if (manualTaps_)
			{
				LOG_DEBUG(fastfilter_i, "using manual taps ");
				bool real, complex;
				getManualTaps(real,complex);
				if (real)
					filter = new firfilter(fftSize, realOut, complexOut, realTaps_);
				else if(complex)
					filter = new firfilter(fftSize, realOut, complexOut, complexTaps_);
				else
				{
					LOG_WARN(fastfilter_i, "state error - using manual taps with no filter provided.  This shouldn't really happen");
					if (updateSRI)
						dataFloat_out->pushSRI(tmp->SRI);
					dataFloat_out->pushPacket(tmp->dataBuffer, tmp->T, tmp->EOS, tmp->streamID);
					delete tmp;
					return NORMAL;
				}
				updateSRI = true;
			}
			else
			{
				LOG_DEBUG(fastfilter_i, "using filter designer");
				correlationMode=false;
				if (filterProps.filterComplex)
				{
					designTaps(complexTaps_, fs);
					filter = new firfilter(fftSize, realOut, complexOut, complexTaps_);
				}
				else
				{
					designTaps(realTaps_, fs);
					filter = new firfilter(fftSize, realOut, complexOut, realTaps_);
				}
			}
			map_type::value_type filterWrapperMap(tmp->streamID, FilterWrapper());
			i = filters_.insert(filters_.end(),filterWrapperMap);
			i->second.setParams(fs,filter);
		}
		else
			//get the filter we have used before
			filter = i->second.filter;

		//if we are in design mode and the sample rate has changed - redesign and apply our filter
		if (!manualTaps_ && i->second.hasSampleRateChanged(fs))
		{
			if (filterProps.filterComplex)
			{
				designTaps(complexTaps_, fs);
				filter->setTaps(complexTaps_);
			}
			else
			{
				designTaps(realTaps_, fs);
				filter->setTaps(realTaps_);
			}
		}

		//now process the data
		if (tmp->SRI.mode==1)
		{
			//data is complex
			//run the filter
			std::vector<std::complex<float> >* cxData = (std::vector<std::complex<float> >*) &(tmp->dataBuffer);
			filter->newComplexData(*cxData);
		}
		else
		{
			//data is real
			//run the filter
			filter->newRealData(tmp->dataBuffer);
			//we might have a single complex frame if the previous data was complex and there were
			//complex data still in the filter taps
			if (!complexOut.empty())
			{
				//update the mode to true for the complex fame and force an sri push
				tmp->SRI.mode=1;
				updateSRI = true;
			}
		}
	    if (tmp->EOS)
	    {
	    	//if we have an eos - remove the wrapper from the container
	    	filters_.erase(i);
	    }
	}

	//to do -- adjust time stamps appropriately on all these output pushes
    // NOTE: You must make at least one valid pushSRI call
    if (updateSRI) {
    	dataFloat_out->pushSRI(tmp->SRI);
    }
    if (!complexOut.empty())
    {
    	std::vector<float>* tmpRealOut = (std::vector<float>*) &(complexOut);
    	dataFloat_out->pushPacket(*tmpRealOut, tmp->T, tmp->EOS, tmp->streamID);
    }
    if (!realOut.empty())
    {
    	//case we we forced a push on real data from previous complex data
    	//need to force our sri back to real and push another sri
    	if (updateSRI && tmp->SRI.mode==1)
    	{
    		//change mode back to 0 and send another sri with our real output
    		tmp->SRI.mode=0;
    		dataFloat_out->pushSRI(tmp->SRI);
    	}
    	dataFloat_out->pushPacket(realOut, tmp->T, tmp->EOS, tmp->streamID);
    }
    delete tmp; // IMPORTANT: MUST RELEASE THE RECEIVED DATA BLOCK
    return NORMAL;
}
示例#9
0
void *reader_thread(void *_arg)
{
	orc_t *orc = (orc_t*) _arg;

	setup_thread();

	orc->fd = -1;

	int reconnectcount = 0;

reconnect:
	
	// reconnect, if necessary.
	while (orc->fd < 0) {
		LOG_INFO("Trying to connect to orcboard...(%i)", reconnectcount++);
		orc->fd = orc->impl->connect(orc->impl);
		
		if (orc->fd < 0)
			sleep(1);
	}

	// read for a while
	while (1) {

		// read a packet
		uint8_t buf[3];
		int res = read_fully(orc->fd, buf, 1);
		if (res <= 0)
			goto disconnected;
		if (buf[0] != 0xED) {
			LOG_DEBUG("Recovering sync [%02X]", buf[0]);
			continue;
		}

		res = read_fully(orc->fd, &buf[1], 2);
		if (res <= 0)
			goto disconnected;

		int id = buf[1];
		int datalen = buf[2];

		transaction_t *t = &orc->transactions[id];
		memcpy(t->response, buf, 3);

		res = read_fully(orc->fd, &t->response[PACKET_DATA], datalen + 1);
		if (res <= 0)
			goto disconnected;
		if (!packet_test_checksum(t->response)) {
			LOG_WARN("Bad checksum received from Orc");
			continue;
		}

		if (t->response == garbage && t->response[1]>=orc->idLow && t->response[1]<=orc->idHigh)
			LOG_VERBOSE("Unsolicited ack, id = %02X", t->response[1]);

		// is this a message from orcd, assigning us a client id?
		if (t->response[1] == 0xf7) {
			orc->idLow = t->response[4];
			orc->idHigh = t->response[5];
			orc->idLast = orc->idLow;
			LOG_INFO("Got client transaction range: %02x-%02x", orc->idLow, orc->idHigh);
		}

		if (t->response[1] == 0xfe)
			handle_pad_packet(orc, t->response);

		if (t->response[1] == PACKET_ID_ORCBOARD_BROADCAST &&
		    packet_16u(t->response, 1) == MSG_ASYNC_HEARTBEAT)
			handle_heartbeat_packet(orc, t->response);

		pthread_mutex_lock(&t->mutex);
		pthread_cond_signal(&t->cond);
		pthread_mutex_unlock(&t->mutex);

	}
	
disconnected:
	orc->impl->disconnect(orc->impl, orc->fd);
	orc->fd = -1;
	goto reconnect;

	// silence compiler
	return NULL;
}
int HttpSvc::Sn::Handler_mediafile::parseRequest()
{
    int err = 0;

    // URI looks like /mediafile/tag/<deviceId>/<objectId>
    const std::string &uri = hs->GetUri();

    VPLHttp_SplitUri(uri, uri_tokens);
    if (uri_tokens.size() != 4) {
        LOG_ERROR("Handler_mediafile[%p]: Unexpected number of segments; uri %s", this, uri.c_str());
        std::ostringstream oss;
        oss << "{\"errMsg\":\"Unexpected number of segments; uri " << uri << "\"}";
        HttpStream_Helper::SetCompleteResponse(hs, 400, oss.str(), "application/json");
        return CCD_ERROR_PARAMETER;
    }
    objectId.assign(uri_tokens[3]);

    char buf[4096];
    char *reqBody = NULL;
    {
        ssize_t bytes = hs->Read(buf, sizeof(buf) - 1);  // subtract 1 for EOL
        if (bytes < 0) {
            LOG_ERROR("Handler_mediafile[%p]: Failed to read from HttpStream[%p]: err "FMT_ssize_t, this, hs, bytes);
            std::ostringstream oss;
            oss << "{\"errMsg\":\"Failed to read from HttpStream\"}";
            HttpStream_Helper::SetCompleteResponse(hs, 500, oss.str(), "application/json");
            return 0;
        }
        buf[bytes] = '\0';
        char *boundary = strstr(buf, "\r\n\r\n");  // find header-body boundary
        if (!boundary) {
            LOG_ERROR("Handler_mediafile[%p]: Failed to find header-body boundary in request", this);
            std::ostringstream oss;
            oss << "{\"errMsg\":\"Failed to find header-body boundary in request\"}";
            HttpStream_Helper::SetCompleteResponse(hs, 400, oss.str(), "application/json");
            return 0;
        }
        reqBody = boundary + 4;
    }

    cJSON2 *json = cJSON2_Parse(reqBody);
    if (!json) {
        LOG_ERROR("Handler_mediafile[%p]: Failed to parse JSON in request body %s", this, reqBody);
        std::ostringstream oss;
        oss << "{\"errMsg\":\"Failed to parse JSON in request body\"}";
        HttpStream_Helper::SetCompleteResponse(hs, 400, oss.str(), "application/json");
        return 0;
    }
    ON_BLOCK_EXIT(cJSON2_Delete, json);

    for (int i = 0; i < cJSON2_GetArraySize(json); i++) {
        cJSON2 *item = cJSON2_GetArrayItem(json, i);
        if (item->type != cJSON2_String) {
            LOG_WARN("Handler_mediafile[%p]: Ignored non-string value", this);
            continue;
        }
        tags.push_back(std::make_pair(item->string, item->valuestring));
    }

    return err;
}
示例#11
0
// checks for parsing overflows
void CheckOverflow(Packet *pkt, size_t size) {
  if (pkt->ptr + size - 1 >= pkt->len) {
    // overflow case, throw error
    LOG_WARN("Parsing error: pointer overflow for int");
  }
}
int32_t ofs_open_nolock(const char *ct_name, container_handle_t **ct)
{
    container_handle_t *tmp_ct = NULL;
    int32_t ret = 0;
    container_handle_t *hnd = NULL;
    avl_index_t where = 0;
    ofs_super_block_t *sb = NULL;

    if ((ct == NULL) || (ct_name == NULL))
    {
        LOG_ERROR("Invalid parameter. ct(%p) ct_name(%p)\n", ct, ct_name);
        return -INDEX_ERR_PARAMETER;
    }

    if (strlen(ct_name) >= OFS_NAME_SIZE)
    {
        LOG_ERROR("file name size must < %d bytes.\n", OFS_NAME_SIZE);
        return -INDEX_ERR_PARAMETER;
    }

    LOG_INFO("Open the ct. ct_name(%s)\n", ct_name);

    tmp_ct = avl_find(g_container_list, (avl_find_fn_t)compare_container2, ct_name, &where);
    if (tmp_ct)
    {
        tmp_ct->ref_cnt++;
        *ct = tmp_ct;
        LOG_WARN("File ref_cnt inc. ct_name(%s) ref_cnt(%d)\n", ct_name, tmp_ct->ref_cnt);
        return 0;
    }

    ret = init_container_resource(&tmp_ct, ct_name);
    if (ret < 0)
    {
        LOG_ERROR("Init ct resource failed. ct_name(%s) ret(%d)\n", ct_name, ret);
        return ret;
    }

    ret = os_disk_open(&tmp_ct->disk_hnd, ct_name);
    if (ret < 0)
    {
        LOG_ERROR("Open disk failed. ct_name(%s) ret(%d)\n", ct_name, ret);
        (void)close_container(tmp_ct);
        return ret;
    }

    sb = &tmp_ct->sb;

    sb->sectors_per_block = SECTORS_PER_BLOCK;
    sb->block_size = BYTES_PER_BLOCK;

    ret = ofs_read_super_block(tmp_ct);
    if (ret < 0)
    {
        LOG_ERROR("Read block failed. ct_name(%s) vbn(%lld) ret(%d)\n", ct_name, SUPER_BLOCK_VBN, ret);
        (void)close_container(tmp_ct);
        return ret;
    }

    ret = check_super_block(sb);
    if (ret < 0)
    {
        LOG_ERROR("Check super block failed. ct_name(%s) ret(%d)\n", ct_name, ret);
        (void)close_container(tmp_ct);
        return ret;
    }

    /* open system object */
    ret = open_system_objects(tmp_ct);
    if (ret < 0)
    {
        LOG_ERROR("Open system object failed. ct_name(%s) ret(%d)\n", ct_name, ret);
        close_container(tmp_ct);
        return ret;
    }

    *ct = tmp_ct;
    
    LOG_INFO("Open the ct success. ct_name(%s) ct(%p)\n", ct_name, ct);

    return 0;
}     
int32_t ofs_create_container_nolock(const char *ct_name, uint64_t total_sectors, container_handle_t **ct)
{
    container_handle_t *tmp_ct = NULL;
    int32_t ret = 0;
    avl_index_t where = 0;

    if ((ct == NULL) || (total_sectors == 0) || (ct_name == NULL))
    {
        LOG_ERROR("Invalid parameter. ct(%p) total_sectors(%lld) ct_name(%p)\n", ct, total_sectors, ct_name);
        return -INDEX_ERR_PARAMETER;
    }
    
    if (strlen(ct_name) >= OFS_NAME_SIZE)
    {
        LOG_ERROR("file name size must < %d bytes.\n", OFS_NAME_SIZE);
        return -INDEX_ERR_PARAMETER;
    }
    
    LOG_INFO("Create the ct. ct_name(%s) total_sectors(%lld)\n", ct_name, total_sectors);

    /* already opened */
    tmp_ct = avl_find(g_container_list, (avl_find_fn_t)compare_container2, ct_name, &where);
    if (tmp_ct)
    {
        *ct = tmp_ct;
        LOG_WARN("The ct is opened already. ct_name(%s) start_lba(%lld)\n", ct_name);
        return -INDEX_ERR_IS_OPENED;
    }

    /* allocate resource */
    ret = init_container_resource(&tmp_ct, ct_name);
    if (ret < 0)
    {
        LOG_ERROR("Init ct resource failed. ct_name(%s) ret(%d)", ct_name, ret);
        return ret;
    }
    
    /* init super block */
    ret = init_super_block(&tmp_ct->sb, total_sectors, BYTES_PER_BLOCK_SHIFT);
    if (ret < 0)
    {
        LOG_ERROR("init super block failed. name(%s)\n", ct_name);
        close_container(tmp_ct);
        return ret;
    }

    ret = os_disk_create(&tmp_ct->disk_hnd, ct_name);
    if (ret < 0)
    {
        LOG_ERROR("init disk failed. ret(%d)\n", ret);
        close_container(tmp_ct);
        return ret;
    }

    ret = ofs_init_super_block(tmp_ct);
    if (ret < 0)
    {
        LOG_ERROR("Update super block failed. ct_name(%s) vbn(%lld) ret(%d)\n", ct_name, SUPER_BLOCK_VBN, ret);
        close_container(tmp_ct);
        return ret;
    }
    
    ret = create_system_objects(tmp_ct);
    if (ret < 0)
    {
        LOG_ERROR("create system objects failed. ct_name(%s) ret(%d)\n", ct_name, ret);
        close_container(tmp_ct);
        return ret;
    }
    
    ret = ofs_update_super_block(tmp_ct);
    if (ret < 0)
    {
        LOG_ERROR("Update super block failed. hnd(%p) ret(%d)\n", tmp_ct, ret);
        close_container(tmp_ct);
        return ret;
    }

    *ct = tmp_ct;

    LOG_INFO("Create the ct success. ct_name(%s) total_sectors(%lld) ct(%p)\n", ct_name, total_sectors, tmp_ct);
    
    return 0;
}     
示例#14
0
void ScriptTest::runTest()
{
  // before we start remove any temporary files that we generated last time.
  _removeFile(_script + ".stdout.failed");
  _removeFile(_script + ".stderr.failed");
  _removeFile(_script + ".stdout.failed.stripped");
  _removeFile(_script + ".stderr.failed.stripped");
  _removeFile(_script + ".stdout.first");
  _removeFile(_script + ".stderr.first");
  _removeFile(_script + ".stdout.first.stripped");
  _removeFile(_script + ".stderr.first.stripped");
  _removeFile(_script + ".stdout.stripped");
  _removeFile(_script + ".stderr.stripped");

  _runProcess();

  if (QFile(_script + ".stdout").exists() == false || QFile(_script + ".stderr").exists() == false)
  {
    LOG_WARN("STDOUT or STDERR doesn't exist for " + _script +
             "\n*************************\n"
             "  This can be resolved by reviewing the output for correctness and then \n"
             "  creating a new baseline. E.g.\n"
             "  verify: \n"
             "    less " + _script + ".stdout.first\n"
             "    less " + _script + ".stderr.first\n"
             "  ### NOTE: If the test is comparing against a known good file (e.g. .osm\n"
             "  ### then it may be better to update that file. You'll have to look at\n"
             "  ### the source files to be sure.\n"
             "  Make a new baseline:\n"
             "    mv " + _script + ".stdout.first " + _script + ".stdout\n"
             "    mv " + _script + ".stderr.first " + _script + ".stderr\n"
             "*************************\n"
             );

    _baseStderr = "<invalid/>";
    _baseStdout = "<invalid/>";
    _writeFile(_script + ".stdout.first", _stdout);
    _writeFile(_script + ".stderr.first", _stderr);
    _writeFile(_script + ".stdout.first.stripped", _removeIgnoredSubstrings(_stdout));
    _writeFile(_script + ".stderr.first.stripped", _removeIgnoredSubstrings(_stderr));
    CPPUNIT_ASSERT_MESSAGE(QString("STDOUT or STDERR does not exist").toStdString(), false);
  }

  _baseStderr = _readFile(_script + ".stderr");
  _baseStdout = _readFile(_script + ".stdout");

  bool failed = false;

  if (_removeIgnoredSubstrings(_baseStdout) != _removeIgnoredSubstrings(_stdout))
  {
    _writeFile(_script + ".stdout.failed", _stdout);
    _writeFile(_script + ".stdout.failed.stripped", _removeIgnoredSubstrings(_stdout));
    _writeFile(_script + ".stdout.stripped", _removeIgnoredSubstrings(_baseStdout));

    if (_printDiff)
    {
      LOG_WARN("STDOUT does not match for:\n" +
        _script + ".stdout" + " " + _script + ".stdout.failed");
      _runDiff(_script + ".stdout.stripped", _script + ".stdout.failed.stripped");
    }
    else
    {
      LOG_WARN("STDOUT does not match for:\n" +
               _script + ".stdout.failed" + " " + _script + ".stdout\n"
               "\n*************************\n"
               "  This can be resolved by reviewing the output for correctness and then \n"
               "  creating a new baseline. E.g.\n"
               "  verify: \n"
               "    diff " + _script + ".stdout.stripped " + _script + ".stdout.failed.stripped\n"
               "  ### NOTE: If the test is comparing against a known good file (e.g. .osm\n"
               "  ### then it may be better to update that file. You'll have to look at\n"
               "  ### the source files to be sure.\n"
               "  Make a new baseline:\n"
               "    mv " + _script + ".stdout.failed " + _script + ".stdout\n"
               "*************************\n"
               );
    }

    failed = true;
  }

  if (_removeIgnoredSubstrings(_baseStderr) != _removeIgnoredSubstrings(_stderr))
  {
    _writeFile(_script + ".stderr.failed", _stderr);
    _writeFile(_script + ".stderr.failed.stripped", _removeIgnoredSubstrings(_stderr));
    _writeFile(_script + ".stderr.stripped", _removeIgnoredSubstrings(_baseStderr));

    if (_printDiff)
    {
      LOG_WARN("STDERR does not match for:\n" +
        _script + ".stderr" + " " + _script + ".stderr.failed");
      _runDiff(_script + ".stderr.stripped", _script + ".stderr.failed.stripped");
    }
    else
    {
      LOG_WARN("STDERR does not match for:\n" +
               _script + ".stderr.failed" + " " + _script + ".stderr\n"
               "\n*************************\n"
               "  This can be resolved by reviewing the output for correctness and then \n"
               "  creating a new baseline. E.g.\n"
               "  verify: \n"
               "    diff " + _script + ".stderr.stripped " + _script + ".stderr.failed.stripped\n"
               "  ### NOTE: If the test is comparing against a known good file (e.g. .osm\n"
               "  ### then it may be better to update that file. You'll have to look at\n"
               "  ### the source files to be sure.\n"
               "  Make a new baseline:\n"
               "    mv " + _script + ".stderr.failed " + _script + ".stderr\n"
               "*************************\n"
               );
    }

    failed = true;
  }

  if (failed)
  {
    CPPUNIT_ASSERT_MESSAGE(QString("STDOUT or STDERR does not match").toStdString(), false);
  }
}
示例#15
0
void thread_mutex_unlock_c(mutex_t *mutex, int line, char *file)
{
#ifdef DEBUG_MUTEXES
    thread_type *th = thread_self();

    if (!th) {
        LOG_ERROR3("No record for %u in unlock [%s:%d]", thread_self(), file, line);
    }

    LOG_DEBUG5("Unlocking %p (%s) on line %d in file %s by thread %d", mutex, mutex->name, line, file, th ? th->thread_id : -1);

    mutex->line = line;

# ifdef CHECK_MUTEXES
    if (th) {
        int locks = 0;
        avl_node *node;
        mutex_t *tmutex;

        _mutex_lock(&_mutextree_mutex);

        while (node) {
            tmutex = (mutex_t *)node->key;

            if (tmutex->mutex_id == mutex->mutex_id) {
                if (tmutex->thread_id != th->thread_id) {
                    LOG_ERROR7("ILLEGAL UNLOCK (%d != %d) on mutex [%s] in file %s line %d by thread %d [%s]", tmutex->thread_id, th->thread_id, 
                         mutex->name ? mutex->name : "undefined", file, line, th->thread_id, th->name);
                    _mutex_unlock(&_mutextree_mutex);
                    return;
                }
            } else if (tmutex->thread_id == th->thread_id) {
                locks++;
            }

            node = avl_get_next (node);
        }

        if ((locks > 0) && (_multi_mutex.thread_id != th->thread_id)) {
            /* Don't have double mutex, has more than this mutex left */
        
            LOG_WARN("(%d != %d) Thread %d [%s] tries to unlock a mutex [%s] in file %s line %d, without owning double mutex!",
                 _multi_mutex.thread_id, th->thread_id, th->thread_id, th->name, mutex->name ? mutex->name : "undefined", file, line);
        }

        _mutex_unlock(&_mutextree_mutex);
    }
# endif  /* CHECK_MUTEXES */

    _mutex_unlock(mutex);

    _mutex_lock(&_mutextree_mutex);

    LOG_DEBUG2("Unlocked %p by thread %d", mutex, th ? th->thread_id : -1);
    mutex->line = -1;
    if (mutex->thread_id == th->thread_id) {
        mutex->thread_id = MUTEX_STATE_NOTLOCKED;
    }

    _mutex_unlock(&_mutextree_mutex);
#else
    _mutex_unlock(mutex);
#endif /* DEBUG_MUTEXES */
}
示例#16
0
void ContactLoop::run(){
	#ifdef CONTACTLOOP_TIMING
		timingDeltas->start();
	#endif

	DemField& dem=field->cast<DemField>();

	if(dem.contacts->removeAllPending()>0 && !alreadyWarnedNoCollider){
		LOG_WARN("Contacts pending removal found (and were removed); no collider being used?");
		alreadyWarnedNoCollider=true;
	}

	if(dem.contacts->dirty){
		throw std::logic_error("ContactContainer::dirty is true; the collider should re-initialize in such case and clear the dirty flag.");
	}
	// update Scene* of the dispatchers
	geoDisp->scene=phyDisp->scene=lawDisp->scene=scene;
	geoDisp->field=phyDisp->field=lawDisp->field=field;
	// ask dispatchers to update Scene* of their functors
	geoDisp->updateScenePtr(); phyDisp->updateScenePtr(); lawDisp->updateScenePtr();

	// cache transformed cell size
	Matrix3r cellHsize; if(scene->isPeriodic) cellHsize=scene->cell->hSize;

	stress=Matrix3r::Zero();

	// force removal of interactions that were not encountered by the collider
	// (only for some kinds of colliders; see comment for InteractionContainer::iterColliderLastRun)
	bool removeUnseen=(dem.contacts->stepColliderLastRun>=0 && dem.contacts->stepColliderLastRun==scene->step);

	const bool doStress=(evalStress && scene->isPeriodic);
	const bool deterministic(scene->deterministic);

	if(reorderEvery>0 && (scene->step%reorderEvery==0)) reorderContacts();

	size_t size=dem.contacts->size();

	CONTACTLOOP_CHECKPOINT("prologue");

	const bool hasHook=!!hook;

	#ifdef WOO_OPENMP
		#pragma omp parallel for schedule(guided)
	#endif
	for(size_t i=0; i<size; i++){
		CONTACTLOOP_CHECKPOINT("loop-begin");
		const shared_ptr<Contact>& C=(*dem.contacts)[i];

		if(unlikely(removeUnseen && !C->isReal() && C->stepLastSeen<scene->step)) { removeAfterLoop(C); continue; }
		if(unlikely(!C->isReal() && !C->isColliding())){ removeAfterLoop(C); continue; }

		/* this block is called exactly once for every potential contact created; it should check whether shapes
			should be swapped, and also set minDist00Sq if used (Sphere-Sphere only)
		*/
		if(unlikely(!C->isReal() && C->isFresh(scene))){
			bool swap=false;
			const shared_ptr<CGeomFunctor>& cgf=geoDisp->getFunctor2D(C->leakPA()->shape,C->leakPB()->shape,swap);
			if(!cgf) continue;
			if(swap){ C->swapOrder(); }
			cgf->setMinDist00Sq(C->pA.lock()->shape,C->pB.lock()->shape,C);
			CONTACTLOOP_CHECKPOINT("swap-check");
		}
		Particle *pA=C->leakPA(), *pB=C->leakPB();
		Vector3r shift2=(scene->isPeriodic?scene->cell->intrShiftPos(C->cellDist):Vector3r::Zero());
		// the order is as the geometry functor expects it
		shared_ptr<Shape>& sA(pA->shape); shared_ptr<Shape>& sB(pB->shape);

		// if minDist00Sq is defined, we might see that there is no contact without ever calling the functor
		// saving quite a few calls for sphere-sphere contacts
		if(likely(dist00 && !C->isReal() && !C->isFresh(scene) && C->minDist00Sq>0 && (sA->nodes[0]->pos-(sB->nodes[0]->pos+shift2)).squaredNorm()>C->minDist00Sq)){
			CONTACTLOOP_CHECKPOINT("dist00Sq-too-far");
			continue;
		}

		CONTACTLOOP_CHECKPOINT("pre-geom");

		bool geomCreated=geoDisp->operator()(sA,sB,shift2,/*force*/false,C);

		CONTACTLOOP_CHECKPOINT("geom");
		if(!geomCreated){
			if(/* has both geo and phy */C->isReal()) LOG_ERROR("CGeomFunctor "<<geoDisp->getClassName()<<" did not update existing contact ##"<<pA->id<<"+"<<pB->id);
			continue;
		}


		// CPhys
		if(!C->phys) C->stepCreated=scene->step;
		if(!C->phys || updatePhys>UPDATE_PHYS_NEVER) phyDisp->operator()(pA->material,pB->material,C);
		if(!C->phys) throw std::runtime_error("ContactLoop: ##"+to_string(pA->id)+"+"+to_string(pB->id)+": con Contact.phys created from materials "+pA->material->getClassName()+" and "+pB->material->getClassName()+" (a CPhysFunctor must be available for every contacting material combination).");

		if(hasHook && C->isFresh(scene) && hook->isMatch(pA->mask,pB->mask)) hook->hookNew(dem,C);

		CONTACTLOOP_CHECKPOINT("phys");

		// CLaw
		bool keepContact=lawDisp->operator()(C->geom,C->phys,C);
		if(!keepContact){
			if(hasHook && hook->isMatch(pA->mask,pB->mask)) hook->hookDel(dem,C); // call before requestRemove resets contact internals
			dem.contacts->requestRemoval(C);
		}
		CONTACTLOOP_CHECKPOINT("law");

		if(applyForces && C->isReal() && likely(!deterministic)){
			applyForceUninodal(C,pA);
			applyForceUninodal(C,pB);
			#if  0
			for(const Particle* particle:{pA,pB}){
				// remove once tested thoroughly
					const shared_ptr<Shape>& sh(particle->shape);
					if(!sh || sh->nodes.size()!=1) continue;
					// if(sh->nodes.size()!=1) continue;
					#if 0
						for(size_t i=0; i<sh->nodes.size(); i++){
							if((sh->nodes[i]->getData<DemData>().flags&DemData::DOF_ALL)!=DemData::DOF_ALL) LOG_WARN("Multinodal #"<<particle->id<<" has free DOFs, but force will not be applied; set ContactLoop.applyForces=False and use IntraForce(...) dispatcher instead.");
						}
					#endif
					Vector3r F,T,xc;
					std::tie(F,T,xc)=C->getForceTorqueBranch(particle,/*nodeI*/0,scene);
					sh->nodes[0]->getData<DemData>().addForceTorque(F,xc.cross(F)+T);
			}
			#endif
		}

		// track gradV work
		/* this is meant to avoid calling extra loop at every step, since the work must be evaluated incrementally */
		if(doStress && /*contact law deleted the contact?*/ C->isReal()){
			const auto& nnA(pA->shape->nodes); const auto& nnB(pB->shape->nodes);
			if(nnA.size()!=1 || nnB.size()!=1) throw std::runtime_error("ContactLoop.trackWork not allowed with multi-nodal particles in contact (##"+lexical_cast<string>(pA->id)+"+"+lexical_cast<string>(pB->id)+")");
			Vector3r branch=C->dPos(scene); // (nnB[0]->pos-nnA[0]->pos+scene->cell->intrShiftPos(C->cellDist));
			Vector3r F=C->geom->node->ori*C->phys->force; // force in global coords
			#ifdef WOO_OPENMP
				#pragma omp critical
			#endif
			{
				stress.noalias()+=F*branch.transpose();
			}
		}
		CONTACTLOOP_CHECKPOINT("force+stress");
	}
	// process removeAfterLoop
	#ifdef WOO_OPENMP
		for(list<shared_ptr<Contact>>& l: removeAfterLoopRefs){
			for(const shared_ptr<Contact>& c: l) dem.contacts->remove(c);
			l.clear();
		}
	#else
		for(const shared_ptr<Contact>& c: removeAfterLoopRefs) dem.contacts->remove(c);
		removeAfterLoopRefs.clear();
	#endif
	// compute gradVWork eventually
	if(doStress){
		stress/=scene->cell->getVolume();
		if(scene->trackEnergy){
			Matrix3r midStress=.5*(stress+prevStress);
			Real midVol=(!isnan(prevVol)?.5*(prevVol+scene->cell->getVolume()):scene->cell->getVolume());
			Real dW=-(scene->cell->gradV*midStress).trace()*scene->dt*midVol;
			scene->energy->add(dW,"gradV",gradVIx,EnergyTracker::IsIncrement | EnergyTracker::ZeroDontCreate);
		}
		//prevTrGradVStress=trGradVStress;
		prevVol=scene->cell->getVolume();
		prevStress=stress;
	}
	// apply forces deterministically, after the parallel loop
	// this could be also loop over particles in parallel (since per-particle loop would still be deterministic) but time per particle is very small here
	if(unlikely(deterministic) && applyForces){
		// non-paralell loop here
		for(const auto& C: *dem.contacts){
			if(!C->isReal()) continue;
			applyForceUninodal(C,C->leakPA());
			applyForceUninodal(C,C->leakPB());
		}
	}
	// reset updatePhys if it was to be used only once
	if(updatePhys==UPDATE_PHYS_ONCE) updatePhys=UPDATE_PHYS_NEVER;
	CONTACTLOOP_CHECKPOINT("epilogue");
}
void ServiceDescription::setDescription(const std::string& label, const std::string& description)
{
	// Total size of mDNS up to the IP MTU of the physical interface, less
	// the space required for UP header (20 bytes IPv4/40 bytes IPv6, and UDP header 8bytes)
	// MAXIMUM 9000 bytes !!!! we consider max as 2312 (WiFi)
	// considering IPv6 and UDP: 2312 - 48 = 2264 bytes
	// sety margin for description we use max 2000 bytes
	// http://files.multicastdns.org/drt-cheshire-dnsext-multicastdns.txt
	// page 41
	int descriptionsSize = description.size();

	// +1 for the equal sign
	int labelSize = label.size() + 1;
	if( labelSize > 100 )
	{
		LOG_WARN("Size of label is larger than 100 bytes. Description payload of less than 100 bytes.");
	} else if (labelSize >= 200)
	{
		LOG_FATAL("Size of label exceeds maximum payload size");
		throw std::runtime_error("Size of label exceeds maximum payload size");
	}

	// Based on size how much bytes does the description consume
	int requiredNumberOfEntries = ceil( static_cast<double>(descriptionsSize) / static_cast<double>(mDNSMaxRecordSize - label.size()) );

	int currentDescriptionSize = getDescriptionSize();
	unsigned int currentPayloadSize = descriptionsSize + requiredNumberOfEntries * label.size() + currentDescriptionSize;

	if( currentPayloadSize > mDNSMaxPayloadSize)
	{
		char buffer[256];
		snprintf(buffer,256, "Size of descriptions exceeds maximum allowed payload size: current %d vs. maximum %d", currentPayloadSize, mDNSMaxPayloadSize);
		LOG_FATAL(buffer)
		throw std::runtime_error(buffer);
	}

	std::list<std::string>::iterator it;	

	std::list<std::string> tmpDescriptions;

	// positive selection of items
	// leave out items with the same label
	for(it = descriptions_.begin(); it != descriptions_.end(); it++)
	{		
		std::string item = *it;
		if( item.substr(0, label.size()) != label)
			tmpDescriptions.push_back(item);
	}

	// add new items
	for(int i = 0; i < requiredNumberOfEntries; i++)
	{
		// split description in chunks of 200 - label +1
		// create entry such as: "IOR=2812739831273"
		std::string entry;
		if (i == 0)
			entry = label + "=" + description.substr(200*i,200 - labelSize);
		else
			entry = label + "=" + description.substr((200-labelSize)*i,200 - labelSize);
		tmpDescriptions.push_back(entry);
	}

	descriptions_ = std::list<std::string>();

	// add Label to labels
	if(! static_cast<int>(count(labels_.begin(), labels_.end(), label)))
		labels_.push_back(label);	

	descriptions_ = tmpDescriptions;
}
示例#18
0
void qc_per_read(int i, int length, int base_quality, int* mean_read_quality, long* read_sum_length, results_server_input_t* input_p, qc_batch_t* qc_batch_p, status_batch_t* status_batch_p, qc_report_t* qc_report, int cpu_num_threads) {
    int index, counters_a, counters_c, counters_g, counters_t, counters_n;
    int source_id = qc_batch_p->source_id;

    if (length > 0) {
        if (length > MAX_LINE_LENGTH) {
            char log_message[50];
            sprintf(log_message, "Be careful, length = %i > MAX_LINE_LENGTH (%i)\n", length, MAX_LINE_LENGTH);
            LOG_WARN(log_message);
        }

        if (length < qc_report[source_id].min_read_length) {
            qc_report[source_id].min_read_length = length;
        }
        if (length > qc_report[source_id].max_read_length) {
            qc_report[source_id].max_read_length = length;
        }

        read_sum_length[source_id] += length;

        // variables are filled depending on the read status
        if (status_batch_p->read_status[i] == RTRIM_READ) {
            *mean_read_quality = GET_16_24(qc_batch_p->gpu_result_p[i].counters[TRIM_QUALITY]) - base_quality;
            counters_a = GET_0_12(qc_batch_p->gpu_result_p[i].counters[A]) - GET_12_22(qc_batch_p->gpu_result_p[i].counters[A]);
            counters_c = GET_0_12(qc_batch_p->gpu_result_p[i].counters[C]) - GET_12_22(qc_batch_p->gpu_result_p[i].counters[C]);
            counters_g = GET_0_12(qc_batch_p->gpu_result_p[i].counters[G]) - GET_12_22(qc_batch_p->gpu_result_p[i].counters[G]);
            counters_t = GET_0_12(qc_batch_p->gpu_result_p[i].counters[T]) - GET_12_22(qc_batch_p->gpu_result_p[i].counters[T]);
            counters_n = GET_0_12(qc_batch_p->gpu_result_p[i].counters[N]) - GET_12_22(qc_batch_p->gpu_result_p[i].counters[N]);
        } else if (status_batch_p->read_status[i] == TRIM_READ) {
            *mean_read_quality = GET_8_16(qc_batch_p->gpu_result_p[i].counters[TRIM_QUALITY]) - base_quality;
            counters_a = GET_0_12(qc_batch_p->gpu_result_p[i].counters[A]) - GET_12_22(qc_batch_p->gpu_result_p[i].counters[A]) - GET_22_32(qc_batch_p->gpu_result_p[i].counters[A]);
            counters_c = GET_0_12(qc_batch_p->gpu_result_p[i].counters[C]) - GET_12_22(qc_batch_p->gpu_result_p[i].counters[C]) - GET_22_32(qc_batch_p->gpu_result_p[i].counters[C]);
            counters_g = GET_0_12(qc_batch_p->gpu_result_p[i].counters[G]) - GET_12_22(qc_batch_p->gpu_result_p[i].counters[G]) - GET_22_32(qc_batch_p->gpu_result_p[i].counters[G]);
            counters_t = GET_0_12(qc_batch_p->gpu_result_p[i].counters[T]) - GET_12_22(qc_batch_p->gpu_result_p[i].counters[T]) - GET_22_32(qc_batch_p->gpu_result_p[i].counters[T]);
            counters_n = GET_0_12(qc_batch_p->gpu_result_p[i].counters[N]) - GET_12_22(qc_batch_p->gpu_result_p[i].counters[N]) - GET_22_32(qc_batch_p->gpu_result_p[i].counters[N]);
        } else if (status_batch_p->read_status[i] == LTRIM_READ) {
            *mean_read_quality = GET_24_32(qc_batch_p->gpu_result_p[i].counters[TRIM_QUALITY]) - base_quality;
            counters_a = GET_0_12(qc_batch_p->gpu_result_p[i].counters[A]) - GET_22_32(qc_batch_p->gpu_result_p[i].counters[A]);
            counters_c = GET_0_12(qc_batch_p->gpu_result_p[i].counters[C]) - GET_22_32(qc_batch_p->gpu_result_p[i].counters[C]);
            counters_g = GET_0_12(qc_batch_p->gpu_result_p[i].counters[G]) - GET_22_32(qc_batch_p->gpu_result_p[i].counters[G]);
            counters_t = GET_0_12(qc_batch_p->gpu_result_p[i].counters[T]) - GET_22_32(qc_batch_p->gpu_result_p[i].counters[T]);
            counters_n = GET_0_12(qc_batch_p->gpu_result_p[i].counters[N]) - GET_22_32(qc_batch_p->gpu_result_p[i].counters[N]);
        } else {
            *mean_read_quality = GET_0_8(qc_batch_p->gpu_result_p[i].counters[TRIM_QUALITY]) - base_quality;
            counters_a = GET_0_12(qc_batch_p->gpu_result_p[i].counters[A]);
            counters_c = GET_0_12(qc_batch_p->gpu_result_p[i].counters[C]);
            counters_g = GET_0_12(qc_batch_p->gpu_result_p[i].counters[G]);
            counters_t = GET_0_12(qc_batch_p->gpu_result_p[i].counters[T]);
            counters_n = GET_0_12(qc_batch_p->gpu_result_p[i].counters[N]);
        }

        qc_report[source_id].mean_read_quality += *mean_read_quality;
        qc_report[source_id].per_sequence_quality[*mean_read_quality]++;
        qc_report[source_id].a_perc += counters_a;
        qc_report[source_id].c_perc += counters_c;
        qc_report[source_id].g_perc += counters_g;
        qc_report[source_id].t_perc += counters_t;
        qc_report[source_id].n_perc += counters_n;

        qc_report[source_id].gc_histogram[100 * (counters_g + counters_c)/(counters_a + counters_c + counters_g + counters_t + counters_n)]++;

        // intervals of nt count must be calculated depending on the read status
        int length_after_trims, init_pos, end_pos;

        if (status_batch_p->read_status[i] == RTRIM_READ) {
            length_after_trims = length - input_p->rtrim_nts;
            init_pos = 0;
            end_pos = length - input_p->rtrim_nts;
        } else if (status_batch_p->read_status[i] == TRIM_READ) {
            length_after_trims = length - input_p->rtrim_nts - input_p->ltrim_nts;
            init_pos = input_p->ltrim_nts;
            end_pos = length - input_p->rtrim_nts;
        } else if (status_batch_p->read_status[i] == LTRIM_READ) {
            length_after_trims = length - input_p->ltrim_nts;
            init_pos = input_p->ltrim_nts;
            end_pos = length;
        } else {
            length_after_trims = length;
            init_pos = 0;
            end_pos = length;
        }

        //end position relative to init position
        int end_relative_pos = end_pos - init_pos;

        //offset of the quality index: init_pos + vector index + offset of the read/quality pair in data vector
        index = init_pos + qc_batch_p->read_p->data_indices[i] - 1;

        for (int j = 0 ; j < end_relative_pos ; j++) {
            index++;
            qc_report[source_id].mean_nt_quality[j] += (int) qc_batch_p->read_p->quality[index];
            qc_report[source_id].nt_counter[j]++;
        }

        // calculation of the index offset, only dependant on the order of the read [i]
        int index_offset = init_pos + qc_batch_p->read_p->data_indices[i] - 1;

        for (int j = init_pos; j < end_pos; j++) {
            index = (j * INT_COUNTERS_SIZE_IN_MEMORY) + (qc_batch_p->read_p->seq[index_offset++] & 7);

            if (status_batch_p->read_status[i] == INVALID_READ) {
                qc_batch_p->gpu_nt_type_invalid_counter_p[index]++;
            } else {
                qc_batch_p->gpu_nt_type_valid_counter_p[index - init_pos]++;
            }
        }
    }
}
示例#19
0
void ConflateCaseTestSuite::_loadDir(QString dir, QStringList confs)
{
  if (dir.endsWith(".off"))
  {
    return;
  }
  QDir d(dir);

  QFileInfo fi(d.absoluteFilePath("Config.conf"));

  if (fi.exists())
  {
    confs.append(fi.absoluteFilePath());
  }

  // a list of strings paths to ignore if this string is found in the path.
  QStringList ignoreList;

# ifndef HOOT_HAVE_RND
    ignoreList << "hoot-rnd";
# endif
# ifndef HOOT_HAVE_SERVICES
    ignoreList << "hoot-services";
# endif
# ifndef HOOT_HAVE_NODEJS
    ignoreList << "hoot-js";
# endif

  QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
  for (int i = 0; i < dirs.size(); i++)
  {
    QString path = d.absoluteFilePath(dirs[i]);

    bool ignore = false;

    for (int i = 0; i < ignoreList.size(); i++)
    {
      if (path.contains(ignoreList[i]))
      {
        ignore = true;
      }
    }

    if (ignore)
    {
      LOG_WARN("Disabling: " + path);
    }
    else
    {
      _loadDir(path, confs);
    }
  }

  if (dirs.size() > 0)
  {
    // this is entirely a preference thing. I want people to keep the tests clean and uncluttered.
    if (QFileInfo(d, "Input1.osm").exists() ||
        QFileInfo(d, "Input2.osm").exists() ||
        QFileInfo(d, "Output.osm").exists())
    {
      throw HootException("Please put conflate test cases in a directory w/o sub directories.");
    }
  }
  else
  {
    addTest(new ConflateCaseTest(d, confs));
  }
}
示例#20
0
    void LightingPass::CreateLightBufferData(const std::vector<Light *> & lights)
    {
        m_pointLights.clear();
        m_directionalLights.clear();

        for (auto light : lights)
        {
            unsigned int dindex = m_directionalLights.size();
            unsigned int pindex = m_pointLights.size();

            switch(light->GetLightType())
            {
            case LightType::DIRECTIONAL:
                m_directionalLights.push_back(DirectionalLight());

                m_directionalLights[dindex].direction = Vector4(light->GetLightDirection(), 1.f);

                m_directionalLights[dindex].ambient = light->GetAmbientLight();
                m_directionalLights[dindex].diffuse = light->GetDiffuseLight();
                m_directionalLights[dindex].specular = light->GetSpecularLight();
                break;

            case LightType::POINT:
                m_pointLights.push_back(PointLight());

                //LOG_ERR(light->GetAttenuationConstant(), ", ", light->GetAttenuationLinear(), ", ", light->GetAttenuationQuadratic());

                m_pointLights[pindex].position = Vector4(light->worldTransform.Position(), 1.f);

                m_pointLights[pindex].ambient = light->GetAmbientLight();
                m_pointLights[pindex].diffuse = light->GetDiffuseLight();
                m_pointLights[pindex].specular = light->GetSpecularLight();

                m_pointLights[pindex].constant = light->GetAttenuationConstant();
                m_pointLights[pindex].linear = light->GetAttenuationLinear();
                m_pointLights[pindex].quadratic = light->GetAttenuationQuadratic();
                break;

            default:
                LOG_WARN("Unknown light type, unable to render: ", light->GetLightType());
                break;
            }
        }

        // XXX hack
        // make sure at least 2 point lights exist, and 1 directional light
        switch (m_directionalLights.size())
        {
        case 0:
            m_directionalLights.push_back(DirectionalLight());
            break;
        }

        switch (m_pointLights.size())
        {
        case 1:
            m_pointLights.push_back(PointLight());
            
            m_pointLights[m_pointLights.size() - 1].constant = 1.f;
            m_pointLights[m_pointLights.size() - 1].linear = 0.045f;
            m_pointLights[m_pointLights.size() - 1].quadratic = 0.0075f;

            break;

        case 0:
            for (int i = 0; i < 2; i++)
            {
                m_pointLights.push_back(PointLight());
            }
            break;
        }
    }
    void
    writeClusters(size_t n,
                  uint32_t pattern,
                  ClusterLocation *loc,
                  int retries = 7)
    {
	const uint64_t bufsz = dStore_->getClusterSize() * n;
	std::vector<uint8_t> buf(bufsz);
	uint64_t off;
	uint32_t *p;

	for (p = (uint32_t *) &buf[0], off = 0; off < bufsz;
             off += sizeof(*p), ++p)
            *p = pattern;

        size_t wsize = 0;
        for (size_t i = 0; i < n; i += wsize)
        {
            wsize = std::min(dStore_->getRemainingSCOCapacity(),
                             static_cast<ssize_t>(n - i));
            ASSERT_LT(0U,
                      wsize);

            int tries = retries;
            while (true)
            {
                try
                {
                    uint32_t dummy1;
                    std::vector<ClusterLocation> locs(wsize);
                    std::unique_ptr<CheckSum> cs;

                    dStore_->writeClusters(&buf[i],
                                           locs,
                                           locs.size(),
                                           dummy1);

                    ASSERT_LE(0,
                              dStore_->getRemainingSCOCapacity());

                    if (dStore_->getRemainingSCOCapacity() == 0)
                    {
                        dStore_->finalizeCurrentSCO();
                    }

                    for (size_t j = 0; j < locs.size(); ++j)
                    {
                        *(loc + i + j) = locs[j];
                    }
                }
                catch (TransientException &)
                {
                    LOG_WARN("backend congestion detected, retrying");
                    if (--tries < 0)
                        throw;
                    sleep(1);
                    continue;
                }
                break;
            }
        }
    }
示例#22
0
/**
 * Runs an update process as the service using the SYSTEM account.
 *
 * @param  argc           The number of arguments in argv
 * @param  argv           The arguments normally passed to updater.exe
 *                        argv[0] must be the path to updater.exe
 * @param  processStarted Set to TRUE if the process was started.
 * @return TRUE if the update process was run had a return code of 0.
 */
BOOL
StartUpdateProcess(int argc,
                   LPWSTR *argv,
                   LPCWSTR installDir,
                   BOOL &processStarted)
{
  LOG(("Starting update process as the service in session 0."));
  STARTUPINFO si = {0};
  si.cb = sizeof(STARTUPINFO);
  si.lpDesktop = L"winsta0\\Default";
  PROCESS_INFORMATION pi = {0};

  // The updater command line is of the form:
  // updater.exe update-dir apply [wait-pid [callback-dir callback-path args]]
  LPWSTR cmdLine = MakeCommandLine(argc, argv);

  // If we're about to start the update process from session 0,
  // then we should not show a GUI.  This only really needs to be done
  // on Vista and higher, but it's better to keep everything consistent
  // across all OS if it's of no harm.
  if (argc >= 2 ) {
    // Setting the desktop to blank will ensure no GUI is displayed
    si.lpDesktop = L"";
    si.dwFlags |= STARTF_USESHOWWINDOW;
    si.wShowWindow = SW_HIDE;
  }

  // We move the updater.ini file out of the way because we will handle 
  // executing PostUpdate through the service.  We handle PostUpdate from
  // the service because there are some per user things that happen that
  // can't run in session 0 which we run updater.exe in.
  // Once we are done running updater.exe we rename updater.ini back so
  // that if there were any errors the next updater.exe will run correctly.
  WCHAR updaterINI[MAX_PATH + 1];
  WCHAR updaterINITemp[MAX_PATH + 1];
  BOOL selfHandlePostUpdate = FALSE;
  // We use the updater.ini from the same directory as the updater.exe
  // because of background updates.
  if (PathGetSiblingFilePath(updaterINI, argv[0], L"updater.ini") &&
      PathGetSiblingFilePath(updaterINITemp, argv[0], L"updater.tmp")) {
    selfHandlePostUpdate = MoveFileExW(updaterINI, updaterINITemp, 
                                       MOVEFILE_REPLACE_EXISTING);
  }

  // Add an env var for MOZ_USING_SERVICE so the updater.exe can
  // do anything special that it needs to do for service updates.
  // Search in updater.cpp for more info on MOZ_USING_SERVICE.
  putenv(const_cast<char*>("MOZ_USING_SERVICE=1"));
  LOG(("Starting service with cmdline: %ls", cmdLine));
  processStarted = CreateProcessW(argv[0], cmdLine, 
                                  nullptr, nullptr, FALSE, 
                                  CREATE_DEFAULT_ERROR_MODE, 
                                  nullptr, 
                                  nullptr, &si, &pi);
  // Empty value on putenv is how you remove an env variable in Windows
  putenv(const_cast<char*>("MOZ_USING_SERVICE="));
  
  BOOL updateWasSuccessful = FALSE;
  if (processStarted) {
    // Wait for the updater process to finish
    LOG(("Process was started... waiting on result."));
    DWORD waitRes = WaitForSingleObject(pi.hProcess, TIME_TO_WAIT_ON_UPDATER);
    if (WAIT_TIMEOUT == waitRes) {
      // We waited a long period of time for updater.exe and it never finished
      // so kill it.
      TerminateProcess(pi.hProcess, 1);
    } else {
      // Check the return code of updater.exe to make sure we get 0
      DWORD returnCode;
      if (GetExitCodeProcess(pi.hProcess, &returnCode)) {
        LOG(("Process finished with return code %d.", returnCode));
        // updater returns 0 if successful.
        updateWasSuccessful = (returnCode == 0);
      } else {
        LOG_WARN(("Process finished but could not obtain return code."));
      }
    }
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);

    // Check just in case updater.exe didn't change the status from
    // applying.  If this is the case we report an error.
    BOOL isApplying = FALSE;
    if (IsStatusApplying(argv[1], isApplying) && isApplying) {
      if (updateWasSuccessful) {
        LOG(("update.status is still applying even know update "
             " was successful."));
        if (!WriteStatusFailure(argv[1], 
                                SERVICE_STILL_APPLYING_ON_SUCCESS)) {
          LOG_WARN(("Could not write update.status still applying on"
                    " success error."));
        }
        // Since we still had applying we know updater.exe didn't do its
        // job correctly.
        updateWasSuccessful = FALSE;
      } else {
        LOG_WARN(("update.status is still applying and update was not successful."));
        if (!WriteStatusFailure(argv[1], 
                                SERVICE_STILL_APPLYING_ON_FAILURE)) {
          LOG_WARN(("Could not write update.status still applying on"
                    " success error."));
        }
      }
    }
  } else {
    DWORD lastError = GetLastError();
    LOG_WARN(("Could not create process as current user, "
              "updaterPath: %ls; cmdLine: %ls.  (%d)",
              argv[0], cmdLine, lastError));
  }

  // Now that we're done with the update, restore back the updater.ini file
  // We use it ourselves, and also we want it back in case we had any type 
  // of error so that the normal update process can use it.
  if (selfHandlePostUpdate) {
    MoveFileExW(updaterINITemp, updaterINI, MOVEFILE_REPLACE_EXISTING);

    // Only run the PostUpdate if the update was successful
    if (updateWasSuccessful && argc > 2) {
      LPCWSTR updateInfoDir = argv[1];
      bool backgroundUpdate = IsUpdateBeingStaged(argc, argv);

      // Launch the PostProcess with admin access in session 0.  This is
      // actually launching the post update process but it takes in the 
      // callback app path to figure out where to apply to.
      // The PostUpdate process with user only access will be done inside
      // the unelevated updater.exe after the update process is complete
      // from the service.  We don't know here which session to start
      // the user PostUpdate process from.
      // Note that we don't need to do this if we're just staging the
      // update in the background, as the PostUpdate step runs when
      // performing the replacing in that case.
      if (!backgroundUpdate) {
        LOG(("Launching post update process as the service in session 0."));
        if (!LaunchWinPostProcess(installDir, updateInfoDir, true, nullptr)) {
          LOG_WARN(("The post update process could not be launched."
                    " installDir: %ls, updateInfoDir: %ls",
                    installDir, updateInfoDir));
        }
      }
    }
  }

  free(cmdLine);
  return updateWasSuccessful;
}
示例#23
0
  //
  // HandleEvent
  //
  // Pass any events to the registered handler
  //
  U32 Login::HandleEvent(Event &e)
  {
    if (e.type == IFace::EventID())
    {
      switch (e.subType)
      {
        case IFace::NOTIFY:
        {
          switch (e.iface.p1)
          {
            case LoginMsg::Select:
              return (TRUE);

            case LoginMsg::Login:
            {
              // Get the selected user
              if (const User::ExistingUser *e = User::Find(user->GetStringValue()))
              {
                // Login the selected user
                if (User::Login(e))
                {
                  User::SampleStatCount("Logins");
                  SendNotify(this, LoginNotify::LoggedIn);
                }
              }

              return (TRUE);
            }

            case LoginMsg::Create:
            {
              // Get the name of the new user
              const char *userName = newUser->GetStringValue();

              // Filter empty strings and existing users
              if ((*userName != '\0') && !User::Find(userName))
              {
                // Create the new user
                if (User::Create(userName))
                {
                  // Build the user list
                  BuildUserList();
                }
                else
                {
                  LOG_WARN(("Creation of user [%s] failed", userName));
                }
              }

              return (TRUE);
            }

            case LoginMsg::Delete:
            {
              // Attempt to delete the user
              if (User::Delete(user->GetStringValue()))
              {
                // Rebuild the list
                BuildUserList();
              }

              return (TRUE);
            }
          }

          break;
        }
      }
    }

    return (ICWindow::HandleEvent(e));  
  }
示例#24
0
/**
 * Processes a software update command
 *
 * @param  argc           The number of arguments in argv
 * @param  argv           The arguments normally passed to updater.exe
 *                        argv[0] must be the path to updater.exe
 * @return TRUE if the update was successful.
 */
BOOL
ProcessSoftwareUpdateCommand(DWORD argc, LPWSTR *argv)
{
  BOOL result = TRUE;
  if (argc < 3) {
    LOG_WARN(("Not enough command line parameters specified. "
              "Updating update.status."));

    // We can only update update.status if argv[1] exists.  argv[1] is
    // the directory where the update.status file exists.
    if (argc < 2 || 
        !WriteStatusFailure(argv[1], 
                            SERVICE_NOT_ENOUGH_COMMAND_LINE_ARGS)) {
      LOG_WARN(("Could not write update.status service update failure.  (%d)",
                GetLastError()));
    }
    return FALSE;
  }

  WCHAR installDir[MAX_PATH + 1] = {L'\0'};
  if (!GetInstallationDir(argc, argv, installDir)) {
    LOG_WARN(("Could not get the installation directory"));
    if (!WriteStatusFailure(argv[1],
                            SERVICE_INSTALLDIR_ERROR)) {
      LOG_WARN(("Could not write update.status for GetInstallationDir failure."));
    }
    return FALSE;
  }

  // Make sure the path to the updater to use for the update is local.
  // We do this check to make sure that file locking is available for
  // race condition security checks.
  BOOL isLocal = FALSE;
  if (!IsLocalFile(argv[0], isLocal) || !isLocal) {
    LOG_WARN(("Filesystem in path %ls is not supported (%d)",
              argv[0], GetLastError()));
    if (!WriteStatusFailure(argv[1], 
                            SERVICE_UPDATER_NOT_FIXED_DRIVE)) {
      LOG_WARN(("Could not write update.status service update failure.  (%d)",
                GetLastError()));
    }
    return FALSE;
  }

  nsAutoHandle noWriteLock(CreateFileW(argv[0], GENERIC_READ, FILE_SHARE_READ, 
                                       nullptr, OPEN_EXISTING, 0, nullptr));
  if (INVALID_HANDLE_VALUE == noWriteLock) {
      LOG_WARN(("Could not set no write sharing access on file.  (%d)",
                GetLastError()));
    if (!WriteStatusFailure(argv[1], 
                            SERVICE_COULD_NOT_LOCK_UPDATER)) {
      LOG_WARN(("Could not write update.status service update failure.  (%d)",
                GetLastError()));
    }
    return FALSE;
  }

  // Verify that the updater.exe that we are executing is the same
  // as the one in the installation directory which we are updating.
  // The installation dir that we are installing to is installDir.
  WCHAR installDirUpdater[MAX_PATH + 1] = { L'\0' };
  wcsncpy(installDirUpdater, installDir, MAX_PATH);
  if (!PathAppendSafe(installDirUpdater, L"updater.exe")) {
    LOG_WARN(("Install directory updater could not be determined."));
    result = FALSE;
  }

  BOOL updaterIsCorrect;
  if (result && !VerifySameFiles(argv[0], installDirUpdater, 
                                 updaterIsCorrect)) {
    LOG_WARN(("Error checking if the updaters are the same.\n"
              "Path 1: %ls\nPath 2: %ls", argv[0], installDirUpdater));
    result = FALSE;
  }

  if (result && !updaterIsCorrect) {
    LOG_WARN(("The updaters do not match, updater will not run.")); 
    result = FALSE;
  }

  if (result) {
    LOG(("updater.exe was compared successfully to the installation directory"
         " updater.exe."));
  } else {
    if (!WriteStatusFailure(argv[1], 
                            SERVICE_UPDATER_COMPARE_ERROR)) {
      LOG_WARN(("Could not write update.status updater compare failure."));
    }
    return FALSE;
  }

  // Check to make sure the updater.exe module has the unique updater identity.
  // This is a security measure to make sure that the signed executable that
  // we will run is actually an updater.
  HMODULE updaterModule = LoadLibraryEx(argv[0], nullptr, 
                                        LOAD_LIBRARY_AS_DATAFILE);
  if (!updaterModule) {
    LOG_WARN(("updater.exe module could not be loaded. (%d)", GetLastError()));
    result = FALSE;
  } else {
    char updaterIdentity[64];
    if (!LoadStringA(updaterModule, IDS_UPDATER_IDENTITY, 
                     updaterIdentity, sizeof(updaterIdentity))) {
      LOG_WARN(("The updater.exe application does not contain the Mozilla"
                " updater identity."));
      result = FALSE;
    }

    if (strcmp(updaterIdentity, UPDATER_IDENTITY_STRING)) {
      LOG_WARN(("The updater.exe identity string is not valid."));
      result = FALSE;
    }
    FreeLibrary(updaterModule);
  }

  if (result) {
    LOG(("The updater.exe application contains the Mozilla"
          " updater identity."));
  } else {
    if (!WriteStatusFailure(argv[1], 
                            SERVICE_UPDATER_IDENTITY_ERROR)) {
      LOG_WARN(("Could not write update.status no updater identity."));
    }
    return TRUE;
  }

  // Check for updater.exe sign problems
  BOOL updaterSignProblem = FALSE;
#ifndef DISABLE_UPDATER_AUTHENTICODE_CHECK
  updaterSignProblem = !DoesBinaryMatchAllowedCertificates(installDir,
                                                           argv[0]);
#endif

  // Only proceed with the update if we have no signing problems
  if (!updaterSignProblem) {
    BOOL updateProcessWasStarted = FALSE;
    if (StartUpdateProcess(argc, argv, installDir,
                           updateProcessWasStarted)) {
      LOG(("updater.exe was launched and run successfully!"));
      LogFlush();

      // Don't attempt to update the service when the update is being staged.
      if (!IsUpdateBeingStaged(argc, argv)) {
        // We might not execute code after StartServiceUpdate because
        // the service installer will stop the service if it is running.
        StartServiceUpdate(installDir);
      }
    } else {
      result = FALSE;
      LOG_WARN(("Error running update process. Updating update.status  (%d)",
                GetLastError()));
      LogFlush();

      // If the update process was started, then updater.exe is responsible for
      // setting the failure code.  If it could not be started then we do the 
      // work.  We set an error instead of directly setting status pending 
      // so that the app.update.service.errors pref can be updated when 
      // the callback app restarts.
      if (!updateProcessWasStarted) {
        if (!WriteStatusFailure(argv[1], 
                                SERVICE_UPDATER_COULD_NOT_BE_STARTED)) {
          LOG_WARN(("Could not write update.status service update failure.  (%d)",
                    GetLastError()));
        }
      }
    }
  } else {
    result = FALSE;
    LOG_WARN(("Could not start process due to certificate check error on "
              "updater.exe. Updating update.status.  (%d)", GetLastError()));

    // When there is a certificate check error on the updater.exe application,
    // we want to write out the error.
    if (!WriteStatusFailure(argv[1], 
                            SERVICE_UPDATER_SIGN_ERROR)) {
      LOG_WARN(("Could not write pending state to update.status.  (%d)",
                GetLastError()));
    }
  }

  return result;
}
示例#25
0
static int pa_device_id(const char *device) {
	int len = strlen(device);
	int i;

	if (!strncmp(device, "default", 7)) {
#ifndef PA18API
		return Pa_GetDefaultOutputDevice();
#else
		return Pa_GetDefaultOutputDeviceID();
#endif
	}
	if (len >= 1 && len <= 2 && device[0] >= '0' && device[0] <= '9') {
		return atoi(device);
	}

#ifndef PA18API
#define DEVICE_ID_MAXLEN 256
	for (i = 0; i < Pa_GetDeviceCount(); ++i) {
		char tmp[DEVICE_ID_MAXLEN];
		snprintf(tmp, DEVICE_ID_MAXLEN, "%s [%s]", Pa_GetDeviceInfo(i)->name, Pa_GetHostApiInfo(Pa_GetDeviceInfo(i)->hostApi)->name);
		if (!strncmp(tmp, device, len)) {
#else
	for (i = 0; i < Pa_CountDevices(); ++i) {
		if (!strncmp(Pa_GetDeviceInfo(i)->name, device, len)) {
#endif
			return i;
		}
	}

	return -1;
}

#ifndef PA18API
static int pa_callback(const void *pa_input, void *pa_output, unsigned long pa_frames_wanted, 
					   const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags, void *userData);

#else
static int pa_callback(void *pa_input, void *pa_output, unsigned long pa_frames_wanted, 
			   PaTimestamp outTime, void *userData);
#endif
bool test_open(const char *device, unsigned rates[]) {
	PaStreamParameters outputParameters;
	PaError err;
	unsigned ref[] TEST_RATES;
	int device_id, i, ind;

	if ((device_id = pa_device_id(device)) == -1) {
		LOG_INFO("device %s not found", device);
		return false;
	}

	outputParameters.device = device_id;
	outputParameters.channelCount = 2;
	outputParameters.sampleFormat = paInt32;
#ifndef PA18API
	outputParameters.suggestedLatency =
		output.latency ? (double)output.latency/(double)1000 : Pa_GetDeviceInfo(outputParameters.device)->defaultHighOutputLatency;
	outputParameters.hostApiSpecificStreamInfo = NULL;
#endif

	// check supported sample rates
	// Note use Pa_OpenStream as it appears more reliable than Pa_IsFormatSupported on some windows apis
	for (i = 0, ind = 0; ref[i]; ++i) {
#ifndef PA18API
		err = Pa_OpenStream(&pa.stream, NULL, &outputParameters, (double)ref[i], paFramesPerBufferUnspecified, paNoFlag, 
							pa_callback, NULL);
#else
		err = Pa_OpenStream(&pa.stream, paNoDevice, 0, 0, NULL, outputParameters.device,
			outputParameters.channelCount, outputParameters.sampleFormat, NULL, (double)ref[i],
			paFramesPerBuffer, paNumberOfBuffers, paNoFlag, pa_callback, NULL);
#endif
		if (err == paNoError) {
			Pa_CloseStream(pa.stream);
			rates[ind++] = ref[i];
		}
	}

	if (!rates[0]) {
		LOG_WARN("no available rate found");
		return false;
	}

	pa.stream = NULL;
	return true;
}

static void pa_stream_finished(void *userdata) {
	if (running) {
		LOG_INFO("stream finished");
		LOCK;
		output.pa_reopen = true;
		wake_controller();
		UNLOCK;
	}
}

static thread_type monitor_thread;
bool monitor_thread_running = false;

static void *pa_monitor() {
	bool output_off;

	LOCK;

	if (monitor_thread_running) {
		LOG_DEBUG("monitor thread already running");
		UNLOCK;
		return 0;
	}

	LOG_DEBUG("start monitor thread");

	monitor_thread_running = true;
	output_off = (output.state == OUTPUT_OFF);

	while (monitor_thread_running) {
		if (output_off) {
			if (output.state != OUTPUT_OFF) {
				LOG_INFO("output on");
				break;
			}
		} else {
			// this is a hack to partially support hot plugging of devices
			// we rely on terminating and reinitalising PA to get an updated list of devices and use name for output.device
			LOG_INFO("probing device %s", output.device);
			Pa_Terminate();
			Pa_Initialize();
			pa.stream = NULL;
			if (pa_device_id(output.device) != -1) {
				LOG_INFO("device reopen");
				break;
			}
		}

		UNLOCK;
		sleep(output_off ? 1 : 5);
		LOCK;
	}

	LOG_DEBUG("end monitor thread");

	monitor_thread_running = false;
	pa.stream = NULL;

	_pa_open();

	UNLOCK;

	return 0;
}
示例#26
0
/**
 * Executes a service command.
 *
 * @param argc The number of arguments in argv
 * @param argv The service command line arguments, argv[0] and argv[1]
 *             and automatically included by Windows.  argv[2] is the
 *             service command.
 *             
 * @return FALSE if there was an error executing the service command.
 */
BOOL
ExecuteServiceCommand(int argc, LPWSTR *argv)
{
  if (argc < 3) {
    LOG_WARN(("Not enough command line arguments to execute a service command"));
    return FALSE;
  }

  // The tests work by making sure the log has changed, so we put a 
  // unique ID in the log.
  RPC_WSTR guidString = RPC_WSTR(L"");
  GUID guid;
  HRESULT hr = CoCreateGuid(&guid);
  if (SUCCEEDED(hr)) {
    UuidToString(&guid, &guidString);
  }
  LOG(("Executing service command %ls, ID: %ls",
       argv[2], reinterpret_cast<LPCWSTR>(guidString)));
  RpcStringFree(&guidString);

  BOOL result = FALSE;
  if (!lstrcmpi(argv[2], L"software-update")) {

    // Use the passed in command line arguments for the update, except for the
    // path to updater.exe.  We copy updater.exe to a the directory of the
    // MozillaMaintenance service so that a low integrity process cannot
    // replace the updater.exe at any point and use that for the update.
    // It also makes DLL injection attacks harder.
    LPWSTR oldUpdaterPath = argv[3];
    WCHAR secureUpdaterPath[MAX_PATH + 1] = { L'\0' };
    result = GetSecureUpdaterPath(secureUpdaterPath); // Does its own logging
    if (result) {
      LOG(("Passed in path: '%ls'; Using this path for updating: '%ls'.",
           oldUpdaterPath, secureUpdaterPath));
      DeleteSecureUpdater(secureUpdaterPath);
      result = CopyFileW(oldUpdaterPath, secureUpdaterPath, FALSE);
    }

    if (!result) {
      LOG_WARN(("Could not copy path to secure location.  (%d)",
                GetLastError()));
      if (argc > 4 && !WriteStatusFailure(argv[4],
                                          SERVICE_COULD_NOT_COPY_UPDATER)) {
        LOG_WARN(("Could not write update.status could not copy updater error"));
      }
    } else {

      // We obtained the path and copied it successfully, update the path to
      // use for the service update.
      argv[3] = secureUpdaterPath;

      WCHAR oldUpdaterINIPath[MAX_PATH + 1] = { L'\0' };
      WCHAR secureUpdaterINIPath[MAX_PATH + 1] = { L'\0' };
      if (PathGetSiblingFilePath(secureUpdaterINIPath, secureUpdaterPath,
                                 L"updater.ini") &&
          PathGetSiblingFilePath(oldUpdaterINIPath, oldUpdaterPath,
                                 L"updater.ini")) {
        // This is non fatal if it fails there is no real harm
        if (!CopyFileW(oldUpdaterINIPath, secureUpdaterINIPath, FALSE)) {
          LOG_WARN(("Could not copy updater.ini from: '%ls' to '%ls'.  (%d)",
                    oldUpdaterINIPath, secureUpdaterINIPath, GetLastError()));
        }
      }

      result = ProcessSoftwareUpdateCommand(argc - 3, argv + 3);
      DeleteSecureUpdater(secureUpdaterPath);
    }

    // We might not reach here if the service install succeeded
    // because the service self updates itself and the service
    // installer will stop the service.
    LOG(("Service command %ls complete.", argv[2]));
  } else {
    LOG_WARN(("Service command not recognized: %ls.", argv[2]));
    // result is already set to FALSE
  }

  LOG(("service command %ls complete with result: %ls.",
       argv[1], (result ? L"Success" : L"Failure")));
  return TRUE;
}
template <  typename IN_PORT_TYPE, typename OUT_PORT_TYPE > int stream_to_vector_ii_base::_forecastAndProcess( bool &eos, typename  std::vector< gr_istream< IN_PORT_TYPE > > &istreams ,
                                 typename  std::vector< gr_ostream< OUT_PORT_TYPE > > &ostreams  )
{
    typedef typename std::vector< gr_istream< IN_PORT_TYPE > >   _IStreamList;
    typedef typename std::vector< gr_ostream< OUT_PORT_TYPE > >  _OStreamList;

    typename _OStreamList::iterator ostream;
    typename _IStreamList::iterator istream = istreams.begin();
    int nout = 0;
    bool dataReady = false;
    if ( !eos ) {
        uint64_t max_items_avail = 0;
        for ( int idx=0 ; istream != istreams.end() && serviceThread->threadRunning() ; idx++, istream++ ) {
            LOG_TRACE( stream_to_vector_ii_base, "GET MAX ITEMS: STREAM:"<< idx << " NITEMS/SCALARS:" << 
                       istream->nitems() << "/" << istream->_data.size() );
            max_items_avail = std::max( istream->nitems(), max_items_avail );
        }

        if ( max_items_avail == 0  ) {
            LOG_TRACE( stream_to_vector_ii_base, "DATA CHECK - MAX ITEMS  NOUTPUT/MAX_ITEMS:" <<   noutput_items << "/" << max_items_avail);
            return -1;
        }

        //
        // calc number of output elements based on input items available
        //
        noutput_items = 0;
        if ( !gr_sptr->fixed_rate() )  {
            noutput_items = round_down((int32_t) (max_items_avail * gr_sptr->relative_rate()), gr_sptr->output_multiple());
            LOG_TRACE( stream_to_vector_ii_base, " VARIABLE FORECAST NOUTPUT == " << noutput_items );
        } else {
            istream = istreams.begin();
            for ( int i=0; istream != istreams.end(); i++, istream++ ) {
                int t_noutput_items = gr_sptr->fixed_rate_ninput_to_noutput( istream->nitems() );
                if ( gr_sptr->output_multiple_set() ) {
                    t_noutput_items = round_up(t_noutput_items, gr_sptr->output_multiple());
                }
                if ( t_noutput_items > 0 ) {
                    if ( noutput_items == 0 ) {
                        noutput_items = t_noutput_items;
                    }
                    if ( t_noutput_items <= noutput_items ) {
                        noutput_items = t_noutput_items;
                    }
                }
            }
            LOG_TRACE( stream_to_vector_ii_base,  " FIXED FORECAST NOUTPUT/output_multiple == " << 
                        noutput_items  << "/" << gr_sptr->output_multiple());
        }

        //
        // ask the block how much input they need to produce noutput_items...
        // if enough data is available to process then set the dataReady flag
        //
        int32_t  outMultiple = gr_sptr->output_multiple();
        while ( !dataReady && noutput_items >= outMultiple  ) {
            //
            // ask the block how much input they need to produce noutput_items...
            //
            gr_sptr->forecast(noutput_items, _ninput_items_required);

            LOG_TRACE( stream_to_vector_ii_base, "--> FORECAST IN/OUT " << _ninput_items_required[0]  << "/" << noutput_items  );

            istream = istreams.begin();
            uint32_t dr_cnt=0;
            for ( int idx=0 ; noutput_items > 0 && istream != istreams.end(); idx++, istream++ ) {
                // check if buffer has enough elements
                _input_ready[idx] = false;
                if ( istream->nitems() >= (uint64_t)_ninput_items_required[idx] ) {
                    _input_ready[idx] = true;
                    dr_cnt++;
                }
                LOG_TRACE( stream_to_vector_ii_base, "ISTREAM DATACHECK NELMS/NITEMS/REQ/READY:" <<   istream->nelems() << 
                          "/" << istream->nitems() << "/" << _ninput_items_required[idx] << "/" << _input_ready[idx]);
            }
    
            if ( dr_cnt < istreams.size() ) {
                if ( outMultiple > 1 ) {
                    noutput_items -= outMultiple;
                } else {
                    noutput_items /= 2;
                }
            } else {
                dataReady = true;
            }
            LOG_TRACE( stream_to_vector_ii_base, " TRIM FORECAST NOUTPUT/READY " << noutput_items << "/" << dataReady );
        }

        // check if data is ready...
        if ( !dataReady ) {
            LOG_TRACE( stream_to_vector_ii_base, "DATA CHECK - NOT ENOUGH DATA  AVAIL/REQ:" <<   _istreams[0].nitems() << 
                      "/" << _ninput_items_required[0] );
            return -1;
        }

        // reset looping variables
        int  ritems = 0;
        int  nitems = 0;

        // reset caching vectors
        _output_items.clear();
        _input_items.clear();
        _ninput_items.clear();
        istream = istreams.begin();

        for ( int idx=0 ; istream != istreams.end(); idx++, istream++ ) {
            // check if the stream is ready
            if ( !_input_ready[idx] ) {
                continue;
            }
            // get number of items remaining
            try {
                ritems = gr_sptr->nitems_read( idx );
            } catch(...){
                // something bad has happened, we are missing an input stream
                LOG_ERROR( stream_to_vector_ii_base, "MISSING INPUT STREAM FOR GR BLOCK, STREAM ID:" <<   istream->streamID );
                return -2;
            } 
    
            nitems = istream->nitems() - ritems;
            LOG_TRACE( stream_to_vector_ii_base,  " ISTREAM: IDX:" << idx  << " ITEMS AVAIL/READ/REQ " << nitems << "/" 
                       << ritems << "/" << _ninput_items_required[idx] );
            if ( nitems >= _ninput_items_required[idx] && nitems > 0 ) {
                //remove eos checks ...if ( nitems < _ninput_items_required[idx] ) nitems=0;
                _ninput_items.push_back( nitems );
                _input_items.push_back( (const void *) (istream->read_pointer(ritems)) );
            }
        }

        //
        // setup output buffer vector based on noutput..
        //
        ostream = ostreams.begin();
        for( ; ostream != ostreams.end(); ostream++ ) {
            ostream->resize(noutput_items);
            _output_items.push_back((void*)(ostream->write_pointer()) );
        }

        nout=0;
        if ( _input_items.size() != 0 && serviceThread->threadRunning() ) {
            LOG_TRACE( stream_to_vector_ii_base, " CALLING WORK.....N_OUT:" << noutput_items << " N_IN:" << nitems 
                      << " ISTREAMS:" << _input_items.size() << " OSTREAMS:" << _output_items.size());
            nout = gr_sptr->general_work( noutput_items, _ninput_items, _input_items, _output_items);
            LOG_TRACE( stream_to_vector_ii_base, "RETURN  WORK ..... N_OUT:" << nout);
        }

        // check for stop condition from work method
        if ( nout < gr_block::WORK_DONE ) {
            LOG_WARN( stream_to_vector_ii_base, "WORK RETURNED STOP CONDITION..." << nout );
            nout=0;
            eos = true;
        }
    }

    if (nout != 0 or eos ) {
        noutput_items = nout;
        LOG_TRACE( stream_to_vector_ii_base, " WORK RETURNED: NOUT : " << nout << " EOS:" << eos);
        ostream = ostreams.begin();
        typename IN_PORT_TYPE::dataTransfer *pkt=NULL;
        for ( int idx=0 ; ostream != ostreams.end(); idx++, ostream++ ) {

            pkt=NULL;
            int inputIdx = idx;
            if ( (size_t)(inputIdx) >= istreams.size() ) {
                for ( inputIdx= istreams.size()-1; inputIdx > -1; inputIdx--) {
                    if ( istreams[inputIdx].pkt != NULL ) {
                        pkt = istreams[inputIdx].pkt;
                        break;
                    }
                }
            } else {
                pkt = istreams[inputIdx].pkt;
            }

            LOG_TRACE( stream_to_vector_ii_base,  "PUSHING DATA   ITEMS/STREAM_ID " << ostream->nitems() << "/" << ostream->streamID );    
            if ( _maintainTimeStamp ) {

                // set time stamp for output samples based on input time stamp
                if ( ostream->nelems() == 0 )  {
#ifdef TEST_TIME_STAMP
      LOG_DEBUG( stream_to_vector_ii_base, "SEED - TS SRI:  xdelta:" << std::setprecision(12) << ostream->sri.xdelta );
      LOG_DEBUG( stream_to_vector_ii_base, "OSTREAM WRITE:   maint:" << _maintainTimeStamp );
      LOG_DEBUG( stream_to_vector_ii_base, "                  mode:" <<  ostream->tstamp.tcmode );
      LOG_DEBUG( stream_to_vector_ii_base, "                status:" <<  ostream->tstamp.tcstatus );
      LOG_DEBUG( stream_to_vector_ii_base, "                offset:" <<  ostream->tstamp.toff );
      LOG_DEBUG( stream_to_vector_ii_base, "                 whole:" <<  std::setprecision(10) << ostream->tstamp.twsec );
      LOG_DEBUG( stream_to_vector_ii_base, "SEED - TS         frac:" <<  std::setprecision(12) << ostream->tstamp.tfsec );
#endif
                    ostream->setTimeStamp( pkt->T, _maintainTimeStamp );
                }

                // write out samples, and set next time stamp based on xdelta and  noutput_items
                ostream->write ( noutput_items, eos );
            } else {
// use incoming packet's time stamp to forward
                if ( pkt ) {
#ifdef TEST_TIME_STAMP
      LOG_DEBUG( stream_to_vector_ii_base, "OSTREAM  SRI:  items/xdelta:" << noutput_items << "/" << std::setprecision(12) << ostream->sri.xdelta );
      LOG_DEBUG( stream_to_vector_ii_base, "PKT - TS         maint:" << _maintainTimeStamp );
      LOG_DEBUG( stream_to_vector_ii_base, "                  mode:" <<  pkt->T.tcmode );
      LOG_DEBUG( stream_to_vector_ii_base, "                status:" <<  pkt->T.tcstatus );
      LOG_DEBUG( stream_to_vector_ii_base, "                offset:" <<  pkt->T.toff );
      LOG_DEBUG( stream_to_vector_ii_base, "                 whole:" <<  std::setprecision(10) << pkt->T.twsec );
      LOG_DEBUG( stream_to_vector_ii_base, "PKT - TS          frac:" <<  std::setprecision(12) << pkt->T.tfsec );
#endif
                    ostream->write( noutput_items, eos, pkt->T  );
                } else {
#ifdef TEST_TIME_STAMP
      LOG_DEBUG( stream_to_vector_ii_base, "OSTREAM  SRI:  items/xdelta:" << noutput_items << "/" << std::setprecision(12) << ostream->sri.xdelta );
      LOG_DEBUG( stream_to_vector_ii_base, "OSTREAM TOD      maint:" << _maintainTimeStamp );
      LOG_DEBUG( stream_to_vector_ii_base, "                  mode:" <<  ostream->tstamp.tcmode );
      LOG_DEBUG( stream_to_vector_ii_base, "                status:" <<  ostream->tstamp.tcstatus );
      LOG_DEBUG( stream_to_vector_ii_base, "                offset:" <<  ostream->tstamp.toff );
      LOG_DEBUG( stream_to_vector_ii_base, "                 whole:" <<  std::setprecision(10) << ostream->tstamp.twsec );
      LOG_DEBUG( stream_to_vector_ii_base, "OSTREAM TOD       frac:" <<  std::setprecision(12) << ostream->tstamp.tfsec );
#endif
                    // use time of day as time stamp
                    ostream->write( noutput_items, eos,  _maintainTimeStamp );
                }
            }

        } // for ostreams
    }

    return nout;     
}
示例#28
0
void thread_mutex_lock_c(mutex_t *mutex, int line, char *file)
{
#ifdef DEBUG_MUTEXES
    thread_type *th = thread_self();

    if (!th) LOG_WARN("No mt record for %u in lock [%s:%d]", thread_self(), file, line);

    LOG_DEBUG5("Locking %p (%s) on line %d in file %s by thread %d", mutex, mutex->name, line, file, th ? th->thread_id : -1);

# ifdef CHECK_MUTEXES
    /* Just a little sanity checking to make sure that we're locking
    ** mutexes correctly
    */

    if (th) {
        int locks = 0;
        avl_node *node;
        mutex_t *tmutex;

        _mutex_lock(&_mutextree_mutex);

        node = avl_get_first (_mutextree);
        
        while (node) {
            tmutex = (mutex_t *)node->key;

            if (tmutex->mutex_id == mutex->mutex_id) {
                if (tmutex->thread_id == th->thread_id) { 
                    /* Deadlock, same thread can't lock the same mutex twice */
                    LOG_ERROR7("DEADLOCK AVOIDED (%d == %d) on mutex [%s] in file %s line %d by thread %d [%s]", 
                         tmutex->thread_id, th->thread_id, mutex->name ? mutex->name : "undefined", file, line, th->thread_id, th->name);

                    _mutex_unlock(&_mutextree_mutex);
                    return;
                }
            } else if (tmutex->thread_id == th->thread_id) { 
                /* Mutex locked by this thread (not this mutex) */
                locks++;
            }

            node = avl_get_next(node);
        }

        if (locks > 0) { 
            /* Has already got a mutex locked */
            if (_multi_mutex.thread_id != th->thread_id) {
                /* Tries to lock two mutexes, but has not got the double mutex, norty boy! */
                LOG_WARN("(%d != %d) Thread %d [%s] tries to lock a second mutex [%s] in file %s line %d, without locking double mutex!",
                     _multi_mutex.thread_id, th->thread_id, th->thread_id, th->name, mutex->name ? mutex->name : "undefined", file, line);
            }
        }
        
        _mutex_unlock(&_mutextree_mutex);
    }
# endif /* CHECK_MUTEXES */
    
    _mutex_lock(mutex);
    
    _mutex_lock(&_mutextree_mutex);

    LOG_DEBUG2("Locked %p by thread %d", mutex, th ? th->thread_id : -1);
    mutex->line = line;
    if (th) {
        mutex->thread_id = th->thread_id;
    }

    _mutex_unlock(&_mutextree_mutex);
#else
    _mutex_lock(mutex);
#endif /* DEBUG_MUTEXES */
}
template <  typename IN_PORT_TYPE > int tagged_file_sink_b_base::_forecastAndProcess( bool &eos, typename  std::vector< gr_istream< IN_PORT_TYPE > > &istreams )
{
    typedef typename std::vector< gr_istream< IN_PORT_TYPE > >   _IStreamList;

    typename _IStreamList::iterator istream = istreams.begin();
    int nout = 0;
    bool dataReady = false;
    if ( !eos ) {
        uint64_t max_items_avail = 0;
        for ( int idx=0 ; istream != istreams.end() && serviceThread->threadRunning() ; idx++, istream++ ) {
            LOG_TRACE( tagged_file_sink_b_base, "GET MAX ITEMS: STREAM:" << idx << " NITEMS/SCALARS:"
                      << istream->nitems() << "/" << istream->_data.size() );
            max_items_avail = std::max( istream->nitems(), max_items_avail );
        }

        //
        // calc number of output items to produce
        //
        noutput_items = (int) (max_items_avail * gr_sptr->relative_rate ());
        noutput_items = round_down (noutput_items, gr_sptr->output_multiple ());

        if ( noutput_items <= 0  ) {
           LOG_TRACE( tagged_file_sink_b_base, "DATA CHECK - MAX ITEMS  NOUTPUT/MAX_ITEMS:" <<   noutput_items << "/" << max_items_avail);
           return -1;
        }

        if ( gr_sptr->fixed_rate() ) {
            istream = istreams.begin();
            for ( int i=0; istream != istreams.end(); i++, istream++ ) {
                int t_noutput_items = gr_sptr->fixed_rate_ninput_to_noutput( istream->nitems() );
                if ( gr_sptr->output_multiple_set() ) {
                    t_noutput_items = round_up(t_noutput_items, gr_sptr->output_multiple());
                }
                if ( t_noutput_items > 0 ) {
                    if ( noutput_items == 0 ) {
                        noutput_items = t_noutput_items;
                    }
                    if ( t_noutput_items <= noutput_items ) {
                        noutput_items = t_noutput_items;
                    }
                }
            }
            LOG_TRACE( tagged_file_sink_b_base, " FIXED FORECAST NOUTPUT/output_multiple == " 
                      << noutput_items  << "/" << gr_sptr->output_multiple());
        }

        //
        // ask the block how much input they need to produce noutput_items...
        // if enough data is available to process then set the dataReady flag
        //
        int32_t  outMultiple = gr_sptr->output_multiple();
        while ( !dataReady && noutput_items >= outMultiple  ) {
            //
            // ask the block how much input they need to produce noutput_items...
            //
            gr_sptr->forecast(noutput_items, _ninput_items_required);

            LOG_TRACE( tagged_file_sink_b_base, "--> FORECAST IN/OUT " << _ninput_items_required[0]  << "/" << noutput_items  );

            istream = istreams.begin();
            uint32_t dr_cnt=0;
            for ( int idx=0 ; noutput_items > 0 && istream != istreams.end(); idx++, istream++ ) {
                // check if buffer has enough elements
                _input_ready[idx] = false;
                if ( istream->nitems() >= (uint64_t)_ninput_items_required[idx] ) {
                    _input_ready[idx] = true;
                    dr_cnt++;
                }
                LOG_TRACE( tagged_file_sink_b_base, "ISTREAM DATACHECK NELMS/NITEMS/REQ/READY:" << 
                          istream->nelems() << "/" << istream->nitems() << "/" << 
                          _ninput_items_required[idx] << "/" << _input_ready[idx]);
            }
    
            if ( dr_cnt < istreams.size() ) {
                if ( outMultiple > 1 ) {
                    noutput_items -= outMultiple;
                } else {
                    noutput_items /= 2;
                }
            } else {
                dataReady = true;
            }
            LOG_TRACE( tagged_file_sink_b_base, " TRIM FORECAST NOUTPUT/READY " << noutput_items << "/" << dataReady );
        }

        // check if data is ready...
        if ( !dataReady ) {
            LOG_TRACE( tagged_file_sink_b_base, "DATA CHECK - NOT ENOUGH DATA  AVAIL/REQ:" 
                      <<   _istreams[0].nitems() << "/" << _ninput_items_required[0] );
            return -1;
        }

        // reset looping variables
        int  ritems = 0;
        int  nitems = 0;

        // reset caching vectors
        _output_items.clear();
        _input_items.clear();
        _ninput_items.clear();
        istream = istreams.begin();

        for ( int idx=0 ; istream != istreams.end(); idx++, istream++ ) {
            // check if the stream is ready
            if ( !_input_ready[idx] ) continue;
      
            // get number of items remaining
            try {
                ritems = gr_sptr->nitems_read( idx );
            } catch(...){
                // something bad has happened, we are missing an input stream
                LOG_ERROR( tagged_file_sink_b_base, "MISSING INPUT STREAM FOR GR BLOCK, STREAM ID:" <<   istream->streamID );
                return -2;
            } 

            nitems = istream->nitems() - ritems;
            LOG_TRACE( tagged_file_sink_b_base,  " ISTREAM: IDX:" << idx  << " ITEMS AVAIL/READ/REQ " << nitems << "/" 
                      << ritems << "/" << _ninput_items_required[idx] );
            if ( nitems >= _ninput_items_required[idx] && nitems > 0 ) {
                //remove eos checks ...if ( nitems < _ninput_items_required[idx] ) nitems=0;
                _ninput_items.push_back( nitems );
                _input_items.push_back( (const void *) (istream->read_pointer(ritems)) );
            }
        }

        nout=0;
        if ( _input_items.size() != 0 && serviceThread->threadRunning() ) {
            LOG_TRACE( tagged_file_sink_b_base, " CALLING WORK.....N_OUT:" << noutput_items << 
                      " N_IN:" << nitems << " ISTREAMS:" << _input_items.size() << 
                      " OSTREAMS:" << _output_items.size());
            nout = gr_sptr->general_work( noutput_items, _ninput_items, _input_items, _output_items);

            // sink/analyzer patterns do not return items, so consume_each is not called in Gnu Radio BLOCK
            if ( nout == 0 ) {
                gr_sptr->consume_each(nitems);
            }

            LOG_TRACE( tagged_file_sink_b_base, "RETURN  WORK ..... N_OUT:" << nout);
        }

        // check for stop condition from work method
        if ( nout < gr_block::WORK_DONE ) {
            LOG_WARN( tagged_file_sink_b_base, "WORK RETURNED STOP CONDITION..." << nout );
            nout=0;
            eos = true;
        }
    }

    return nout;
 
}
示例#30
0
int LsapiConn::processResp()
{
    int ret;
    while( getState() == PROCESSING )
    {
        if ( m_iPacketHeaderLeft > 0 )
        {
            ret = read( ((char *)&m_respHeader) + sizeof( m_respHeader ) - m_iPacketHeaderLeft, 
                        m_iPacketHeaderLeft );
            if ( D_ENABLED( DL_MEDIUM ) )
                LOG_D(( getLogger(), "[%s] process packet header %d bytes",
                    getLogId(), ret ));
            if ( ret > 0 )
            {
                m_iPacketHeaderLeft -= ret;
                if ( m_iPacketHeaderLeft == 0 )
                {
                    m_iPacketLeft = verifyPacketHeader( &m_respHeader ) -
                            LSAPI_PACKET_HEADER_LEN;
                    if ( m_iPacketLeft < 0 )
                    {
                        const char * p = (const char *)&m_respHeader;
                        LOG_WARN(( "[%s] LSAPI Packet header is invalid,"
                                "('%c','%c','%c','%c','%c','%c','%c','%c')",
                                getLogId(), *p, *(p+1), *(p+2), *(p+3),
                                *(p+4), *(p+5), *(p+6), *(p+7) ));
						break;

                    }
//                     if ( m_iPacketLeft > LSAPI_MAX_HEADER_LEN )
//                     {
//                         LOG_WARN(( "[%s] LSAPI Packet is too large: %d",
//                                 getLogId(), m_iPacketLeft ));
// 						break;
//                     }
                    switch( m_respHeader.m_type )
                    {
                    case LSAPI_RESP_END:
                        m_respState = 0;
						incReqProcessed();
                        setInProcess( 0 );
                        getConnector()->endResponse( 0, 0 );
                        return 0;
                    case LSAPI_RESP_HEADER:
                        m_iCurRespHeader = 0;
                        m_respState = LSAPI_CONN_READ_RESP_INFO;
                        m_pRespHeaderProcess = (char *)&m_respInfo;
                        setRespBuf( m_pRespHeaderProcess );
                        break;
                    case LSAPI_REQ_RECEIVED:
                        m_reqReceived       = 1;
                        break;
                    }
                }
            }
            else
            {
                if (( m_respState == LSAPI_CONN_READ_RESP_BODY )&&
                    ( getConnector()))
                    getConnector()->flushResp();
                return ret;
            }
        }
        if ( m_iPacketLeft > 0 )
        {
            switch( m_respHeader.m_type )
            {
            case LSAPI_RESP_HEADER:
                ret = processRespHeader();
                if ( ret <= 0 )
                    return ret;
                break;
            case LSAPI_RESP_STREAM:
                ret = readRespBody();
                if ( ret <= 0 )
                {
                    if (( m_respState == LSAPI_CONN_READ_RESP_BODY )&&
                        ( getConnector()))
                        getConnector()->flushResp();
                    return ret;
                }
                break;
            case LSAPI_STDERR_STREAM:
                ret = readStderrStream();
                if ( ret <= 0 )
                    return ret;
                break;
            default:
                //error: protocol error
                LOG_NOTICE(( getLogger(), "[%s] Unknown Packet Type %c, LSAPI protcol is broken.",
                    getLogId(), m_respHeader.m_type ));
                errno = EIO;
                return -1;
            }
        }
        else
        {
            m_iPacketHeaderLeft = LSAPI_PACKET_HEADER_LEN;
        }
    }
	errno = EIO;    
    return -1;
}