コード例 #1
0
ファイル: fmd_common.c プロジェクト: kadoma/fms
/**
 * the file_lock funtion
 * is just for the thread check,
 * make sure only one is running.
 *
 * @name file_lock
 * @param const char *
 * @return int
 *
 */
int
file_lock(char *app_name)
{
    char lockfile[64] = {0};
    sprintf(lockfile, ".%s.lock", app_name);

    int lfp = open(lockfile, O_WRONLY|O_CREAT, 0666);
    if(lfp < 0)
    {
        wr_log("file lock", WR_LOG_ERROR, "can't create lockfile in working directory");
        return -1;
    }

    pid_t owner_pid = mylock(lfp);
    if (owner_pid < 0)
    {
        wr_log("", WR_LOG_ERROR, "contrl error.");
        return -1;
    }
    if (owner_pid > 0)
    {
        return owner_pid;
    }
    return 0;
}
コード例 #2
0
ファイル: ev_record.c プロジェクト: kadoma/fms
// open db and create tables.
int ras_event_opendb()
{
	int rc;
	sqlite3 *db;

	printf("Calling %s()\n", __FUNCTION__);

	priv = calloc(1, sizeof(*priv));
	if (!priv)
		return -1;
    
	rc = sqlite3_initialize();
	if (rc != SQLITE_OK) {
		wr_log("", WR_LOG_ERROR,
		    "cpu: Failed to initialize sqlite: error = %d\n",
		     rc);
		return -1;
	}

	do {
		rc = sqlite3_open_v2(SQLITE_RAS_DB, &db,
				     SQLITE_OPEN_FULLMUTEX |
				     SQLITE_OPEN_READWRITE |
				     SQLITE_OPEN_CREATE, NULL);
		if (rc == SQLITE_BUSY)
			usleep(10000);
	} while (rc == SQLITE_BUSY);

	priv->db = db;
    
	if (rc != SQLITE_OK) {
		wr_log("", WR_LOG_ERROR,
		    "cpu: Failed to connect to %s: error = %d\n",
		    SQLITE_RAS_DB, rc);
		return -1;
	}
    
	rc = rasdb_create_table(&cpu_event_tab);
	if (rc == SQLITE_OK)
		rc = ras_prepare_stmt(&priv->stmt_cpu_event, &cpu_event_tab);

	rc = rasdb_create_table(&mem_event_tab);
	if (rc == SQLITE_OK)
		rc = ras_prepare_stmt(&priv->stmt_mem_event, &mem_event_tab);

	rc = rasdb_create_table(&disk_event_tab);
	if (rc == SQLITE_OK)
		rc = ras_prepare_stmt(&priv->stmt_disk_event, &disk_event_tab);

    /* create repaired and not repaired events */
	rc = rasdb_create_table(&rep_record_tab);
	if (rc == SQLITE_OK)
		rc = ras_prepare_stmt(&priv->stmt_rep_record, &rep_record_tab);

	rc = rasdb_create_table(&norep_record_tab);
	if (rc == SQLITE_OK)
		rc = ras_prepare_stmt(&priv->stmt_norep_record, &norep_record_tab);

	return 0;
}
コード例 #3
0
ファイル: ev_record.c プロジェクト: kadoma/fms
static int rasdb_create_table(const struct db_table_descriptor *db_tab)
{
	const struct db_fields *field;
 	char sql[1024] = {0};
    char *p = sql, *end = sql + sizeof(sql);
 	int i,rc;

    memset(sql, 0, sizeof(sql));
    
	p += snprintf(p, end - p, "CREATE TABLE IF NOT EXISTS %s (",
		      db_tab->name);
    
	for (i = 0; i < db_tab->num_fields; i++) {
		field = &db_tab->fields[i];
		p += snprintf(p, end - p, "%s %s", field->name, field->type);

		if (i < db_tab->num_fields - 1)
			p += snprintf(p, end - p, ", ");
	}
	p += snprintf(p, end - p, ")");

	wr_log("", WR_LOG_DEBUG, "SQL: %s\n", sql);

	rc = sqlite3_exec(priv->db, sql, NULL, NULL, NULL);
	if (rc != SQLITE_OK) {
		wr_log("", WR_LOG_ERROR,
		    "Failed to create table %s on %s: error = %d\n", db_tab->name, SQLITE_RAS_DB, rc);
	}
	return rc;
}
コード例 #4
0
ファイル: cpumem_agent.c プロジェクト: kadoma/fms
static int
__log_event(fmd_event_t *pevt) 
{
	int type, fd;
	char *dir;
	char *eclass = NULL;
	char times[26];
	char buf[512];

	char dev_name[32];
	uint64_t dev_id = 0;
	time_t evtime;
	
	evtime = pevt->ev_create;
	eclass = pevt->ev_class;
	
	strcpy(dev_name, pevt->dev_name);
	dev_id = pevt->dev_id;

	if (pevt->event_type == EVENT_FAULT) {
		type = FMD_LOG_FAULT;
		dir = "/var/log/fms/cpumem/fault";
	} else if (pevt->event_type == EVENT_LIST) {
		type = FMD_LOG_LIST;
		dir = "/var/log/fms/cpumem/list";
	} else {
		type = FMD_LOG_ERROR;
		dir = "/var/log/fms/cpumem/serd";
	}

	if ((fd = fmd_log_open(dir, type)) < 0) {
		wr_log(CMEA_LOG_DOMAIN, WR_LOG_ERROR, 
			"failed to record log for event: %s\n", eclass);
		return -1;
	}

	fmd_get_time(times, evtime);
	memset(buf, 0, sizeof buf);
	snprintf(buf, sizeof(buf), "%s\t%s\t%s:\t%llu\n", times, eclass, dev_name, 
		(long long unsigned int)dev_id);

	if (fmd_log_write(fd, buf, strlen(buf)) != 0) {
		wr_log(CMEA_LOG_DOMAIN, WR_LOG_ERROR, 
			"failed to write log file for event: %s\n", eclass);
		fmd_log_close(fd);
		return -1;
	}
	if (type == FMD_LOG_ERROR)
		cpumem_err_printf(fd, (struct fms_cpumem*)pevt->data);
	
	fmd_log_close(fd);

	return 0;
}
コード例 #5
0
ファイル: ev_record.c プロジェクト: kadoma/fms
// there is a bug. wanghuan
int ras_events_handle(fmd_event_t *event)
{
    int i;
	for (i = 0; g_store_handler[i].event_type; i++) {
		char *name = g_store_handler[i].event_type;
		if (strncmp(name, event->dev_name, strlen(name)) == 0) {
			wr_log("", WR_LOG_DEBUG, "handle dev store to DB.[%s]", name);
			return g_store_handler[i].store_handler(event);
		}
	}
    wr_log("", WR_LOG_ERROR, "failed to find event store handler.");
    return -1;
}
コード例 #6
0
ファイル: fmd_common.c プロジェクト: kadoma/fms
void
fmd_timer_fire(fmd_timer_t *ptimer)
{
    pthread_mutex_lock(&ptimer->timer_lock);
    pthread_cond_signal(&ptimer->cond_signal);
    wr_log("", WR_LOG_DEBUG, "fmd time fire again ok ....");
    pthread_mutex_unlock(&ptimer->timer_lock);
}
コード例 #7
0
ファイル: cpumem_agent.c プロジェクト: kadoma/fms
static int
__cpuinfo_init()
{
	enum { 
		MHZ = 1, 
		FLAGS = 2, 
		ALL = 0x3 
	} seen = 0;
	FILE *f;

	f = fopen("/proc/cpuinfo", "r");
	if (f != NULL) { 
		char *line = NULL;
		size_t linelen = 0; 
		double mhz;

		while (getdelim(&line, &linelen, '\n', f) > 0  && seen != ALL) { 
			/* We use only Mhz of the first CPU, assuming they are the same
			   (there are more sanity checks later to make this not as wrong
			   as it sounds) */
			if (sscanf(line, "cpu MHz : %lf", &mhz) == 1) { 
					cpumhz = mhz;
				seen |= MHZ;
			}
			if (!strncmp(line, "flags", 5) && isspace(line[6])) {
				processor_flags = line;
				line = NULL;
				linelen = 0;
				seen |= FLAGS;
			}			      
		} 

		wr_log(CMEA_LOG_DOMAIN, WR_LOG_DEBUG, 
			"cpumhz: %f, processor_flags: %s", 
			cpumhz, processor_flags); 
		
		fclose(f);
		free(line);
	} else
		wr_log(CMEA_LOG_DOMAIN, WR_LOG_WARNING, 
			"Cannot open /proc/cpuinfo");

	return 0;
}
コード例 #8
0
ファイル: fmd_log.c プロジェクト: kadoma/fms
int
fmd_log_open(const char *dir, int type)
{
	char datename[PATH_MAX];
	char filename[PATH_MAX];
	int fd;
	struct dirent *dp;
	const char *logname;
	DIR *dirp;

	if (access(dir, 0) != 0) {
		wr_log("", WR_LOG_ERROR, 
			"FMD: Log Directory %s isn't exist, so create it.\n", dir);
		mkdir(dir, 0777 );
	}

	if ((dirp = opendir(dir)) == NULL) {
		wr_log("", WR_LOG_ERROR, 
			"FMD: failed to open directory %s\n", dir);
		return (-1);
	}

	logname = get_logname(datename, type);
	snprintf(filename, sizeof(filename), "%s/%s", dir, logname);

	if (access(filename, 0) != 0) {
		if ((fd = open(filename, O_RDWR | O_CREAT | O_SYNC | O_APPEND, S_IREAD | S_IWRITE)) < 0) {
			wr_log("", WR_LOG_ERROR, 
				"FMD: failed to create log file %s\n", filename);
			(void) closedir(dirp);
			return (-1);
		}
        } else {
		if ((fd = open(filename, O_RDWR | O_SYNC | O_APPEND)) < 0) {
			wr_log("", WR_LOG_ERROR, 
				"FMD: failed to open log file %s\n", filename);
			(void) closedir(dirp);
			return (-1);
		}
	}
        (void) closedir(dirp);

	return fd;
}
コード例 #9
0
ファイル: ev_record.c プロジェクト: kadoma/fms
int ras_store_rep_event(fmd_event_t *event)
{
	int rc;
    char time1[64] = {0};
    char time2[64] = {0};
    char time3[64] = {0};

	if (!priv || !priv->stmt_rep_record)
		return 0;
    
	wr_log("", WR_LOG_DEBUG, "disk event store: %p\n", priv->stmt_rep_record);
    
    time2string(&event->repaired_T, time1);
    time2string(&event->ev_create, time2);
    time2string(&event->ev_last_occur, time3);

	sqlite3_bind_text(priv->stmt_rep_record,  1, event->dev_name, -1, NULL);
        
	sqlite3_bind_text(priv->stmt_rep_record,  2, time1, -1, NULL);
    sqlite3_bind_text(priv->stmt_rep_record,  3, time2, -1, NULL);
    sqlite3_bind_text(priv->stmt_rep_record,  4, time3, -1, NULL);
    
	sqlite3_bind_int(priv->stmt_rep_record,  5, event->event_type);
	sqlite3_bind_text (priv->stmt_rep_record,  6, event->ev_class, -1, NULL);
	sqlite3_bind_text (priv->stmt_rep_record,  7, "offline", -1, NULL);
	sqlite3_bind_int(priv->stmt_rep_record,  8, event->ev_count);

	sqlite3_bind_int(priv->stmt_rep_record,  9, event->dev_id);
    sqlite3_bind_int(priv->stmt_rep_record,  10, event->evt_id);

	rc = sqlite3_step(priv->stmt_rep_record);
	if (rc != SQLITE_OK && rc != SQLITE_DONE)
		wr_log("", WR_LOG_ERROR,
		    "Failed to do rep event step on sqlite: error = %d\n", rc);
    
	rc = sqlite3_reset(priv->stmt_rep_record);
	if (rc != SQLITE_OK && rc != SQLITE_DONE)
		wr_log("", WR_LOG_ERROR,
		    "Failed reset rep event on sqlite: error = %d\n", rc);
    
	wr_log("", WR_LOG_DEBUG, "register inserted at db\n");

	return rc;
}
コード例 #10
0
ファイル: cpumem_agent.c プロジェクト: kadoma/fms
fmd_event_t *
cpumem_handle_event(fmd_t *pfmd, fmd_event_t *e)
{
	int action = 0;
	int ret = 0;
	uint64_t ev_flag;

	ev_flag = e->ev_flag;
	wr_log(CMEA_LOG_DOMAIN, WR_LOG_DEBUG,
		"handle event, class: %s  flag: 0X%08x, handle_mode: 0X%08x", 
		e->ev_class, ev_flag, e->handle_mode);

	__log_event(e); 
	
	switch (ev_flag) {
	case AGENT_TODO:
		wr_log(CMEA_LOG_DOMAIN, WR_LOG_DEBUG, 
			"cpumem agent handle fault event.");

		if (e->handle_mode & EVENT_HANDLE_MODE_AUTO)
			ret = __handle_fault_event(e);
		/* add other handle mode, eg. user-define. */
		if(e->handle_mode == EVENT_HANDLE_MODE_MANUAL)
			ret = LIST_REPAIRED_MANUAL;
		
		e->event_type = EVENT_LIST;
		__log_event(e);
		action = 1;
		break;
	}

	if (!action) {
		wr_log(CMEA_LOG_DOMAIN, WR_LOG_DEBUG, 
			"cpumem agent log event.");
		return NULL;
	}
	
	wr_log(CMEA_LOG_DOMAIN, WR_LOG_DEBUG,
			"handle event result: %08x", 
			ret);
	
	return (fmd_event_t *)fmd_create_listevent(e, ret);
}
コード例 #11
0
ファイル: cpumem_agent.c プロジェクト: kadoma/fms
fmd_module_t *
fmd_module_init(char *path, fmd_t *pfmd)
{
	if (cpumem_agent_init()) {
		wr_log(CMEA_LOG_DOMAIN, WR_LOG_ERROR,
			"failed to cpumem agent init");
		return NULL;
	}
	
	return (fmd_module_t *)agent_init(&cpumem_mops, path, pfmd);
}
コード例 #12
0
ファイル: ev_record.c プロジェクト: kadoma/fms
static int ras_prepare_stmt(sqlite3_stmt **stmt,
                                const struct db_table_descriptor *db_tab)
{
	int i, rc;
	char sql[1024], *p = sql, *end = sql + sizeof(sql);
	const struct db_fields *field;

	p += snprintf(p, end - p, "INSERT INTO %s (",
		      db_tab->name);

	for (i = 0; i < db_tab->num_fields; i++) {
		field = &db_tab->fields[i];
		p += snprintf(p, end - p, "%s", field->name);

		if (i < db_tab->num_fields - 1)
			p += snprintf(p, end - p, ", ");
	}

	p += snprintf(p, end - p, ") VALUES ( NULL, ");

	for (i = 1; i < db_tab->num_fields; i++) {
		if (i <  db_tab->num_fields - 1)
			strcat(sql, "?, ");
		else
			strcat(sql, "?)");
	}

	wr_log("", WR_LOG_DEBUG, "SQL: %s\n", sql);

	rc = sqlite3_prepare_v2(priv->db, sql, -1, stmt, NULL);
	if (rc != SQLITE_OK) {
		wr_log("", WR_LOG_ERROR,
		    "Failed to prepare insert db at table %s (db %s): error = %s\n",
		    db_tab->name, SQLITE_RAS_DB, sqlite3_errmsg(priv->db));
		stmt = NULL;
	} else {
		wr_log("", WR_LOG_DEBUG, "Recording %s events\n", db_tab->name);
	}

	return rc;
}
コード例 #13
0
ファイル: ev_record.c プロジェクト: kadoma/fms
//mc memcache 
int ras_store_cpu_event(fmd_event_t *event)
{
	int rc;
    char time[64] = {0};

	if (!priv || !priv->stmt_cpu_event)
		return 0;
    
	wr_log("", WR_LOG_DEBUG, "mc_event store: %p\n", priv->stmt_cpu_event);

    time2string(&event->ev_create, time);

	sqlite3_bind_text(priv->stmt_cpu_event,  1, time, -1, NULL);
	sqlite3_bind_text (priv->stmt_cpu_event,  2, event->ev_class, -1, NULL);
    
	sqlite3_bind_int(priv->stmt_cpu_event,  3, event->event_type);
	sqlite3_bind_int(priv->stmt_cpu_event,  4, event->dev_id);
    sqlite3_bind_int(priv->stmt_cpu_event,  5, event->evt_id);

	sqlite3_bind_text(priv->stmt_cpu_event,  6, event->data, -1, NULL);

    if(event->event_type == EVENT_SERD)
	    sqlite3_bind_text(priv->stmt_cpu_event,  7, "Minor", -1, NULL);
    else if(event->event_type == EVENT_FAULT)
	    sqlite3_bind_text(priv->stmt_cpu_event,  7, "Major", -1, NULL);

	rc = sqlite3_step(priv->stmt_cpu_event);
	if (rc != SQLITE_OK && rc != SQLITE_DONE)
		wr_log("", WR_LOG_ERROR,
		    "Failed to do mc_event step on sqlite: error = %d\n", rc);
    
	rc = sqlite3_reset(priv->stmt_cpu_event);
	if (rc != SQLITE_OK && rc != SQLITE_DONE)
		wr_log("", WR_LOG_ERROR,
		    "Failed reset mc_event on sqlite: error = %d\n", rc);
    
	wr_log("", WR_LOG_DEBUG, "register inserted at db\n");

	return rc;
    
}
コード例 #14
0
ファイル: fmd_log.c プロジェクト: kadoma/fms
int
fmd_log_write(int fd, const char *buf, int size)
{
	int len;

	if ((len = write(fd, buf, size)) <= 0) {
		wr_log("", WR_LOG_ERROR, 
			"FMD: failed to write log file: fd=%d.\n", fd);
		return (-1);
	}

    fsync(fd);
    return 0;
}
コード例 #15
0
ファイル: cpu.c プロジェクト: kadoma/fms
/**
 * @param
 * @return
 *     FMD_SUCCESS
 *     NODE_ID_INVALID
 *     OPENDIR_FAILED
 *
 * @desc:
 *     Add Single CPU Info TO LIST
 */
void
fmd_topo_walk_cpu(const char *dir, int nodeid, fmd_topo_t *ptopo)
{
    char path[PATH_MAX];
    //int len;
    struct dirent *dp;
    const char *p;
    char ch;
    DIR *dirp;
    topo_cpu_t *pcpu;
    if ((dirp = opendir(dir)) == NULL)
        return; /* failed to open directory; just skip it */

    while ((dp = readdir(dirp)) != NULL) {
        if (dp->d_name[0] == '.')
            continue; /* skip "." and ".." */

        p = dp->d_name;

        /* check name */
        assert(p != NULL);
        if((strncmp(p, "cpu", 3) != 0)) {
            continue;
        }
        ch = p[3];
        if(ch < '0' || ch > '9') {
            continue;
        }
        ch = p[4];
        if(ch && (ch < '0' || ch > '9')) {
            continue;
        }

        snprintf(path, sizeof(path), "%s/%s", dir, p);
        pcpu = fmd_topo_read_cpu(path, nodeid, atoi(p + 3));
        if(pcpu == NULL) {
            wr_log("",WR_LOG_ERROR,"CPU %d Maybe OFFLINE!  ",atoi(p+3));
            continue;
        }
        list_add(&pcpu->list, &ptopo->list_cpu);
    }

    (void) closedir(dirp);
}
コード例 #16
0
ファイル: fmadm.c プロジェクト: kadoma/fms
int
main(int argc, char *argv[])
{
    const struct cmd *cp;
    const char *p;
    int  err;

    wr_log_logrotate(0);
        wr_log_init("/var/log/fms/fmsadm.log");
        wr_log_set_loglevel(WR_LOG_ERROR);

    if ((p = strrchr(argv[0], '/')) == NULL)
        g_pname = argv[0];
    else
        g_pname = p + 1;

    if (optind >= argc)
        return (usage(stdout));

    for (cp = cmds; cp->cmd_name != NULL; cp++) {
        if (strcmp(cp->cmd_name, argv[optind]) == 0)
            break;
    }

    if (cp->cmd_name == NULL) {
        wr_log("",WR_LOG_ERROR,"%s: illegal subcommand -- %s\n",g_pname,argv[optind]);
        return (usage(stderr));
    }

    if ((g_adm = fmd_adm_open()) == NULL)
        die(NULL); /* fmd_adm_errmsg() has enough info */

    argc -= optind;
    argv += optind;

    optind = 1; /* reset optind so subcommands can getopt() */

    err = cp->cmd_func(g_adm, argc, argv);
    fmd_adm_close(g_adm);
    return (err == FMADM_EXIT_USAGE ? usage(stderr) : err);
}
コード例 #17
0
int p3dThinningSkeletonization(   
	unsigned char* in_im, 
	unsigned char* out_im, 
	const int dimx,
	const int dimy, 
	const int dimz,
	int (*wr_log)(const char*, ...)
	)
{

	unsigned char* tmp_im;

	// Padding/cropping size and dimensions
	const int a_rad = 1;					
	const int a_dimx = dimx + a_rad*2;
	const int a_dimy = dimy + a_rad*2;
	const int a_dimz = dimz + a_rad*2;	


	// Start tracking computational time:
	if (wr_log != NULL)
	{
		p3dResetStartTime(); 
		wr_log ("Pore3D - Performing thinning skeletonization..." );
	}



	// Init output voume with input volume values zero padded:
	P3D_MEM_TRY( tmp_im = (unsigned char*) malloc( a_dimx*a_dimy*a_dimz*sizeof(unsigned char) ) );
	P3D_TRY( p3dZeroPadding3D_uchar2uchar ( in_im, tmp_im, dimx, dimy, dimz, a_rad ) );

	// Call in-place version:
	P3D_TRY( p3dThinning ( tmp_im, a_dimx, a_dimy, a_dimz ) );

	// Crop output:
	P3D_TRY( p3dCrop3D_uchar2uchar ( tmp_im, out_im, a_dimx, a_dimy, a_dimz, a_rad ) );




	// Print elapsed time (if required):
	if (wr_log != NULL)
	{			
		wr_log ("Pore3D - Thinning skeletonization performed successfully in %dm%0.3fs.", p3dGetElapsedTime_min(), p3dGetElapsedTime_sec());
	}	
	
    // Release resources:		
	if ( tmp_im != NULL ) free(tmp_im);	

	// Return OK:
	return P3D_SUCCESS;
	

MEM_ERROR:

	if (wr_log != NULL)
	{
		wr_log ("Pore3D - Not enough (contiguous) memory. Program will exit.");
	}

    // Release resources:	
	if ( tmp_im != NULL ) free(tmp_im);	

	
	return P3D_ERROR;

}
コード例 #18
0
int p3dHuangYagerThresholding_8(
        unsigned char* in_im,
        unsigned char* out_im,
        const int dimx,
        const int dimy,
        const int dimz,
        unsigned char* thresh,
        int (*wr_log)(const char*, ...),
        int (*wr_progress)(const int, ...)
        ) 
{

    double *S, *Sbar, *W, *Wbar;
    double *hist, *F, maxv = 0.0, delta, sum, minsum;
    int i, t, tbest = -1, u0, u1;
    int start, end;

    int ct;


    // Start tracking computational time:
    if (wr_log != NULL) {
        p3dResetStartTime();
        wr_log("Pore3D - Thresholding image according to Huang's method...");
    }


    /* Allocate and initialize to zero kernel histogram: */
    /* Allocate and initialize to zero kernel histogram: */
    P3D_MEM_TRY(hist = (double*) calloc((UCHAR_MAX + 1), sizeof (double)));
    P3D_MEM_TRY(S = (double *) malloc(sizeof (double) *(UCHAR_MAX + 1)));
    P3D_MEM_TRY(Sbar = (double *) malloc(sizeof (double) *(UCHAR_MAX + 1)));
    P3D_MEM_TRY(W = (double *) malloc(sizeof (double) *(UCHAR_MAX + 1)));
    P3D_MEM_TRY(Wbar = (double *) malloc(sizeof (double) *(UCHAR_MAX + 1)));
    P3D_MEM_TRY(F = (double *) malloc(sizeof (double) *(UCHAR_MAX + 1)));

    /* Compute image histogram: */
    for (ct = 0; ct < (dimx * dimy * dimz); ct++)
        hist[in_im[ ct ]] = hist[in_im[ ct ]] + 1.0;


    /* Find cumulative histogram */
    S[0] = hist[0];
    W[0] = 0;
    for (i = 1; i <= UCHAR_MAX; i++) {
        S[i] = S[i - 1] + hist[i];
        W[i] = i * hist[i] + W[i - 1];
    }

    /* Cumulative reverse histogram */
    Sbar[UCHAR_MAX] = 0;
    Wbar[UCHAR_MAX] = 0;
    for (i = (UCHAR_MAX - 1); i >= 0; i--) {
        Sbar[i] = Sbar[i + 1] + hist[i + 1];
        Wbar[i] = Wbar[i + 1] + (i + 1) * hist[i + 1];
    }

    for (t = 1; t < UCHAR_MAX; t++) {
        if (hist[t] == 0.0) continue;
        if (S[t] == 0.0) continue;
        if (Sbar[t] == 0.0) continue;

        /* Means */
        u0 = (int) (W[t] / S[t] + 0.5);
        u1 = (int) (Wbar[t] / Sbar[t] + 0.5);

        /* Fuzziness measure */
        F[t] = _p3dHuangYagerThresholding_yager(u0, u1, t) / (dimx * dimy * dimz);

        /* Keep the minimum fuzziness */
        if (F[t] > maxv)
            maxv = F[t];
        if (tbest < 0)
            tbest = t;
        else if (F[t] < F[tbest]) tbest = t;
    }

    /* Find best out of a range of thresholds */
    delta = F[tbest] + (maxv - F[tbest])*0.05; /* 5% */
    start = (int) (tbest - delta);
    if (start <= 0)
        start = 1;
    end = (int) (tbest + delta);
    if (end >= UCHAR_MAX)
        end = (UCHAR_MAX - 1);
    minsum = UINT_MAX;

    for (i = start; i <= end; i++) {
        sum = hist[i - 1] + hist[i] + hist[i + 1];
        if (sum < minsum) {
            t = i;
            minsum = sum;
        }
    }

    *thresh = (unsigned char) t;


#pragma omp parallel for
    for (ct = 0; ct < (dimx * dimy * dimz); ct++)
        out_im[ ct ] = (in_im[ ct ] > (*thresh)) ? OBJECT : BACKGROUND;

    // Free memory:
    free(hist);
    free(S);
    free(Sbar);
    free(W);
    free(Wbar);
    free(F);

    // Print elapsed time (if required):
    if (wr_log != NULL) {
        wr_log("\tDetermined threshold: %d.", *thresh);
        wr_log("Pore3D - Image thresholded successfully in %dm%0.3fs.", p3dGetElapsedTime_min(), p3dGetElapsedTime_sec());
    }

    // Return success:
    return P3D_SUCCESS;


MEM_ERROR:

    if (wr_log != NULL) {
        wr_log("Pore3D - Not enough (contiguous) memory. Program will exit.");
    }

    // Free memory:
    free(hist);
    free(S);
    free(Sbar);
    free(W);
    free(Wbar);
    free(F);

    // Return error:
    return P3D_ERROR;


}
コード例 #19
0
ファイル: cpu.c プロジェクト: kadoma/fms
/**
 * @param
 * @return
 *     FMD_SUCCESS
 *     NODE_ID_INVALID
 *     OPENDIR_FAILED
 *
 * @desc:
 *     Get Single CPU Info
 */
static topo_cpu_t *
fmd_topo_read_cpu(const char *dir, int nodeid, int processorid)
{
    char path[PATH_MAX];
    int fd;
    char buf[8];
    topo_cpu_t *pcpu = NULL;

    /* malloc */
    pcpu = (topo_cpu_t *)malloc(sizeof(topo_cpu_t));
    assert(pcpu != NULL);
    memset(pcpu, 0, sizeof(topo_cpu_t));

    pcpu->cpu_system = 0;
    pcpu->cpu_chassis = nodeid;
    pcpu->cpu_board = 0;

    /* physical_package_id */
    snprintf(path, sizeof(path), "%s/%s", dir,
            "topology/physical_package_id");
    fd = open(path, O_RDONLY);
    if(fd < 0) {
        wr_log("",WR_LOG_ERROR,"OPEN %s failed ",path);
        return NULL;
    }
    if(read(fd, &buf, sizeof(buf)) < 0) {
        close(fd);
        wr_log("",WR_LOG_ERROR,"read %s failed ",path);
        return NULL;
    }
    close(fd);
    //pcpu->cpu_socket = buf - '0';
    pcpu->cpu_socket = atoi(buf);
    /* core id */
    snprintf(path, sizeof(path), "%s/%s", dir,
            "topology/core_id");
    fd = open(path, O_RDONLY);
    if(fd < 0) {
        wr_log("",WR_LOG_ERROR,"OPEN %s failed ",path);
        return NULL;
    }
    if(read(fd, &buf, sizeof(buf)) < 0) {
        wr_log("",WR_LOG_ERROR,"read %s failed ",path);
        close(fd);
        return NULL;
    }
    close(fd);
    //pcpu->cpu_core = buf - '0';
    pcpu->cpu_core = atoi(buf);

    /* thread id */
    pcpu->cpu_thread = 0;

    /* topoclass */
    pcpu->cpu_topoclass = TOPO_PROCESSOR;

    /* processor id */
    pcpu->processor = processorid;

    return pcpu;
}
コード例 #20
0
ファイル: disk_evtsrc.c プロジェクト: kadoma/fms
struct list_head *
disk_probe(evtsrc_module_t * emp)
{
	struct list_head *head = nvlist_head_alloc();

	char fullpath[64] = {0};
    char buff[LINE_MAX] = {0};
    char fullclass[128] = {0};
    char cmd[128] = {0};
    
    sprintf(cmd, "df -h|awk '{print $1}'|grep '/dev'");
    FILE *fstream = popen(cmd,"r");
    if(fstream == NULL)
    {
        wr_log("stderr",WR_LOG_ERROR,"execute command failed: %s",strerror(errno));
		return NULL;
    }	
//avoid boot partition------start----
	char bootdev[64] = {0};
	char buff1[LINE_MAX] = {0};
	char cmd1[128] = {0};
	sprintf(cmd1, "df -h| grep '/boot'|awk '{print $1}'");
	FILE *fstream1 = popen(cmd1,"r");
	if(fstream1== NULL)
    {
        wr_log("stderr",WR_LOG_ERROR,"execute command failed: %s",strerror(errno));
		return NULL;
    }
	if(fgets(buff1, sizeof(buff1),fstream1) != NULL){
		memset(bootdev, 0, sizeof(bootdev));
		strncpy(bootdev, buff1, strlen(buff1)-1);
	}
//avoid boot partition------end----	
    while(fgets(buff, sizeof(buff),fstream) != NULL)
	{
	    memset(fullpath, 0, sizeof(fullpath));
		strncpy(fullpath, buff, strlen(buff)-1);

	    if(disk_space_check(fullpath) == 1 && strcmp(fullpath, bootdev) != 0)
	    {
		    memset(fullclass, 0, sizeof(fullclass));
		    sprintf(fullclass,"%s.disk.space-insufficient", FM_EREPORT_CLASS);
		    nvlist_t *nvl = nvlist_alloc();
            
		    if(nvl == NULL)
            {
		        wr_log("stderr",WR_LOG_ERROR, "DISK: out of memory\n");
				pclose(fstream);
			    return NULL;
		    }
            nvl->evt_id = 1;
		    disk_fm_event_post(head, nvl, fullclass, fullpath);
        }

        int len = strlen(fullpath);
        char n = fullpath[len - 1];
        int nn = atoi(&n);
        if(nn >= 1 && nn <= 9)
            fullpath[len -1] = '\0';
        
		if(disk_unhealthy_check(fullpath))
        {
			memset(fullclass, 0, sizeof(fullclass));
            sprintf(fullclass,"%s.disk.unhealthy", FM_EREPORT_CLASS);
            
            nvlist_t *nvl = nvlist_alloc();
			if(nvl == NULL) {
				wr_log("stderr",WR_LOG_ERROR,"DISK: out of memory\n");
				pclose(fstream);
				return NULL;
			}
            nvl->evt_id = 2;
			disk_fm_event_post(head, nvl, fullclass, fullpath);
		}
				
		if(disk_temperature_check(fullpath))
        {
		    memset(fullclass, 0, sizeof(fullclass));
			sprintf(fullclass,"%s.disk.over-temperature", FM_EREPORT_CLASS);
                
			nvlist_t *nvl = nvlist_alloc();
			if(nvl == NULL){
			    wr_log("stderr",WR_LOG_ERROR,"DISK: out of memory\n");
				pclose(fstream);
				return NULL;
			}
            // 3 temp fault
            nvl->evt_id = 3;
			disk_fm_event_post(head, nvl, fullclass, fullpath);
		}
    }
    pclose(fstream1);
	pclose(fstream);
	return head;
}
コード例 #21
0
int p3dSijbersPostnovRingRemover2D_16(
	unsigned short* in_im,
	unsigned short* out_im,
	const int dimx,
	const int dimy,
	const double centerX,
	const double centerY,
	const int winsize,
	const double in_thresh,
	const int iterations,
	const double precision,
	const int bit12,
	unsigned char* mask_im,
	int (*wr_log)(const char*, ...),
	int (*wr_progress)(const int, ...)
	) 
{
	int i, j, k, it_ct; // generic counters
	double sum, sqrsum;

	double mean, variance;
	double tmp_val;
	double thresh;

	// Polar images:
	unsigned short* p_in_im = NULL; // no need for malloc
	unsigned char* p_mask_im = NULL; // no need for malloc
	unsigned short* c_out_im = NULL; // no need for malloc

	int p_dim;

	// Matrix:
	double* matrix;
	int* matrix_mask;
	double* column;
	int ct;
	int row_ct;
	int prev_rowct = 0;

	// Artifacts vectors:
	double* loc_art;
	double* glob_art;
	int* glob_mask;


	// Start tracking computational time:
	if (wr_log != NULL) {
		p3dResetStartTime();
		wr_log("Pore3D - Applying Sijbers and Postnov ring remover...");
		wr_log("\tCenter of rings: [%0.1f,%0.1f].", centerX, centerY);
		wr_log("\tWinsize: %d.", winsize);
		wr_log("\tThreshold: %0.3f.", in_thresh);
		wr_log("\tIterations: %d.", iterations);
		if (bit12 == P3D_TRUE)
			wr_log("\t12-bit images flag: true.");
		else
			wr_log("\t12-bit images flag: false.");
		if (mask_im != NULL)
			wr_log("\tMask adopted.");        
		wr_log("\tPolar/Cartesian precision: %0.3f.", precision);
	}

	// Set the correct threshold value:
	if (bit12 == P3D_TRUE)
		thresh = in_thresh * 4096.0;
	else
		thresh = in_thresh * 65536.0;


	// STEP2: Transform in polar coordinates. Remember that memory allocation
	// for output images is performed within the procedure.

	p3dCartesian2polar_16(in_im, &p_in_im, dimx, dimy, centerX, centerY, precision, &p_dim);
	if (mask_im != NULL) {
		p3dCartesian2polar_8(mask_im, &p_mask_im, dimx, dimy, centerX, centerY, precision, &p_dim);
	}


	// STEP3: Artifact template selection.

	// Allocate dynamic memory:
	loc_art = (double*) calloc(winsize, sizeof (double));


	// Matrix should be a dynamic structure (i.e. a list of array) but for
	// performance reasons we adopt a matrix allocated with the maximum
	// dimensions (worst case):
	matrix = (double*) calloc(winsize*p_dim, sizeof (double));
	/**/matrix_mask = (int*) malloc(p_dim * sizeof (int));

	// Now that we know the dimensions of polar image we can allocate
	// the global artifacts vector:
	glob_art = (double*) malloc(p_dim * sizeof (double));
	glob_mask = (int*) malloc(p_dim * sizeof (int));

	for (it_ct = 0; it_ct < iterations; it_ct++) {
		// Initializations at every iterations:
		prev_rowct = 0;
		memset(loc_art, 0, winsize * sizeof (double));
		memset(glob_art, 0, p_dim * sizeof (double));
		memset(glob_mask, 0, p_dim * sizeof (int)); // init to 0 (false)

		// Within a sliding window:
		for (i = 0; i < (p_dim - winsize); i++) {
			// Init counters:
			ct = 0;
			row_ct = 0;

			// Initialization of matrix mask:
			/**/memset(matrix_mask, 0, p_dim * sizeof (int)); // init to 0 (false)

			// For each line of polar image:
#pragma omp parallel for private(sum, sqrsum, mean, variance, k) reduction (+ : row_ct)
			for (j = 0; j < p_dim; j++) {
				// If computation of sum and squared sum is meaningful:
				if (_getSums_16(p_in_im, mask_im, p_mask_im, p_dim, i, j, winsize, &sum, &sqrsum)) {
					// Compute mean and variance of the line:
					mean = sum / winsize;
					variance = sqrsum / winsize - mean*mean;

					// If variance is below threshold:
					if ((variance < thresh) && (variance > 0)) {
						// Set that current position in matrix is meaningful:
						/**/matrix_mask[j] = 1; // true

						// For each element subtract mean and add the line
						// to the matrix:
						for (k = i; k < (i + winsize); k++) {
							// Subtract mean from the line and add
							// it to a matrix
							/**///matrix[ct++] = p_in_im[ I(k,j,p_dim) ] - mean;
							matrix[ I2(k - i, j, winsize) ] = p_in_im[ I2(k, j, p_dim) ] - mean;
						}

						// Increment the number of lines that meets the
						// homogeneity criterium:
						row_ct++;
					}
				}
			}


			// Compute median for each column and store the value in the
			// artifact vector for this sliding window:

			// Now that we know the number of rows that meets homogeneity
			// criterium we can allocate memory for a column:
			if (row_ct > 0) {
				// Allocate memory for the column (no OpenMP):
				//column = (double*) malloc( row_ct*sizeof(double) );

#pragma omp parallel for private(k, ct, column)
				for (j = 0; j < winsize; j++) {
					// Allocate memory for the column:
					column = (double*) malloc(row_ct * sizeof (double));

					// Fill the column array:
					/*for ( k = 0; k < row_ct; k++ )
					{
					column[k] = matrix[ I(j,k,winsize) ];
					}*/
					ct = 0;
					for (k = 0; k < p_dim; k++) {
						if (matrix_mask[k] == 1)
							column[ct++] = matrix[ I2(j, k, winsize) ];
					}

					// Order the array:
					/*qsort( column, row_ct, sizeof(double), _cmp);

					// Get the median and put in "local" artifact vector:
					loc_art[j] = column[ row_ct / 2 ];*/
					loc_art[j] = P3DISIJBERSPOSTNOV_RINGREMOVER_MEDIAN(column, row_ct);

					// Free memory for the column:
					free(column);
				}

				// Free memory for the column (no OpenMP):
				//free(column);
			}
			/*else
			{
			// Set to zero "local" artifact vector:
			memset(loc_art,0,winsize*sizeof(double));
			}*/


			// Unwrap the "local" artifact vector of dimension W to the
			// "global" artifact vector of dimension P_DIM using the rule
			// based on number of rows that meets the homogeneity criterium:
			for (k = 0; k < winsize; k++) {
				if ((row_ct > prev_rowct) || (glob_mask[k] == 0)) {
					glob_art[k + i] = loc_art[k];
					glob_mask[k + i] = 1; // true
				}
			}

			// Set the previous equal to the current:
			prev_rowct = row_ct;
		}

		// The "global" artifact template vector is subtracted from each
		// row of the polar image P:
		if (mask_im != NULL) {
#pragma omp parallel for private(i, tmp_val)
			for (j = 0; j < p_dim; j++) {
				for (i = 0; i < p_dim; i++) {
					if (p_mask_im[ I2(i, j, p_dim) ] != 0) {
						// Take care of intensity bounds:
						tmp_val = p_in_im[ I2(i, j, p_dim) ] - glob_art[i];

						if (tmp_val < 0.0) tmp_val = 0.0;
						if (tmp_val > USHRT_MAX) tmp_val = USHRT_MAX;

						p_in_im[ I2(i, j, p_dim) ] = (unsigned short) tmp_val;
					}
				}
			}
		} else {
#pragma omp parallel for private(i, tmp_val)
			for (j = 0; j < p_dim; j++) {
				for (i = 0; i < p_dim; i++) {
					// Take care of intensity bounds:
					tmp_val = p_in_im[ I2(i, j, p_dim) ] - glob_art[i];

					if (tmp_val < 0.0) tmp_val = 0.0;
					if (tmp_val > USHRT_MAX) tmp_val = USHRT_MAX;

					p_in_im[ I2(i, j, p_dim) ] = (unsigned short) tmp_val;
				}
			}
		}
	}


	// Return in cartesian coordinates:
	p3dPolar2cartesian_16(p_in_im, &c_out_im, p_dim, centerX, centerY, dimx, dimy);

	// Copy C_OUT_IM to the output of the procedure:
	memcpy(out_im, c_out_im, dimx * dimy * sizeof (unsigned short));

	// Free memory:
	free(glob_art);
	free(glob_mask);
	free(loc_art);
	free(matrix);
	free(matrix_mask);

	free(p_in_im);
	free(c_out_im);

	if (mask_im != NULL) {
		free(p_mask_im);
	}

	// Print elapsed time (if required):
	if (wr_log != NULL) {
		wr_log("Pore3D - Sijbers and Postnov ring remover applied successfully in %dm%0.3fs.", p3dGetElapsedTime_min(), p3dGetElapsedTime_sec());
	}


	return P3D_SUCCESS;

}
コード例 #22
0
ファイル: fmd_log.c プロジェクト: kadoma/fms
/**
 * fmd_log_close
 *
 * @param: log file fd
 * @return:
 */
void
fmd_log_close(int fd)
{
	if (fd >= 0 && close(fd) != 0)
		wr_log("", WR_LOG_ERROR, "FMD: failed to close log file: fd=%d.\n", fd);
}