Esempio n. 1
0
//!
//!
//!
//! @param[in] pMeta a pointer to the node controller (NC) metadata structure
//! @param[in] serviceIds
//! @param[in] serviceIdsLen
//!
//! @return
//!
//! @pre
//!
//! @note
//!
int doStartService(ncMetadata * pMeta, serviceInfoType * serviceIds, int serviceIdsLen)
{
    int rc = 0;
    int ret = 0;

    rc = initialize(pMeta, FALSE);
    if (rc) {
        return (1);
    }

    LOGDEBUG("invoked: userId=%s\n", SP(pMeta ? pMeta->userId : "UNKNOWN"));

    int start_cc = 0;
    for (int i = 0; i < serviceIdsLen; i++) {
        if (strcmp(serviceIds[i].type, "cluster") == 0) {
            start_cc = 1;
        } else if (strcmp(serviceIds[i].type, "node") == 0) {
            //GRZE: This is currently a NOOP; also "enabled" would not be right
            //ret = doModifyNode(pMeta, serviceIds[i].name, "enabled");
        }
    }
    if (serviceIdsLen < 1) {
        start_cc = 1;
    }
    if (start_cc != 1)
        goto done;

    // this is actually a NOP
    sem_mywait(CONFIG);
    {
        if (config->ccState == SHUTDOWNCC) {
            LOGWARN("attempt to start a shutdown CC, skipping.\n");
            ret++;
        } else if (ccCheckState(0)) {
            LOGWARN("ccCheckState() returned failures, skipping.\n");
            ret++;
        } else {
            LOGINFO("starting service\n");
            ret = 0;
            config->kick_enabled = 0;
            ccChangeState(DISABLED);
        }
    }
    sem_mypost(CONFIG);

done:
    LOGTRACE("done\n");

    return (ret);
}
Esempio n. 2
0
void timer_manager_t::register_timer(
    uint32_t                       interval_,
    const time_event_callback_t&   callback_,
    bool                           persist_,
    time_t                         start_time_
)
{
    LOGTRACE((TIMER_MANAGER_MODULE, "timer_manager_t::register_timer args-[interval:%u, persist:%d, start_time:%lu] begin", interval_, persist_, start_time_));

    CHECK_LOCK(m_is_lock, m_mutex);

    time_t local_start_time = start_time_;

    if (!local_start_time)
    {
        local_start_time = get_cached_time_i().tv_sec;
    }

    time_event_t* time_event = new time_event_t(
        local_start_time,
        interval_,
        0,
        local_start_time + interval_,
        callback_,
        persist_
    );
    if (NULL == time_event)
    {
        LOGWARN((TIMER_MANAGER_MODULE, "timer_manager_t::register_timer new time_event_t failed"));
        return;
    }

    //! yunjie: 这里不需要加锁, m_time_heap被初始化为线程安全的
    register_timer_i(time_event);

    LOGTRACE((TIMER_MANAGER_MODULE, "timer_manager_t::register_timer end"));
}
Esempio n. 3
0
//!
//!
//!
//! @param[in] pMeta a pointer to the node controller (NC) metadata structure
//! @param[in] serviceIds
//! @param[in] serviceIdsLen
//!
//! @return
//!
//! @pre
//!
//! @note
//!
int doStopService(ncMetadata * pMeta, serviceInfoType * serviceIds, int serviceIdsLen)
{
    int rc = 0;
    int ret = 0;

    rc = initialize(pMeta, FALSE);
    if (rc) {
        return (1);
    }

    LOGDEBUG("invoked: userId=%s\n", SP(pMeta ? pMeta->userId : "UNKNOWN"));

    int stop_cc = 0;
    for (int i = 0; i < serviceIdsLen; i++) {
        if (strcmp(serviceIds[i].type, "cluster") == 0) {
            stop_cc = 1;
        } else if (strcmp(serviceIds[i].type, "node") == 0) {
            //GRZE: map stop operation to modifyNode("disabled") here
            ret = doModifyNode(pMeta, serviceIds[i].name, "disabled");
        }
    }
    if (serviceIdsLen < 1) {
        stop_cc = 1;
    }
    if (stop_cc != 1)
        goto done;

    sem_mywait(CONFIG);
    {
        if (config->ccState == SHUTDOWNCC) {
            LOGWARN("attempt to stop a shutdown CC, skipping.\n");
            ret++;
        } else if (ccCheckState(0)) {
            LOGWARN("ccCheckState() returned failures, skipping.\n");
            ret++;
        } else {
            LOGINFO("stopping service\n");
            ret = 0;
            config->kick_enabled = 0;
            ccChangeState(STOPPED);
        }
    }
    sem_mypost(CONFIG);

done:
    LOGTRACE("done\n");

    return (ret);
}
Esempio n. 4
0
bool ServiceMonTask::on_cat_got(const U8 * pData, U32 iLen)
{
	bool bRet = false;
	if((NULL == pData)  || (iLen < 3))
		return bRet;

	try
	{
		novelsuper::psisi_parse::CatSection *pcat = (novelsuper::psisi_parse::CatSection *)pData;

		U8 iCatVersion = pcat->version();
//		LOGTRACE(LOGINFO,"on_cat_got ver %d newver %d\n",m_iCATVersion, iCatVersion);

		if(iCatVersion == m_iCATVersion)
			return bRet;

		for( novelsuper::psisi_parse::CA_I q = pcat->begin<novelsuper::psisi_parse::DescCA>(); ! q.empty(); ++q )
		{
			U32 emmPid = q->ca_pid();
			if(q->ca_system_id() == m_CASystemID && m_stService.emm_pid != emmPid)
			{
				LOGTRACE(LOGINFO,"on_cat_got emmpid change! ca = %d,oldemm = %d newemm = %d ver = %d",m_CASystemID, m_stService.emm_pid, emmPid, m_iCATVersion);
				m_stService.emm_pid = emmPid;
				if(m_iCATVersion != 0xFF)
					bRet = true;
			}
		}
		m_iCATVersion = iCatVersion;
	}
	catch(novelsuper::psisi_parse::RuntimeError &e)
	{
		LOGTRACE(LOGINFO, " RuntimeError!!! %s\n",e.what());
		return false;
	}
	return bRet;
}
Esempio n. 5
0
//!
//! Assumes that the vol_data struct is populated, including the connection_string
//!
//! @param[in] sc_url - The URL to reach the cluster's SC at.
//! @param[in] use_ws_sec - boolean to determine use of WS-SEC.
//! @param[in] ws_sec_policy_file - Policy file path for WS-SEC
//! @param[in] vol_data - The ebs_volume_data struct pointer
//! @param[in] local_ip - The local host's external IP
//! @param[in] local_iqn - The local host's IQN
//!
//! @return EUCA_OK on success, EUCA_ERROR on failure
//!
//! @pre
//!
//! @post
//!
//! @note
//!
int disconnect_ebs_volume_with_struct(char *sc_url, int use_ws_sec, char *ws_sec_policy_file, ebs_volume_data * vol_data, char *local_ip, char *local_iqn)
{
    int ret = EUCA_ERROR;
    int do_rescan = 0;                 // don't do rescan

    if (vol_data == NULL) {
        LOGERROR("Could not disconnect volume, got null volume data struct\n");
        return EUCA_ERROR;
    }

    LOGTRACE("Requesting volume lock\n");
    //Grab a lock.
    sem_p(vol_sem);
    LOGTRACE("Got volume lock\n");

    ret = cleanup_volume_attachment(sc_url, use_ws_sec, ws_sec_policy_file, vol_data, vol_data->connect_string, local_ip, local_iqn, do_rescan);
    LOGTRACE("cleanup_volume_attachment returned: %d\n", ret);

    LOGTRACE("Releasing volume lock\n");
    //Release the volume lock
    sem_v(vol_sem);
    LOGTRACE("Released volume lock\n");
    return ret;
}
Esempio n. 6
0
//! Checks the sensor registry for presence of a sensor with the given name
//! Returns 0 if not found, 1 if found
//! Always returns 0 if name == NULL
static int is_registered_sensor_name(const char *name) {
    int i = 0;
    if(name == NULL) {
        return FALSE;
    }

    for(i = 0; i < sensor_registry.sensor_count; i++) {
        LOGTRACE("Checking sensor config name %s against config name: %s and sensor name: %s\n", name, sensor_registry.sensors[i]->config_name, sensor_registry.sensors[i]->sensor_name);
        if(strncmp(sensor_registry.sensors[i]->config_name, name, SENSOR_NAME_MAX) == 0) {
            return TRUE;
        }
    }

    return FALSE;
}
Esempio n. 7
0
void * thread_t::thread_func(void *arg)
{
    LOGTRACE((THREAD_MODULE, "thread_func begin"));

	thread_t* thread = (thread_t*)arg;

	thread->m_lock.lock();
	thread->m_alive = true;
	thread->m_cond.broadcast();
	thread->m_lock.unlock();

	sigset_t sig_mask;
	sigfillset(&sig_mask);
	pthread_sigmask(SIG_SETMASK, &sig_mask, NULL);

    //! yunjie: invoke the registed function.
	thread->m_thread_func();

	thread->m_lock.lock();
	thread->m_alive = false;
	thread->m_cond.broadcast();
	thread->m_lock.unlock();

	if(!thread->is_joinable())
	{
		thread->m_lock.lock();
		while(thread->m_alive) thread->m_cond.wait(thread->m_lock);
		thread->m_lock.unlock();

		SAFE_DELETE(thread);
	}


    LOGTRACE((THREAD_MODULE, "thread_func end"));
	pthread_exit(NULL);
}
Esempio n. 8
0
    void ClientConnection::writeImpl( std::string message )
    {
        boost::lock_guard<boost::mutex> scope_guard(this->outbox_mutex);

        if (message.back() != '\n')
            message += '\n';
        this->outbox.push_back( message );
        if ( this->outbox.size() > 1 ) {
            // outstanding write
            LOGTRACE(LT("Backlog writing to "), this->socket->remote_endpoint(), LT(" - "), this->outbox.size(), LT(" items awaiting send"));
            return;
        }

        this->write();
    }
Esempio n. 9
0
//! Return if the given sensor is in the list of enabled_sensors. Not terribly efficient
//! But the list is usually really short (eg. <10)
static int get_new_config_status(const char *sensor_name, const char **enabled_sensors) 
{
    if(enabled_sensors == NULL) {
        LOGERROR("Cannot determine config status of sensor %s due to null list of sensors to enable\n", sensor_name);
        return FALSE;
    }

    for (int i=0; enabled_sensors[i] != NULL; i++) {
        const char *enabled_sensor_name = enabled_sensors[i];
        LOGTRACE("Checking config status of sensor %s from %s\n", sensor_name, enabled_sensor_name);
        if(strncmp(sensor_name, enabled_sensor_name, SENSOR_NAME_MAX) == 0) {
            return TRUE;
        }
    }
    return FALSE;
}
Esempio n. 10
0
bool TvDevice::getSignalStatus(long& locked,long& strength,long& quality)
{
	bool bRet = false;
	int  iRet = 0;
	BYTE	szBuf[10]={0};
	
#if defined(WIN32)
	ULONG uBufferSize = 10;
	DWORD uRetBytes = 0;
	BOOL  rt = DeviceIoControl (
		h_,
		IOCTL_NOVELUSB_GET_TUNER_STATUS(DVBC_TUNER_1),
		NULL,
		0,
		szBuf,
		uBufferSize,
		(unsigned long *)&uRetBytes,
		NULL);
	if(rt && szBuf[0] !=0 ) 
	{
		bRet = true;
	}
#else
	{
		AutoLockT lock(mutex_);
		iRet = ioctl(h_, RT10UP_TUNER_GET_SIGNAL_STATUS, szBuf);
		bRet = (0 <= iRet && szBuf[0] != 0) ? true : false;
	}
#endif 
	
	if(bRet)
	{
		locked = (BYTE)szBuf[0];
		strength = (BYTE)szBuf[1];
		quality  = (BYTE)szBuf[2];
	}
	else{
		locked = 0;
		strength =0;
		quality =0;
	}
	
	LOGTRACE(LOGINFO,"TvDevice::getSignalStatus(%d,%d,%d),iRet=%d.\n",locked,strength,quality,iRet);
	return bRet;
}
Esempio n. 11
0
//! Builds a basic sensor output json object. Returns the newly allocated json
json_object *build_sensor_output(const char *sensor_name, const char *description, time_t timestamp, int ttl, json_object *tags, json_object *values) {
    json_object *event = json_object_new_object();
    if(sensor_name != NULL) {
        json_object_object_add(event, SENSOR_NAME_KEY, json_object_new_string(sensor_name));
    }
    if(description != NULL) {
        json_object_object_add(event, SENSOR_DESCRIPTION_KEY, json_object_new_string(description));
    }
    json_object_object_add(event, SENSOR_TIMESTAMP_KEY, json_object_new_int64((long)timestamp));
    json_object_object_add(event, SENSOR_TTL_KEY, json_object_new_int(ttl));
    json_object_object_add(event, SENSOR_TAGS_KEY, tags);
    //copy the values
    const char *tmp_data = json_object_to_json_string(values);
    LOGTRACE("Building sensor output from %s\n", tmp_data);
    json_object *sensor_data = json_tokener_parse(tmp_data);
    json_object_object_add(event, SENSOR_DATA_KEY, sensor_data);
    return event;
}
Esempio n. 12
0
//!
//! Execute a system command
//!
//! @param[in] event_name the event to work on
//! @param[in] param1 the parameters to pass to the command.
//!
//! @return 0 on failure or the proper hook status code [1-99]
//!
int call_hooks(const char *event_name, const char *param1)
{
    int ret = 0;
    DIR *dir = NULL;
    char *entry_name = NULL;
    char cmd[MAX_PATH] = "";
    char entry_path[MAX_PATH] = "";
    struct stat sb = { 0 };
    struct dirent *dir_entry = NULL;

    assert(event_name);
    if (!initialized) {
        // return EUCA_OK if hooks were not initialized
        return (EUCA_OK);
    }

    if ((dir = opendir(hooks_path)) == NULL) {
        return (EUCA_ERROR);
    }

    while ((dir_entry = readdir(dir)) != NULL) {
        entry_name = dir_entry->d_name;

        if (!strcmp(".", entry_name) || !strcmp("..", entry_name))
            continue;                  // ignore known unrelated files

        // get the path of the directory item
        snprintf(entry_path, sizeof(entry_path), "%s/%s", hooks_path, entry_name);
        if (stat(entry_path, &sb) == -1)
            continue;                  // ignore access errors

        // run the hook if...
        if ((S_ISLNK(sb.st_mode) || S_ISREG(sb.st_mode))    // looks like a file or symlink
            && (sb.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) {  // is executable
            snprintf(cmd, sizeof(cmd), "%s %s %s %s", entry_path, event_name, euca_path, param1 ? param1 : "");
            ret = WEXITSTATUS(system(cmd));
            LOGTRACE("executed hook [%s %s%s%s] which returned %d\n", entry_name, event_name, param1 ? " " : "", param1 ? param1 : "", ret);
            if ((ret > 0) && (ret < 100))
                break;                 // bail if any hook returns code [1-99] (100+ are reserved for future use)
        }
    }
    closedir(dir);
    return ((ret == 0) ? EUCA_OK : EUCA_ERROR);
}
Esempio n. 13
0
static void
T(init)(void)
{
	void *libc;
	const char *err;
	void (*libc__exit)(int);
	void (*libc_free)(void *);
	void *(*libc_malloc)(size_t);

	LOGTRACE();

	libc = dlopen(LIBC_PATH, RTLD_NOW);
	if ((err = dlerror()) != NULL) {
		(void) fprintf(stderr, "libc.so load error: %s\r\n", err);
		exit(EX_OSERR);
	}

  	libc_malloc = (void *(*)(size_t)) dlsym(libc, "malloc");
	if ((err = dlerror()) != NULL) {
		(void) fprintf(stderr, "libc malloc() not found: %s\r\n", err);
		exit(EX_OSERR);
	}

  	libc_free = (void (*)(void *)) dlsym(libc, "free");
	if ((err = dlerror()) != NULL) {
		(void) fprintf(stderr, "libc free() not found: %s\r\n", err);
		exit(EX_OSERR);
	}

  	libc__exit = dlsym(libc, "_exit");
	if ((err = dlerror()) != NULL) {
		(void) fprintf(stderr, "libc _exit() not found: %s\r\n", err);
		exit(EX_OSERR);
	}

	(void) dlclose(libc);
	T(init_common)();
	
	/* We've completed initialisation. */
	track_hook__exit = libc__exit;
	track_hook_malloc = libc_malloc;
	track_hook_free = libc_free;
}
Esempio n. 14
0
//!
//!
//!
//! @param[in] dev_string
//!
//! @return -1 for any failures, 0 if a timeout occured or a positive value is success.
//!
int disconnect_iscsi_target(const char *dev_string)
{
    char command[MAX_PATH] = { 0 };
    char stdout_str[MAX_OUTPUT] = { 0 };
    char stderr_str[MAX_OUTPUT] = { 0 };
    int ret = 0;

    assert(strlen(home));

    snprintf(command, MAX_PATH, "%s %s,%s", disconnect_storage_cmd_path, home, dev_string);
    LOGTRACE("invoking `%s`\n", command);

    sem_p(iscsi_sem);
    ret = timeshell(command, stdout_str, stderr_str, MAX_OUTPUT, DISCONNECT_TIMEOUT);
    sem_v(iscsi_sem);
    LOGDEBUG("disconnect script returned: %d, stdout: '%s', stderr: '%s'\n", ret, stdout_str, stderr_str);

    return (ret);
}
Esempio n. 15
0
/**
 * This API is invoked when eucanetd will potentially be idle. For example, after
 * populating the global network state, eucanetd detects that no action needs to
 * be taken. Good for pre-populating cache, or flushing dirty cache - so these
 * actions are not necessary in the regular iteration.
 * @param pConfig [in] a pointer to eucanetd system-wide configuration
 * @param pGni [in] a pointer to the Global Network Information structure
 * @return 0 on success. Integer number on failure.
 */
static int network_driver_system_maint(eucanetdConfig *pConfig, globalNetworkInfo *pGni) {
    int rc = 0;
    struct timeval tv;
    
    LOGTRACE("Running maintenance for '%s' network driver.\n", DRIVER_NAME());
    eucanetd_timer(&tv);

    // Is the driver initialized?
    if (!IS_INITIALIZED()) {
        LOGERROR("Failed to run maintenance activities. Driver '%s' not initialized.\n", DRIVER_NAME());
        return (1);
    }

    // Make sure midoname buffer is available
    midonet_api_cache_midos_init();

    pMidoConfig->config = pConfig;
    rc = do_midonet_maint(pMidoConfig);
    return (rc);
}
Esempio n. 16
0
void
T(clean_key)(void *data)
{
	track_list *list;

	LOGTRACE();
	if (data != NULL) {
		list = data;

		LOCK_LOCK(&lock);
		list->prev->next = list->next;
		list->next->prev = list->prev;
		LOCK_UNLOCK(&lock);

		T(report)(list);	
		(free)(list);

		(void) pthread_setspecific(thread_key, NULL);
	}	
}
Esempio n. 17
0
/**
 * Adds tablename table to this handler. No-op if the table is already present.
 *
 * @param ebth [in] pointer to the EB table handler structure
 * @param tablename [in] a string pointer to the table name
 *
 * @return 0 on success. 1 on failure.
 */
int ebt_handler_add_table(ebt_handler *ebth, char *tablename) {
    ebt_table *table = NULL;
    if (!ebth || !tablename || !ebth->init) {
        return (1);
    }

    LOGTRACE("adding table %s\n", tablename);
    table = ebt_handler_find_table(ebth, tablename);
    if (!table) {
        ebth->tables = realloc(ebth->tables, sizeof(ebt_table) * (ebth->max_tables + 1));
        if (!ebth->tables) {
            LOGFATAL("out of memory!\n");
            exit(1);
        }
        bzero(&(ebth->tables[ebth->max_tables]), sizeof(ebt_table));
        snprintf(ebth->tables[ebth->max_tables].name, 64, tablename);
        ebth->max_tables++;
    }

    return (0);
}
Esempio n. 18
0
 ClientConnection::ClientConnection( boost::asio::io_service& io_service, std::string address, int port )
     : io_service( io_service )
 {
     LOGTRACE(LT("Creating ClientConnection to "), address, LT(":"), port);
     // connect the socket to the requested endpoint
     boost::asio::ip::tcp::resolver resolver( io_service );
     boost::asio::ip::tcp::resolver::query query( address, std::to_string( port ) );
     boost::system::error_code ec;
     boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve( query, ec );
     if (ec)
         LOGERROR(LT("Failed to resolve endpoint "), address, LT(":"), port, LT(" - "), ec.message());
     try
     {
         this->socket = std::unique_ptr< boost::asio::ip::tcp::socket >(new boost::asio::ip::tcp::socket(io_service));
         boost::asio::ip::tcp::resolver::iterator connected_endpoint = boost::asio::connect(*this->socket, endpoint_iterator);
         LOGFINE(LT("Connected - "), connected_endpoint->service_name(), LT(" - "), connected_endpoint->host_name());
     }
     catch (boost::system::system_error e)
     {
         LOGERROR(LT("Failed to connect to "), address, LT(":"), port, LT(" - "), e.code().message());
     }
 }
Esempio n. 19
0
//!
//!
//!
//! @param[in] pMeta a pointer to the node controller (NC) metadata structure
//!
//! @return
//!
//! @pre
//!
//! @note
//!
int doShutdownService(ncMetadata * pMeta)
{
    int rc = 0;
    int ret = 0;

    rc = initialize(pMeta, FALSE);
    if (rc) {
        return (1);
    }

    LOGDEBUG("invoked: userId=%s\n", SP(pMeta ? pMeta->userId : "UNKNOWN"));

    sem_mywait(CONFIG);
    {
        config->kick_enabled = 0;
        ccChangeState(SHUTDOWNCC);
    }
    sem_mypost(CONFIG);

    LOGTRACE("done\n");
    return (ret);
}
Esempio n. 20
0
bool ServiceMonTask::on_nit_got(const U8 * pData, U32 iLen)
{
	bool bRet = false;
	if((NULL == pData)  || (iLen < 10))
		return bRet;

	novelsuper::psisi_parse::NitSection *pNit = (novelsuper::psisi_parse::NitSection *)pData;

	U8 iNitVersion = pNit->version();

//	LOGTRACE(LOGINFO,"[ServiceMonTask::on_nit_got Ver=%u %u \n",m_iNitVersion,iNitVersion);
//
//	int iPDSD = 0;
//	novelsuper::psisi_parse::NitHuangGang_I privateIt = 
//		pNit->begin<novelsuper::psisi_parse::DescNitHuangGang>();
//	if(!privateIt.empty())
//	{
//		iPDSD = privateIt->privateData();
//	}
//	LOGTRACE(LOGINFO,"[ServiceMonTask::on_nit_got iPDSD %d\n",iPDSD);

	if(m_iNitVersion != iNitVersion)
	{
		if(!pNit->CRC_OK())
			return bRet;

		LOGTRACE(LOGINFO,"[ServiceMonTask::on_nit_got Ver=%u %u \n",m_iNitVersion,iNitVersion);
		if(m_iNitVersion == 0xFF)
		{
			m_iNitVersion = iNitVersion;
			UpdateVersions();		
			return bRet;
		}
		
		m_iNitVersion = iNitVersion;
		bRet = true;
	}
	return bRet;
}
Esempio n. 21
0
int conf_stats(const char **enabled_sensors)
{
    int result = EUCA_OK;

    if (enabled_sensors == NULL) {
        LOGDEBUG("conf_stats() called when sensors are not enabled\n");
        return EUCA_ERROR;
    }
    
    if(get_lock_fn != NULL) {
        get_lock_fn();
    }

    {
        // enable ones listed
        int sensor_should_enable = FALSE;
        int toggle_count = 0;
        for(int i = 0; i < sensor_registry.sensor_count; i++) {
            sensor_should_enable = get_new_config_status(sensor_registry.sensors[i]->config_name, enabled_sensors);
            LOGTRACE("Should enable sensor %s = %d .Current enable = %d\n", sensor_registry.sensors[i]->sensor_name, sensor_should_enable, sensor_registry.sensors[i]->enabled);
            if(sensor_registry.sensors[i]->enabled != sensor_should_enable) {
                //Toggle.
                sensor_registry.sensors[i]->enabled = sensor_should_enable;
                if(sensor_registry.sensors[i]->state_toggle_callback != NULL) {
                    sensor_registry.sensors[i]->state_toggle_callback(sensor_should_enable);
                }
                toggle_count++;
            }
        }
        LOGDEBUG("Changed state of %d sensors\n", toggle_count);
    }

    if(release_lock_fn != NULL) {
        release_lock_fn();
    }
    
    return result;
}
Esempio n. 22
0
/**
 * Releases all resources of the given ebt_handler.
 *
 * @param ebth [in] pointer to the EB table handler structure
 *
 * @return 0 on success. 1 otherwise.
 */
int ebt_handler_close(ebt_handler *ebth) {
    int i = 0;
    int j = 0;
    if (!ebth || !ebth->init) {
        LOGTRACE("Invalid argument. NULL or uninitialized ebt_handler.\n");
        return (1);
    }

    for (i = 0; i < ebth->max_tables; i++) {
        for (j = 0; j < ebth->tables[i].max_chains; j++) {
            EUCA_FREE(ebth->tables[i].chains[j].rules);
        }
        EUCA_FREE(ebth->tables[i].chains);
    }
    EUCA_FREE(ebth->tables);

    unlink_handler_file(ebth->ebt_filter_file);
    unlink_handler_file(ebth->ebt_nat_file);
    unlink_handler_file(ebth->ebt_asc_file);
    ebth->init = 0;

    return (0);
}
Esempio n. 23
0
bool TvDevice::smartcard_inserted()
{
	bool bRet = false;
	int  iRet = 0;
	BYTE  cStatus;
	
#if defined(WIN32)
	
	DWORD dwRetBytes = 0;
	BOOL rt = DeviceIoControl (
		h_,
		IOCTL_NOVELUSB_GET_SMARTCART_STATUS,
		NULL,
		0,
		&cStatus,
		sizeof(BYTE),
		&dwRetBytes,
		NULL);
	if(rt && 0 != cStatus) 
	{
		bRet = true;
	}
#else
	{
		AutoLockT lock(mutex_);
		iRet =ioctl(h_, RT10UP_CA_SC_GET_STATUS,&cStatus);
		if(0 <= iRet)
		{
			bRet = true;
		}
	}
#endif 

	LOGTRACE(LOGINFO,"TvDevice::smartcard_inserted(%d),iRet =%d.\n",bRet,iRet);
	return bRet;
}
Esempio n. 24
0
bool TvDevice::open()
{
	bool bRet = true;
#if defined(WIN32)
	h_ = CreateFile(
		"\\\\.\\ntdvbcusbcard-0",
		GENERIC_WRITE,
		FILE_SHARE_WRITE,
		NULL,
		OPEN_EXISTING,
		0,
		NULL);
	
	if(INVALID_HANDLE_VALUE == h_)
		bRet = false;
#else
	if ((h_ = ::open("/dev/rt10up", O_RDWR)) < 0)
		bRet = false;
#endif 

	LOGTRACE(LOGINFO,"TvDevice::open %s.\n",bRet ? "success":"failed");

	return bRet;
}
Esempio n. 25
0
void
(_exit)(int ex_code)
{
	track_list *list;

	LOGTRACE();	
	if (track_hook__exit == NULL)
		T(init)();
	
	/* We need to hook _exit() so that we can report leaks after
	 * all the atexit() functions, which might release dynamic 
	 * memory.  We cannot simply use atexit() for reporting since
	 * there is no way to garantee we are executed last.
	 *
	 * NOTE sys/track.c and sys/malloc.c both hook _exit(), so
	 * cannot be used together (yet).
	 */
	list = (track_list *)pthread_getspecific(thread_key);
	T(report)(list);	
	(void) pthread_key_delete(thread_key);
	(void) LOCK_FREE(&lock);

	(*track_hook__exit)(ex_code);
}
Esempio n. 26
0
/**
 * Adds chain chainname to table tablename with policy policyname and counter counters.
 * No-op if chainname is already present.
 *
 * @param ebth [in] pointer to the EB table handler structure
 * @param tablename [in] a string pointer to the table name
 * @param chainname [in] a string pointer to the chain name
 * @param policyname [in] a string pointer to the default policy name to use (e.g. "DROP", "ACCEPT")
 * @param counters [in] a string pointer to the counter
 *
 * @return 0 on success. 1 on failure.
 */
int ebt_table_add_chain(ebt_handler *ebth, char *tablename, char *chainname, char *policyname, char *counters) {
    ebt_table *table = NULL;
    ebt_chain *chain = NULL;
    if (!ebth || !tablename || !chainname || !counters || !ebth->init) {
        return (1);
    }
    LOGTRACE("adding chain %s to table %s\n", chainname, tablename);
    table = ebt_handler_find_table(ebth, tablename);
    if (!table) {
        return (1);
    }

    chain = ebt_table_find_chain(ebth, tablename, chainname);
    if (!chain) {
        table->chains = realloc(table->chains, sizeof(ebt_chain) * (table->max_chains + 1));
        if (!table->chains) {
            LOGFATAL("out of memory!\n");
            exit(1);
        }
        bzero(&(table->chains[table->max_chains]), sizeof(ebt_chain));
        snprintf(table->chains[table->max_chains].name, 64, "%s", chainname);
        snprintf(table->chains[table->max_chains].policyname, 64, "%s", policyname);
        snprintf(table->chains[table->max_chains].counters, 64, "%s", counters);
        if (!strcmp(table->chains[table->max_chains].name, "INPUT") ||
            !strcmp(table->chains[table->max_chains].name, "FORWARD") ||
            !strcmp(table->chains[table->max_chains].name, "OUTPUT") ||
            !strcmp(table->chains[table->max_chains].name, "PREROUTING") || !strcmp(table->chains[table->max_chains].name, "POSTROUTING")) {
            table->chains[table->max_chains].ref_count = 1;
        }

        table->max_chains++;

    }

    return (0);
}
Esempio n. 27
0
//!
//!
//!
//! @param[in] msg
//!
//! @pre
//!
//! @post
//!
static void bs_errors(const char *msg)
{
    // we normally do not care to print all messages from blobstore as many are errors that we can handle
    LOGTRACE("blobstore: %s", msg);
}
      void FormatBaseStream::mhive_log_default_callback(void* ptr, int level, const char* fmt, va_list vl) {
        boost::mutex::scoped_lock log_lock(log_mutex);

        static int print_prefix = 1;
        static int count;
        static char line[4096], prev[4096];
        //char ptrString[10];
        //char ptrLine[4096];
        AVClass* avc = ptr ? *(AVClass**) ptr : NULL;
#undef fprintf
#ifdef __WIN32__
#define snprintf _snprintf
#endif
        if (print_prefix && avc) {
          snprintf(line, sizeof (line), "[%s @ %p]", avc->item_name(ptr), ptr);
          //snprintf(ptrString, sizeof (ptrString), "%p", ptr);
        } else {
          line[0] = 0;
          //ptrString[0] = 0;
          return;
        }

        vsnprintf(line + strlen(line), sizeof (line) - strlen(line), fmt, vl);
        std::string msg = org::esb::util::StringUtil::trim(line, "\n");
        //std::string msgPtr = org::esb::util::StringUtil::trim(line, "\n");
        /*
        if (logMap.count(ptrString)) {
          if (logMap[ptrString].size() > MAX_HISTORY) {
            logMap[ptrString].erase(--logMap[ptrString].end());
          }
        }
        logMap[ptrString].push_front(msgPtr);
        */
        /*filter out unwanted messages by loglevel*/
        try{
          if(level>av_log_get_level())return;
          switch (level) {
            case AV_LOG_DEBUG:
              LOGDEBUG(msg);
              break;
            case AV_LOG_INFO:
              LOGINFO(msg);
              break;
            case AV_LOG_ERROR:
              LOGERROR(msg);
              break;
            case AV_LOG_WARNING:
              LOGWARN(msg);
              break;
            case AV_LOG_PANIC:
              LOGFATAL(msg);
              break;
            case AV_LOG_VERBOSE:
              LOGTRACE(msg);
              break;
            default:
              LOGERROR("Unknown LogLevel:" << level << " - " << msg);
              break;
          }
        }catch(Poco::AssertionViolationException & ex){
          std::cout << "error logging"<< ex.displayText() <<std::endl;
          //LOGERROR("error in logging")
        }
      }
Esempio n. 29
0
//!
//! Defines the thread that does the actual migration of an instance off the source.
//!
//! @param[in] arg a transparent pointer to the argument passed to this thread handler
//!
//! @return Always return NULL
//!
static void *migrating_thread(void *arg)
{
    ncInstance *instance = ((ncInstance *) arg);
    virDomainPtr dom = NULL;
    virConnectPtr conn = NULL;
    int migration_error = 0;

    LOGTRACE("invoked for %s\n", instance->instanceId);

    if ((conn = lock_hypervisor_conn()) == NULL) {
        LOGERROR("[%s] cannot migrate instance %s (failed to connect to hypervisor), giving up and rolling back.\n", instance->instanceId, instance->instanceId);
        migration_error++;
        goto out;
    } else {
        LOGTRACE("[%s] connected to hypervisor\n", instance->instanceId);
    }

    dom = virDomainLookupByName(conn, instance->instanceId);
    if (dom == NULL) {
        LOGERROR("[%s] cannot migrate instance %s (failed to find domain), giving up and rolling back.\n", instance->instanceId, instance->instanceId);
        migration_error++;
        goto out;
    }

    char duri[1024];
    snprintf(duri, sizeof(duri), "qemu+tls://%s/system", instance->migration_dst);

    virConnectPtr dconn = NULL;

    LOGDEBUG("[%s] connecting to remote hypervisor at '%s'\n", instance->instanceId, duri);
    dconn = virConnectOpen(duri);
    if (dconn == NULL) {
        LOGWARN("[%s] cannot migrate instance using TLS (failed to connect to remote), retrying using SSH.\n", instance->instanceId);
        snprintf(duri, sizeof(duri), "qemu+ssh://%s/system", instance->migration_dst);
        LOGDEBUG("[%s] connecting to remote hypervisor at '%s'\n", instance->instanceId, duri);
        dconn = virConnectOpen(duri);
        if (dconn == NULL) {
            LOGERROR("[%s] cannot migrate instance using TLS or SSH (failed to connect to remote), giving up and rolling back.\n", instance->instanceId);
            migration_error++;
            goto out;
        }
    }

    LOGINFO("[%s] migrating instance\n", instance->instanceId);
    virDomain *ddom = virDomainMigrate(dom,
                                       dconn,
                                       VIR_MIGRATE_LIVE | VIR_MIGRATE_NON_SHARED_DISK,
                                       NULL,    // new name on destination (optional)
                                       NULL,    // destination URI as seen from source (optional)
                                       0L); // bandwidth limitation (0 => unlimited)
    if (ddom == NULL) {
        LOGERROR("[%s] cannot migrate instance, giving up and rolling back.\n", instance->instanceId);
        migration_error++;
        goto out;
    } else {
        LOGINFO("[%s] instance migrated\n", instance->instanceId);
    }
    virDomainFree(ddom);
    virConnectClose(dconn);

out:
    if (dom)
        virDomainFree(dom);

    if (conn != NULL)
        unlock_hypervisor_conn();

    sem_p(inst_sem);
    LOGDEBUG("%d outgoing migrations still active\n", --outgoing_migrations_in_progress);
    if (migration_error) {
        migration_rollback(instance);
    } else {
        // If this is set to NOT_MIGRATING here, it's briefly possible for
        // both the source and destination nodes to report the same instance
        // as Extant/NOT_MIGRATING, which is confusing!
        instance->migration_state = MIGRATION_CLEANING;
        save_instance_struct(instance);
        copy_instances();
    }
    sem_v(inst_sem);

    LOGDEBUG("done\n");
    unset_corrid(get_corrid());
    return NULL;
}
Esempio n. 30
0
//! A single sensor pass. Runs each sensor and emits the result using
//! the configured emitter.
//! 
int internal_sensor_pass(int return_on_fail) {
    LOGTRACE("Executing internal sensor pass\n");
    json_object *result;
    int i = 0;
    int is_enabled = FALSE;
    int ret = EUCA_OK;
    //Get the sensor list from the config
    char **names = NULL;
    char *tmpstr = configFileValue(SENSOR_LIST_CONF_PARAM_NAME);
    if (tmpstr == NULL) {
        LOGDEBUG("%s parameter is missing from config file\n", SENSOR_LIST_CONF_PARAM_NAME);
    } else {
        names = from_var_to_char_list(tmpstr);
        EUCA_FREE(tmpstr);
    }

    char **sensors = { NULL }; // if no config value or an empty list
    if (names != NULL) {
        sensors = names;
    }

    //Enter the execution loop
    if(get_lock_fn != NULL) {
        get_lock_fn();
    } else {
        LOGERROR("Cannot run internal sensor pass because no lock provided to protect data.\n");

        //Free up the sensor listing
        if (names) {
            for (int i=0; names[i]; i++) {
                EUCA_FREE(names[i]);
            }
            EUCA_FREE(names);
        }

        return EUCA_ERROR;
    }

    LOGTRACE("Running %d sensors\n", sensor_registry.sensor_count);
    for(i = 0; i < sensor_registry.sensor_count; i++) {
        LOGTRACE("Checking sensor %s is enabled\n", sensor_registry.sensors[i]->sensor_name);
        is_enabled = get_new_config_status(sensor_registry.sensors[i]->config_name, (const char**)sensors);
        if(is_enabled && sensor_registry.sensors[i]->sensor_function != NULL) {
            result = sensor_registry.sensors[i]->sensor_function(); 
            if(result == NULL) {
                LOGERROR("Error encountered getting internal sensor output from sensor %s\n", sensor_registry.sensors[i]->sensor_name);
                ret = EUCA_ERROR;
            } else {
                LOGTRACE("Offering event for emitter: %s\n", json_object_to_json_string(result));
                if(emitter_offer_event(result) != EUCA_OK) {
                    LOGERROR("Error emitting event from internal sensor %s\n", sensor_registry.sensors[i]->sensor_name);
                    ret = EUCA_ERROR;
                } else {
                    LOGTRACE("Event offered to emitter successfully\n");
                }
            }
        } else {
            LOGTRACE("Sensor %s not enabled, skipping execution\n", sensor_registry.sensors[i]->sensor_name);
        }
        
        //Update the state of the sensor as needed.
        if(sensor_registry.sensors[i]->state_toggle_callback != NULL) {
            //Must be idempotent
            LOGTRACE("Calling toggle callback on sensor %s with enabled=%d\n", sensor_registry.sensors[i]->sensor_name, is_enabled);
            sensor_registry.sensors[i]->state_toggle_callback(is_enabled);
        }

        if(return_on_fail && ret != EUCA_OK) {
            goto cleanup;
        }
    }
    
 cleanup:
    if(release_lock_fn != NULL) {
        release_lock_fn();
        LOGTRACE("Released lock for stats during sensor pass\n");
    } else {
        LOGERROR("No lock release function found, this could result in deadlock or leaks. Continuing to exit sensor pass function\n");       
    }

    //Free up the sensor listing
    if (names) {
        for (int i=0; names[i]; i++) {
            EUCA_FREE(names[i]);
        }
        EUCA_FREE(names);
    }
    return ret;
}