Esempio n. 1
0
bool 
proc_probe(pid_t pid, int opt, proc_t * const pproc)
{
    FUNC_BEGIN("%d,%d,%p", pid, opt, pproc);
    assert(pproc);
    
    if (pproc == NULL)
    {
        FUNC_RET("%d", false);
    }
    
#ifdef HAVE_PROCFS
    /* Grab preliminary information from procfs */
    
    if (!check_procfs(pid))
    {
        WARNING("procfs entries missing or invalid");
        FUNC_RET("%d", false);
    }
    
    char buffer[4096];    
    sprintf(buffer, PROCFS "/%d/stat", pid);
   
    int fd = open(buffer, O_RDONLY);
    if (fd < 0)
    {
        WARNING("procfs stat missing or unaccessable");
        FUNC_RET("%d", false);
    }
    
    int len = read(fd, buffer, sizeof(buffer) - 1);
    
    close(fd);

    if (len < 0)
    {
        WARNING("failed to grab stat from procfs");
        FUNC_RET("%d", false);
    }

    buffer[len] = '\0';
    
    /* Extract interested information */
    struct tms tm;
    int offset = 0;
    char * token = buffer;
    do
    {
        switch (offset++)
        {
        case  0:                /* pid */
            sscanf(token, "%d", &pproc->pid);
            break;
        case  1:                /* comm */
            break;
        case  2:                /* state */
            sscanf(token, "%c", &pproc->state);
            break;
        case  3:                /* ppid */
            sscanf(token, "%d", &pproc->ppid);
            break;
        case  4:                /* pgrp */
        case  5:                /* session */
        case  6:                /* tty_nr */
        case  7:                /* tty_pgrp */
            break;
        case  8:                /* flags */
            sscanf(token, "%lu", &pproc->flags);
            break;
        case  9:                /* min_flt */
            sscanf(token, "%lu", &pproc->minflt);
            break;
        case 10:                /* cmin_flt */
            sscanf(token, "%lu", &pproc->cminflt);
            break;
        case 11:                /* maj_flt */
            sscanf(token, "%lu", &pproc->majflt);
            break;
        case 12:                /* cmaj_flt */
            sscanf(token, "%lu", &pproc->cmajflt);
            break;
        case 13:                /* utime */
            sscanf(token, "%lu", &tm.tms_utime);
            break;
        case 14:                /* stime */
            sscanf(token, "%lu", &tm.tms_stime);
            break;
        case 15:                /* cutime */
            sscanf(token, "%ld", &tm.tms_cutime);
            break;
        case 16:                /* cstime */
            sscanf(token, "%ld", &tm.tms_cstime);
            break;
        case 17:                /* priority */
        case 18:                /* nice */
        case 19:                /* num_threads (since 2.6 kernel) */
        case 20:                /* it_real_value */
        case 21:                /* start_time */
            break;
        case 22:                /* vsize */
            sscanf(token, "%lu", &pproc->vsize);
            break;
        case 23:                /* rss */
            sscanf(token, "%ld", &pproc->rss);
            break;
        case 24:                /* rlim_rss */
        case 25:                /* start_code */
            sscanf(token, "%lu", &pproc->start_code);
            break;
        case 26:                /* end_code */
            sscanf(token, "%lu", &pproc->end_code);
            break;
        case 27:                /* start_stack */
            sscanf(token, "%lu", &pproc->start_stack);
            break;
        case 28:                /* esp */
        case 29:                /* eip */
        case 30:                /* pending_signal */
        case 31:                /* blocked_signal */
        case 32:                /* sigign */
        case 33:                /* sigcatch */
        case 34:                /* wchan */
        case 35:                /* nswap */
        case 36:                /* cnswap */
        case 37:                /* exit_signal */
        case 38:                /* processor */
        case 39:                /* rt_priority */
        case 40:                /* policy */
        default:
            break;
        }
    } while (strsep(&token, " ") != NULL);
    
    long CLK_TCK = sysconf(_SC_CLK_TCK);
    
    #define TS_UPDATE_CLK(pts,clk) \
    {{{ \
        (pts)->tv_sec = ((time_t)((clk) / CLK_TCK)); \
        (pts)->tv_nsec = (1000000000UL * ((clk) % (CLK_TCK)) / CLK_TCK ); \
    }}} /* TS_UPDATE_CLK */
    
    TS_UPDATE_CLK(&pproc->utime, tm.tms_utime);
    TS_UPDATE_CLK(&pproc->stime, tm.tms_stime);
    TS_UPDATE_CLK(&pproc->cutime, tm.tms_cutime);
    TS_UPDATE_CLK(&pproc->cstime, tm.tms_cstime);
    
    DBG("proc.pid                    % 10d", pproc->pid);
    DBG("proc.ppid                   % 10d", pproc->ppid);
    DBG("proc.state                           %c", pproc->state);
    DBG("proc.flags          0x%016lx", pproc->flags);
    DBG("proc.utime                  %010lu", ts2ms(pproc->utime));
    DBG("proc.stime                  %010lu", ts2ms(pproc->stime));
    DBG("proc.cutime                 % 10ld", ts2ms(pproc->cutime));
    DBG("proc.cstime                 % 10ld", ts2ms(pproc->cstime));
    DBG("proc.minflt                 %010lu", pproc->minflt);
    DBG("proc.cminflt                %010lu", pproc->cminflt);
    DBG("proc.majflt                 %010lu", pproc->majflt);
    DBG("proc.cmajflt                %010lu", pproc->cmajflt);
    DBG("proc.vsize                  %010lu", pproc->vsize);
    DBG("proc.rss                    % 10ld", pproc->rss);

#else
#warning "proc_probe() requires procfs"
#endif /* HAVE_PROCFS */

    trace_proxy_t __trace = TRACE_PROXY(pproc);
    
    /* Inspect process registers */
    if (opt & PROBE_REGS)
    {
        if (__trace(T_GETREGS, NULL, pproc) != 0)
        {
            FUNC_RET("%d", false);
        }
#ifdef __x86_64__
        DBG("regs.r15            0x%016lx", pproc->regs.r15);
        DBG("regs.r14            0x%016lx", pproc->regs.r14);
        DBG("regs.r13            0x%016lx", pproc->regs.r13);
        DBG("regs.r12            0x%016lx", pproc->regs.r12);
        DBG("regs.rbp            0x%016lx", pproc->regs.rbp);
        DBG("regs.rbx            0x%016lx", pproc->regs.rbx);
        DBG("regs.r11            0x%016lx", pproc->regs.r11);
        DBG("regs.r10            0x%016lx", pproc->regs.r10);
        DBG("regs.r9             0x%016lx", pproc->regs.r9);
        DBG("regs.r8             0x%016lx", pproc->regs.r8);
        DBG("regs.rax            0x%016lx", pproc->regs.rax);
        DBG("regs.rcx            0x%016lx", pproc->regs.rcx);
        DBG("regs.rdx            0x%016lx", pproc->regs.rdx);
        DBG("regs.rsi            0x%016lx", pproc->regs.rsi);
        DBG("regs.rdi            0x%016lx", pproc->regs.rdi);
        DBG("regs.orig_rax       0x%016lx", pproc->regs.orig_rax);
        DBG("regs.rip            0x%016lx", pproc->regs.rip);
        DBG("regs.cs             0x%016lx", pproc->regs.cs);
        DBG("regs.eflags         0x%016lx", pproc->regs.eflags);
        DBG("regs.rsp            0x%016lx", pproc->regs.rsp);
        DBG("regs.ss             0x%016lx", pproc->regs.ss);
        DBG("regs.fs_base        0x%016lx", pproc->regs.fs_base);
        DBG("regs.gs_base        0x%016lx", pproc->regs.gs_base);
        DBG("regs.ds             0x%016lx", pproc->regs.ds);
        DBG("regs.es             0x%016lx", pproc->regs.es);
        DBG("regs.fs             0x%016lx", pproc->regs.fs);
        DBG("regs.gs             0x%016lx", pproc->regs.gs);
#else /* __i386__ */
        DBG("regs.ebx            0x%016lx", pproc->regs.ebx);
        DBG("regs.ecx            0x%016lx", pproc->regs.ecx);
        DBG("regs.edx            0x%016lx", pproc->regs.edx);
        DBG("regs.esi            0x%016lx", pproc->regs.esi);
        DBG("regs.edi            0x%016lx", pproc->regs.edi);
        DBG("regs.ebp            0x%016lx", pproc->regs.ebp);
        DBG("regs.eax            0x%016lx", pproc->regs.eax);
        DBG("regs.xds            0x%016lx", pproc->regs.xds);
        DBG("regs.xes            0x%016lx", pproc->regs.xes);
        DBG("regs.xfs            0x%016lx", pproc->regs.xfs);
        DBG("regs.xgs            0x%016lx", pproc->regs.xgs);
        DBG("regs.orig_eax       0x%016lx", pproc->regs.orig_eax);
        DBG("regs.eip            0x%016lx", pproc->regs.eip);
        DBG("regs.xcs            0x%016lx", pproc->regs.xcs);
        DBG("regs.eflags         0x%016lx", pproc->regs.eflags);
        DBG("regs.esp            0x%016lx", pproc->regs.esp);
        DBG("regs.xss            0x%016lx", pproc->regs.xss);
#endif /* __x86_64__ */
    }
    
    /* Inspect current instruction */
    if (opt & PROBE_OP)
    {

#ifdef __x86_64__
        pproc->op = pproc->regs.rip;
#else /* __i386__ */
        pproc->op = pproc->regs.eip;
#endif /* __x86_64__ */

        if (!pproc->tflags.single_step)
        {
            pproc->op -= 2; // shift back 16bit in syscall tracing mode
        }
        
        if (__trace(T_GETDATA, (long *)&pproc->op, pproc) != 0)
        {
            FUNC_RET("%d", false);
        }
        
        DBG("proc.op             0x%016lx", pproc->op);
    }
    
    /* Inspect signal information */
    if (opt & PROBE_SIGINFO)
    {
        if (__trace(T_GETSIGINFO, NULL, pproc) != 0)
        {
            FUNC_RET("%d", false);
        }

        DBG("proc.siginfo.si_signo       % 10d", pproc->siginfo.si_signo);
        DBG("proc.siginfo.si_errno       % 10d", pproc->siginfo.si_errno);
        DBG("proc.siginfo.si_code        % 10d", pproc->siginfo.si_code);
    }
    
    FUNC_RET("%d", true);
}
static s32 goodix_tool_read( char *page, char **start, off_t off, int count, int *eof, void *data )
{
    if (2 == cmd_head.wr)
    {
        //memcpy(page, IC_TYPE, cmd_head.data_len);
        memcpy(page, IC_TYPE, sizeof(IC_TYPE_NAME));
        page[sizeof(IC_TYPE_NAME)] = 0;

        DEBUG("Return ic type:%s len:%d\n", page, (s32)cmd_head.data_len);
        return cmd_head.data_len;
        //return sizeof(IC_TYPE_NAME);
    }
    else if (cmd_head.wr % 2)
    {
        return fail;
    }
    else if (!cmd_head.wr)
    {
        u16 len = 0;
        s16 data_len = 0;
        u16 loc = 0;
        
        if (1 == cmd_head.flag)
        {
            if (fail == comfirm())
            {
                WARNING("[READ]Comfirm fail!\n");
                return fail;
            }
        }
        else if (2 == cmd_head.flag)
        {
            //Need interrupt!
        }

        memcpy(cmd_head.data, cmd_head.addr, cmd_head.addr_len);

        DEBUG("[CMD HEAD DATA] ADDR:0x%02x%02x\n", cmd_head.data[0], cmd_head.data[1]);
        DEBUG("[CMD HEAD ADDR] ADDR:0x%02x%02x\n", cmd_head.addr[0], cmd_head.addr[1]);
        
        if (cmd_head.delay)
        {
            msleep(cmd_head.delay);
        }

        data_len = cmd_head.data_len;
        while(data_len > 0)
        {
            if (data_len > DATA_LENGTH)
            {
                len = DATA_LENGTH;
            }
            else
            {
                len = data_len;
            }
            data_len -= DATA_LENGTH;

            if (tool_i2c_read(cmd_head.data, len) <= 0)
            {
                WARNING("[READ]Read data failed!\n");
                return fail;
            }

            memcpy(&page[loc], &cmd_head.data[ADDR_MAX_LENGTH], len);
            loc += len;

            //DEBUG_ARRAY(&cmd_head.data[ADDR_MAX_LENGTH], len);
            DEBUG_ARRAY(page, len);
        }
    }

    return cmd_head.data_len;
}
Esempio n. 3
0
Decode_Status
    VaapiDecoderBase::setupVA(uint32_t numSurface, VAProfile profile)
{
    INFO("base: setup VA");

    if (m_enableNativeBuffersFlag == true) {
        numSurface = 20;        //NATIVE_WINDOW_COUNT;
    }

    if (m_VAStarted) {
        return DECODE_SUCCESS;
    }

    if (m_display != NULL) {
        WARNING("VA is partially started.");
        return DECODE_FAIL;
    }

    m_display = VaapiDisplay::create(m_externalDisplay);

    if (!m_display) {
        ERROR("failed to create display");
        return DECODE_FAIL;
    }

    VAConfigAttrib attrib;
    attrib.type = VAConfigAttribRTFormat;
    attrib.value = VA_RT_FORMAT_YUV420;


    ConfigPtr config = VaapiConfig::create(m_display, profile, VAEntrypointVLD,&attrib, 1);
    if (!config) {
        ERROR("failed to create config");
        return DECODE_FAIL;
    }

    m_configBuffer.surfaceNumber = numSurface;
    m_surfacePool = VaapiDecSurfacePool::create(m_display, &m_configBuffer);
    DEBUG("surface pool is created");
    if (!m_surfacePool)
        return DECODE_FAIL;
    std::vector<VASurfaceID> surfaces;
    m_surfacePool->getSurfaceIDs(surfaces);
    if (surfaces.empty())
        return DECODE_FAIL;
    int size = surfaces.size();
    m_context = VaapiContext::create(config,
                                       m_videoFormatInfo.width,
                                       m_videoFormatInfo.height,
                                       0, &surfaces[0], size);

    if (!m_context) {
        ERROR("create context failed");
        return DECODE_FAIL;
    }

    if (!m_display->setRotation(m_configBuffer.rotationDegrees)) {
        WARNING("set rotation failed");
    }


    if (!(m_configBuffer.flag & USE_NATIVE_GRAPHIC_BUFFER)) {
        m_videoFormatInfo.surfaceWidth = m_videoFormatInfo.width;
        m_videoFormatInfo.surfaceHeight = m_videoFormatInfo.height;
    }

    m_VAStarted = true;
    return DECODE_SUCCESS;
}
Esempio n. 4
0
static int apache_read_host (user_data_t *user_data) /* {{{ */
{
	int i;

	char *ptr;
	char *saveptr;
	char *lines[16];
	int   lines_num = 0;

	char *fields[4];
	int   fields_num;

	apache_t *st;

	st = user_data->data;

	assert (st->url != NULL);
	/* (Assured by `config_add') */

	if (st->curl == NULL)
	{
		int status;

		status = init_host (st);
		if (status != 0)
			return (-1);
	}
	assert (st->curl != NULL);

	st->apache_buffer_fill = 0;
	if (curl_easy_perform (st->curl) != CURLE_OK)
	{
		ERROR ("apache: curl_easy_perform failed: %s",
				st->apache_curl_error);
		return (-1);
	}

	/* fallback - server_type to apache if not set at this time */
	if (st->server_type == -1)
	{
		WARNING ("apache plugin: Unable to determine server software "
				"automatically. Will assume Apache.");
		st->server_type = APACHE;
	}

	ptr = st->apache_buffer;
	saveptr = NULL;
	while ((lines[lines_num] = strtok_r (ptr, "\n\r", &saveptr)) != NULL)
	{
		ptr = NULL;
		lines_num++;

		if (lines_num >= 16)
			break;
	}

	for (i = 0; i < lines_num; i++)
	{
		fields_num = strsplit (lines[i], fields, 4);

		if (fields_num == 3)
		{
			if ((strcmp (fields[0], "Total") == 0)
					&& (strcmp (fields[1], "Accesses:") == 0))
				submit_derive ("apache_requests", "",
						atoll (fields[2]), st);
			else if ((strcmp (fields[0], "Total") == 0)
					&& (strcmp (fields[1], "kBytes:") == 0))
				submit_derive ("apache_bytes", "",
						1024LL * atoll (fields[2]), st);
		}
		else if (fields_num == 2)
		{
			if (strcmp (fields[0], "Scoreboard:") == 0)
				submit_scoreboard (fields[1], st);
			else if ((strcmp (fields[0], "BusyServers:") == 0) /* Apache 1.* */
					|| (strcmp (fields[0], "BusyWorkers:") == 0) /* Apache 2.* */)
				submit_gauge ("apache_connections", NULL, atol (fields[1]), st);
			else if ((strcmp (fields[0], "IdleServers:") == 0) /* Apache 1.x */
					|| (strcmp (fields[0], "IdleWorkers:") == 0) /* Apache 2.x */)
				submit_gauge ("apache_idle_workers", NULL, atol (fields[1]), st);
		}
	}

	st->apache_buffer_fill = 0;

	return (0);
} /* }}} int apache_read_host */
Esempio n. 5
0
// Консоль любит глючить, при попытках запроса более определенного количества ячеек.
// MAX_CONREAD_SIZE подобрано экспериментально
BOOL ReadConsoleOutputEx(HANDLE hOut, CHAR_INFO *pData, COORD bufSize, SMALL_RECT rgn)
{
	BOOL lbRc = FALSE;

	DWORD nTick1 = GetTickCount(), nTick2 = 0, nTick3 = 0, nTick4 = 0, nTick5 = 0;

	static bool bDBCS = false, bDBCS_Checked = false;
	if (!bDBCS_Checked)
	{
		bDBCS = (GetSystemMetrics(SM_DBCSENABLED) != 0);
		bDBCS_Checked = true;
	}

	bool   bDBCS_CP = bDBCS;
	LPCSTR szLeads = NULL;
	UINT   MaxCharSize = 0;
	DWORD  nCP, nCP1, nMode;

	if (bDBCS)
	{
		nCP = GetConsoleOutputCP();
		nCP1 = GetConsoleCP();
		GetConsoleMode(hOut, &nMode);

		szLeads = GetCpInfoLeads(nCP, &MaxCharSize);
		if (!szLeads || !*szLeads || MaxCharSize < 2)
		{
			bDBCS_CP = false;
		}
	}

	size_t nBufWidth = bufSize.X;
	int nWidth = (rgn.Right - rgn.Left + 1);
	int nHeight = (rgn.Bottom - rgn.Top + 1);
	int nCurSize = nWidth * nHeight;

	_ASSERTE(bufSize.X >= nWidth);
	_ASSERTE(bufSize.Y >= nHeight);
	_ASSERTE(rgn.Top>=0 && rgn.Bottom>=rgn.Top);
	_ASSERTE(rgn.Left>=0 && rgn.Right>=rgn.Left);

	//MSectionLock RCS;
	//if (gpSrv->pReqSizeSection && !RCS.Lock(gpSrv->pReqSizeSection, TRUE, 30000))
	//{
	//	_ASSERTE(FALSE);
	//	SetLastError(ERROR_INVALID_PARAMETER);
	//	return FALSE;

	//}

	COORD bufCoord = {0,0};
	DWORD dwErrCode = 0;

	nTick2 = GetTickCount();

	if (!bDBCS_CP && (nCurSize <= MAX_CONREAD_SIZE))
	{
		if (ReadConsoleOutputW(hOut, pData, bufSize, bufCoord, &rgn))
			lbRc = TRUE;
		nTick3 = GetTickCount();
	}

	if (!lbRc)
	{
		// Придется читать построчно
		
		// Теоретически - можно и блоками, но оверхед очень маленький, а велик
		// шанс обломаться, если консоль "глючит". Поэтому построчно...

		//bufSize.X = TextWidth;
		bufSize.Y = 1;
		bufCoord.X = 0; bufCoord.Y = 0;
		//rgn = gpSrv->sbi.srWindow;

		int Y1 = rgn.Top;
		int Y2 = rgn.Bottom;

		CHAR_INFO* pLine = pData;
		if (!bDBCS_CP)
		{
			for (int y = Y1; y <= Y2; y++, rgn.Top++, pLine+=nBufWidth)
			{
				nTick3 = GetTickCount();
				rgn.Bottom = rgn.Top;
				lbRc = ReadConsoleOutputW(hOut, pLine, bufSize, bufCoord, &rgn);
				if (!lbRc)
				{
					dwErrCode = GetLastError();
					_ASSERTE(FALSE && "ReadConsoleOutputW failed in MyReadConsoleOutput");
					break;
				}
				nTick4 = GetTickCount();
			}
		}
		else
		{
			DWORD nAttrsMax = bufSize.X;
			DWORD nCharsMax = nAttrsMax/* *4 */; // -- максимум там вроде на некоторых CP - 4 байта
			wchar_t* pszChars = (wchar_t*)malloc(nCharsMax*sizeof(*pszChars));
			char* pszCharsA = (char*)malloc(nCharsMax*sizeof(*pszCharsA));
			WORD* pnAttrs = (WORD*)malloc(bufSize.X*sizeof(*pnAttrs));
			if (pszChars && pszCharsA && pnAttrs)
			{
				COORD crRead = {rgn.Left,Y1};
				DWORD nChars, nAttrs, nCharsA;
				CHAR_INFO* pLine = pData;
				for (; crRead.Y <= Y2; crRead.Y++, pLine+=nBufWidth)
				{
					nTick3 = GetTickCount();
					rgn.Bottom = rgn.Top;

					nChars = nCharsA = nAttrs = 0;
					BOOL lbRcTxt = ReadConsoleOutputCharacterA(hOut, pszCharsA, nCharsMax, crRead, &nCharsA);
					dwErrCode = GetLastError();
					if (!lbRcTxt || !nCharsA)
					{
						nCharsA = 0;
						lbRcTxt = ReadConsoleOutputCharacterW(hOut, pszChars, nCharsMax, crRead, &nChars);
						dwErrCode = GetLastError();
					}
					BOOL lbRcAtr = ReadConsoleOutputAttribute(hOut, pnAttrs, bufSize.X, crRead, &nAttrs);
					dwErrCode = GetLastError();
					
					lbRc = lbRcTxt && lbRcAtr;

					if (!lbRc)
					{
						dwErrCode = GetLastError();
						_ASSERTE(FALSE && "ReadConsoleOutputAttribute failed in MyReadConsoleOutput");

						CHAR_INFO* p = pLine;
						for (size_t i = 0; i < nAttrsMax; ++i, ++p)
						{
							p->Attributes = 4; // red on black
							p->Char.UnicodeChar = 0xFFFE; // not a character
						}

						break;
					}
					else
					{
						if (nCharsA)
						{
							nChars = MultiByteToWideChar(nCP, 0, pszCharsA, nCharsA, pszChars, nCharsMax);
						}
						CHAR_INFO* p = pLine;
						wchar_t* psz = pszChars;
						WORD* pn = pnAttrs;
						//int i = nAttrsMax;
						//while ((i--) > 0)
						//{
						//	p->Attributes = *(pn++);
						//	p->Char.UnicodeChar = *(psz++);
						//	p++;
						//}
						size_t x1 = min(nChars,nAttrsMax);
						size_t x2 = nAttrsMax;
						for (size_t i = 0; i < x1; ++i, ++p)
						{
							p->Attributes = *pn;
							p->Char.UnicodeChar = *psz;

							WARNING("Некорректно! pn может указывать на начало блока DBCS/QBCS");
							pn++; // += MaxCharSize;
							psz++;
						}
						WORD nLastAttr = pnAttrs[max(0,(int)nAttrs-1)];
						for (size_t i = x1; i < x2; ++i, ++p)
						{
							p->Attributes = nLastAttr;
							p->Char.UnicodeChar = L' ';
						}
					}
					nTick4 = GetTickCount();
				}
			}
			SafeFree(pszChars);
			SafeFree(pszCharsA);
			SafeFree(pnAttrs);
		}

		nTick5 = GetTickCount();
	}

	UNREFERENCED_PARAMETER(nTick1);
	UNREFERENCED_PARAMETER(nTick2);
	UNREFERENCED_PARAMETER(nTick3);
	UNREFERENCED_PARAMETER(nTick4);
	UNREFERENCED_PARAMETER(nTick5);
	return lbRc;
}
Esempio n. 6
0
static int disk_read (void)
{
#if HAVE_IOKIT_IOKITLIB_H
	io_registry_entry_t	disk;
	io_registry_entry_t	disk_child;
	io_iterator_t		disk_list;
	CFDictionaryRef		props_dict;
	CFDictionaryRef		stats_dict;
	CFDictionaryRef		child_dict;
	CFStringRef		tmp_cf_string_ref;
	kern_return_t		status;

	signed long long read_ops;
	signed long long read_byt;
	signed long long read_tme;
	signed long long write_ops;
	signed long long write_byt;
	signed long long write_tme;

	int  disk_major;
	int  disk_minor;
	char disk_name[DATA_MAX_NAME_LEN];
	char disk_name_bsd[DATA_MAX_NAME_LEN];

	/* Get the list of all disk objects. */
	if (IOServiceGetMatchingServices (io_master_port,
				IOServiceMatching (kIOBlockStorageDriverClass),
				&disk_list) != kIOReturnSuccess)
	{
		ERROR ("disk plugin: IOServiceGetMatchingServices failed.");
		return (-1);
	}

	while ((disk = IOIteratorNext (disk_list)) != 0)
	{
		props_dict = NULL;
		stats_dict = NULL;
		child_dict = NULL;

		/* `disk_child' must be released */
		if ((status = IORegistryEntryGetChildEntry (disk, kIOServicePlane, &disk_child))
			       	!= kIOReturnSuccess)
		{
			/* This fails for example for DVD/CD drives.. */
			DEBUG ("IORegistryEntryGetChildEntry (disk) failed: 0x%08x", status);
			IOObjectRelease (disk);
			continue;
		}

		/* We create `props_dict' => we need to release it later */
		if (IORegistryEntryCreateCFProperties (disk,
					(CFMutableDictionaryRef *) &props_dict,
					kCFAllocatorDefault,
					kNilOptions)
				!= kIOReturnSuccess)
		{
			ERROR ("disk-plugin: IORegistryEntryCreateCFProperties failed.");
			IOObjectRelease (disk_child);
			IOObjectRelease (disk);
			continue;
		}

		if (props_dict == NULL)
		{
			DEBUG ("IORegistryEntryCreateCFProperties (disk) failed.");
			IOObjectRelease (disk_child);
			IOObjectRelease (disk);
			continue;
		}

		/* tmp_cf_string_ref doesn't need to be released. */
		tmp_cf_string_ref = (CFStringRef) CFDictionaryGetValue (props_dict,
				CFSTR(kIOBSDNameKey));
		if (!tmp_cf_string_ref)
		{
			DEBUG ("disk plugin: CFDictionaryGetValue("
					"kIOBSDNameKey) failed.");
			CFRelease (props_dict);
			IOObjectRelease (disk_child);
			IOObjectRelease (disk);
			continue;
		}
		assert (CFGetTypeID (tmp_cf_string_ref) == CFStringGetTypeID ());

		memset (disk_name_bsd, 0, sizeof (disk_name_bsd));
		CFStringGetCString (tmp_cf_string_ref,
				disk_name_bsd, sizeof (disk_name_bsd),
				kCFStringEncodingUTF8);
		if (disk_name_bsd[0] == 0)
		{
			ERROR ("disk plugin: CFStringGetCString() failed.");
			CFRelease (props_dict);
			IOObjectRelease (disk_child);
			IOObjectRelease (disk);
			continue;
		}
		DEBUG ("disk plugin: disk_name_bsd = \"%s\"", disk_name_bsd);

		stats_dict = (CFDictionaryRef) CFDictionaryGetValue (props_dict,
				CFSTR (kIOBlockStorageDriverStatisticsKey));

		if (stats_dict == NULL)
		{
			DEBUG ("disk plugin: CFDictionaryGetValue ("
					"%s) failed.",
				       	kIOBlockStorageDriverStatisticsKey);
			CFRelease (props_dict);
			IOObjectRelease (disk_child);
			IOObjectRelease (disk);
			continue;
		}

		if (IORegistryEntryCreateCFProperties (disk_child,
					(CFMutableDictionaryRef *) &child_dict,
					kCFAllocatorDefault,
					kNilOptions)
				!= kIOReturnSuccess)
		{
			DEBUG ("disk plugin: IORegistryEntryCreateCFProperties ("
					"disk_child) failed.");
			IOObjectRelease (disk_child);
			CFRelease (props_dict);
			IOObjectRelease (disk);
			continue;
		}

		/* kIOBSDNameKey */
		disk_major = (int) dict_get_value (child_dict,
			       	kIOBSDMajorKey);
		disk_minor = (int) dict_get_value (child_dict,
			       	kIOBSDMinorKey);
		read_ops  = dict_get_value (stats_dict,
				kIOBlockStorageDriverStatisticsReadsKey);
		read_byt  = dict_get_value (stats_dict,
				kIOBlockStorageDriverStatisticsBytesReadKey);
		read_tme  = dict_get_value (stats_dict,
				kIOBlockStorageDriverStatisticsTotalReadTimeKey);
		write_ops = dict_get_value (stats_dict,
				kIOBlockStorageDriverStatisticsWritesKey);
		write_byt = dict_get_value (stats_dict,
				kIOBlockStorageDriverStatisticsBytesWrittenKey);
		/* This property describes the number of nanoseconds spent
		 * performing writes since the block storage driver was
		 * instantiated. It is one of the statistic entries listed
		 * under the top-level kIOBlockStorageDriverStatisticsKey
		 * property table. It has an OSNumber value. */
		write_tme = dict_get_value (stats_dict,
				kIOBlockStorageDriverStatisticsTotalWriteTimeKey);

		if (use_bsd_name)
			sstrncpy (disk_name, disk_name_bsd, sizeof (disk_name));
		else
			ssnprintf (disk_name, sizeof (disk_name), "%i-%i",
					disk_major, disk_minor);
		DEBUG ("disk plugin: disk_name = \"%s\"", disk_name);

		if ((read_byt != -1LL) || (write_byt != -1LL))
			disk_submit (disk_name, "disk_octets", read_byt, write_byt);
		if ((read_ops != -1LL) || (write_ops != -1LL))
			disk_submit (disk_name, "disk_ops", read_ops, write_ops);
		if ((read_tme != -1LL) || (write_tme != -1LL))
			disk_submit (disk_name, "disk_time",
					read_tme / 1000,
					write_tme / 1000);

		CFRelease (child_dict);
		IOObjectRelease (disk_child);
		CFRelease (props_dict);
		IOObjectRelease (disk);
	}
	IOObjectRelease (disk_list);
/* #endif HAVE_IOKIT_IOKITLIB_H */

#elif KERNEL_LINUX
	FILE *fh;
	char buffer[1024];
	
	char *fields[32];
	int numfields;
	int fieldshift = 0;

	int minor = 0;

	derive_t read_sectors  = 0;
	derive_t write_sectors = 0;

	derive_t read_ops      = 0;
	derive_t read_merged   = 0;
	derive_t read_time     = 0;
	derive_t write_ops     = 0;
	derive_t write_merged  = 0;
	derive_t write_time    = 0;
	int is_disk = 0;

	diskstats_t *ds, *pre_ds;

	if ((fh = fopen ("/proc/diskstats", "r")) == NULL)
	{
		fh = fopen ("/proc/partitions", "r");
		if (fh == NULL)
		{
			ERROR ("disk plugin: fopen (/proc/{diskstats,partitions}) failed.");
			return (-1);
		}

		/* Kernel is 2.4.* */
		fieldshift = 1;
	}

#if HAVE_LIBUDEV
	handle_udev = udev_new();
#endif

	while (fgets (buffer, sizeof (buffer), fh) != NULL)
	{
		char *disk_name;
		char *output_name;
		char *alt_name;

		numfields = strsplit (buffer, fields, 32);

		if ((numfields != (14 + fieldshift)) && (numfields != 7))
			continue;

		minor = atoll (fields[1]);

		disk_name = fields[2 + fieldshift];

		for (ds = disklist, pre_ds = disklist; ds != NULL; pre_ds = ds, ds = ds->next)
			if (strcmp (disk_name, ds->name) == 0)
				break;

		if (ds == NULL)
		{
			if ((ds = (diskstats_t *) calloc (1, sizeof (diskstats_t))) == NULL)
				continue;

			if ((ds->name = strdup (disk_name)) == NULL)
			{
				free (ds);
				continue;
			}

			if (pre_ds == NULL)
				disklist = ds;
			else
				pre_ds->next = ds;
		}

		is_disk = 0;
		if (numfields == 7)
		{
			/* Kernel 2.6, Partition */
			read_ops      = atoll (fields[3]);
			read_sectors  = atoll (fields[4]);
			write_ops     = atoll (fields[5]);
			write_sectors = atoll (fields[6]);
		}
		else if (numfields == (14 + fieldshift))
		{
			read_ops  =  atoll (fields[3 + fieldshift]);
			write_ops =  atoll (fields[7 + fieldshift]);

			read_sectors  = atoll (fields[5 + fieldshift]);
			write_sectors = atoll (fields[9 + fieldshift]);

			if ((fieldshift == 0) || (minor == 0))
			{
				is_disk = 1;
				read_merged  = atoll (fields[4 + fieldshift]);
				read_time    = atoll (fields[6 + fieldshift]);
				write_merged = atoll (fields[8 + fieldshift]);
				write_time   = atoll (fields[10+ fieldshift]);
			}
		}
		else
		{
			DEBUG ("numfields = %i; => unknown file format.", numfields);
			continue;
		}

		{
			derive_t diff_read_sectors;
			derive_t diff_write_sectors;

		/* If the counter wraps around, it's only 32 bits.. */
			if (read_sectors < ds->read_sectors)
				diff_read_sectors = 1 + read_sectors
					+ (UINT_MAX - ds->read_sectors);
			else
				diff_read_sectors = read_sectors - ds->read_sectors;
			if (write_sectors < ds->write_sectors)
				diff_write_sectors = 1 + write_sectors
					+ (UINT_MAX - ds->write_sectors);
			else
				diff_write_sectors = write_sectors - ds->write_sectors;

			ds->read_bytes += 512 * diff_read_sectors;
			ds->write_bytes += 512 * diff_write_sectors;
			ds->read_sectors = read_sectors;
			ds->write_sectors = write_sectors;
		}

		/* Calculate the average time an io-op needs to complete */
		if (is_disk)
		{
			derive_t diff_read_ops;
			derive_t diff_write_ops;
			derive_t diff_read_time;
			derive_t diff_write_time;

			if (read_ops < ds->read_ops)
				diff_read_ops = 1 + read_ops
					+ (UINT_MAX - ds->read_ops);
			else
				diff_read_ops = read_ops - ds->read_ops;
			DEBUG ("disk plugin: disk_name = %s; read_ops = %"PRIi64"; "
					"ds->read_ops = %"PRIi64"; diff_read_ops = %"PRIi64";",
					disk_name,
					read_ops, ds->read_ops, diff_read_ops);

			if (write_ops < ds->write_ops)
				diff_write_ops = 1 + write_ops
					+ (UINT_MAX - ds->write_ops);
			else
				diff_write_ops = write_ops - ds->write_ops;

			if (read_time < ds->read_time)
				diff_read_time = 1 + read_time
					+ (UINT_MAX - ds->read_time);
			else
				diff_read_time = read_time - ds->read_time;

			if (write_time < ds->write_time)
				diff_write_time = 1 + write_time
					+ (UINT_MAX - ds->write_time);
			else
				diff_write_time = write_time - ds->write_time;

			if (diff_read_ops != 0)
				ds->avg_read_time += disk_calc_time_incr (
						diff_read_time, diff_read_ops);
			if (diff_write_ops != 0)
				ds->avg_write_time += disk_calc_time_incr (
						diff_write_time, diff_write_ops);

			ds->read_ops = read_ops;
			ds->read_time = read_time;
			ds->write_ops = write_ops;
			ds->write_time = write_time;
		} /* if (is_disk) */

		/* Don't write to the RRDs if we've just started.. */
		ds->poll_count++;
		if (ds->poll_count <= 2)
		{
			DEBUG ("disk plugin: (ds->poll_count = %i) <= "
					"(min_poll_count = 2); => Not writing.",
					ds->poll_count);
			continue;
		}

		if ((read_ops == 0) && (write_ops == 0))
		{
			DEBUG ("disk plugin: ((read_ops == 0) && "
					"(write_ops == 0)); => Not writing.");
			continue;
		}

		output_name = disk_name;

#if HAVE_LIBUDEV
		alt_name = disk_udev_attr_name (handle_udev, disk_name,
				conf_udev_name_attr);
#else
		alt_name = NULL;
#endif
		if (alt_name != NULL)
			output_name = alt_name;

		if ((ds->read_bytes != 0) || (ds->write_bytes != 0))
			disk_submit (output_name, "disk_octets",
					ds->read_bytes, ds->write_bytes);

		if ((ds->read_ops != 0) || (ds->write_ops != 0))
			disk_submit (output_name, "disk_ops",
					read_ops, write_ops);

		if ((ds->avg_read_time != 0) || (ds->avg_write_time != 0))
			disk_submit (output_name, "disk_time",
					ds->avg_read_time, ds->avg_write_time);

		if (is_disk)
		{
			disk_submit (output_name, "disk_merged",
					read_merged, write_merged);
		} /* if (is_disk) */

		/* release udev-based alternate name, if allocated */
		free(alt_name);
	} /* while (fgets (buffer, sizeof (buffer), fh) != NULL) */

#if HAVE_LIBUDEV
	udev_unref(handle_udev);
#endif

	fclose (fh);
/* #endif defined(KERNEL_LINUX) */

#elif HAVE_LIBKSTAT
# if HAVE_KSTAT_IO_T_WRITES && HAVE_KSTAT_IO_T_NWRITES && HAVE_KSTAT_IO_T_WTIME
#  define KIO_ROCTETS reads
#  define KIO_WOCTETS writes
#  define KIO_ROPS    nreads
#  define KIO_WOPS    nwrites
#  define KIO_RTIME   rtime
#  define KIO_WTIME   wtime
# elif HAVE_KSTAT_IO_T_NWRITTEN && HAVE_KSTAT_IO_T_WRITES && HAVE_KSTAT_IO_T_WTIME
#  define KIO_ROCTETS nread
#  define KIO_WOCTETS nwritten
#  define KIO_ROPS    reads
#  define KIO_WOPS    writes
#  define KIO_RTIME   rtime
#  define KIO_WTIME   wtime
# else
#  error "kstat_io_t does not have the required members"
# endif
	static kstat_io_t kio;
	int i;

	if (kc == NULL)
		return (-1);

	for (i = 0; i < numdisk; i++)
	{
		if (kstat_read (kc, ksp[i], &kio) == -1)
			continue;

		if (strncmp (ksp[i]->ks_class, "disk", 4) == 0)
		{
			disk_submit (ksp[i]->ks_name, "disk_octets",
					kio.KIO_ROCTETS, kio.KIO_WOCTETS);
			disk_submit (ksp[i]->ks_name, "disk_ops",
					kio.KIO_ROPS, kio.KIO_WOPS);
			/* FIXME: Convert this to microseconds if necessary */
			disk_submit (ksp[i]->ks_name, "disk_time",
					kio.KIO_RTIME, kio.KIO_WTIME);
		}
		else if (strncmp (ksp[i]->ks_class, "partition", 9) == 0)
		{
			disk_submit (ksp[i]->ks_name, "disk_octets",
					kio.KIO_ROCTETS, kio.KIO_WOCTETS);
			disk_submit (ksp[i]->ks_name, "disk_ops",
					kio.KIO_ROPS, kio.KIO_WOPS);
		}
	}
/* #endif defined(HAVE_LIBKSTAT) */

#elif defined(HAVE_LIBSTATGRAB)
	sg_disk_io_stats *ds;
	int disks, counter;
	char name[DATA_MAX_NAME_LEN];
	
	if ((ds = sg_get_disk_io_stats(&disks)) == NULL)
		return (0);
		
	for (counter=0; counter < disks; counter++) {
		strncpy(name, ds->disk_name, sizeof(name));
		name[sizeof(name)-1] = '\0'; /* strncpy doesn't terminate longer strings */
		disk_submit (name, "disk_octets", ds->read_bytes, ds->write_bytes);
		ds++;
	}
/* #endif defined(HAVE_LIBSTATGRAB) */

#elif defined(HAVE_PERFSTAT)
	derive_t read_sectors;
	derive_t write_sectors;
	derive_t read_time;
	derive_t write_time;
	derive_t read_ops;
	derive_t write_ops;
	perfstat_id_t firstpath;
	int rnumdisk;
	int i;

	if ((numdisk = perfstat_disk(NULL, NULL, sizeof(perfstat_disk_t), 0)) < 0) 
	{
		char errbuf[1024];
		WARNING ("disk plugin: perfstat_disk: %s",
				sstrerror (errno, errbuf, sizeof (errbuf)));
		return (-1);
	}

	if (numdisk != pnumdisk || stat_disk==NULL) {
		if (stat_disk!=NULL) 
			free(stat_disk);
		stat_disk = (perfstat_disk_t *)calloc(numdisk, sizeof(perfstat_disk_t));
	} 
	pnumdisk = numdisk;

	firstpath.name[0]='\0';
	if ((rnumdisk = perfstat_disk(&firstpath, stat_disk, sizeof(perfstat_disk_t), numdisk)) < 0) 
	{
		char errbuf[1024];
		WARNING ("disk plugin: perfstat_disk : %s",
				sstrerror (errno, errbuf, sizeof (errbuf)));
		return (-1);
	}

	for (i = 0; i < rnumdisk; i++) 
	{
		read_sectors = stat_disk[i].rblks*stat_disk[i].bsize;
		write_sectors = stat_disk[i].wblks*stat_disk[i].bsize;
		disk_submit (stat_disk[i].name, "disk_octets", read_sectors, write_sectors);

		read_ops = stat_disk[i].xrate;
		write_ops = stat_disk[i].xfers - stat_disk[i].xrate;
		disk_submit (stat_disk[i].name, "disk_ops", read_ops, write_ops);

		read_time = stat_disk[i].rserv;
		read_time *= ((double)(_system_configuration.Xint)/(double)(_system_configuration.Xfrac)) / 1000000.0;
		write_time = stat_disk[i].wserv;
		write_time *= ((double)(_system_configuration.Xint)/(double)(_system_configuration.Xfrac)) / 1000000.0;
		disk_submit (stat_disk[i].name, "disk_time", read_time, write_time);
	}
#endif /* defined(HAVE_PERFSTAT) */

	return (0);
} /* int disk_read */
Esempio n. 7
0
/* Configuration handling functiions
 * <Plugin apache>
 *   <Instance "instance_name">
 *     URL ...
 *   </Instance>
 *   URL ...
 * </Plugin>
 */
static int config_add (oconfig_item_t *ci)
{
	apache_t *st;
	int i;
	int status;

	st = malloc (sizeof (*st));
	if (st == NULL)
	{
		ERROR ("apache plugin: malloc failed.");
		return (-1);
	}
	memset (st, 0, sizeof (*st));

	status = cf_util_get_string (ci, &st->name);
	if (status != 0)
	{
		sfree (st);
		return (status);
	}
	assert (st->name != NULL);

	for (i = 0; i < ci->children_num; i++)
	{
		oconfig_item_t *child = ci->children + i;

		if (strcasecmp ("URL", child->key) == 0)
			status = cf_util_get_string (child, &st->url);
		else if (strcasecmp ("Host", child->key) == 0)
			status = cf_util_get_string (child, &st->host);
		else if (strcasecmp ("User", child->key) == 0)
			status = cf_util_get_string (child, &st->user);
		else if (strcasecmp ("Password", child->key) == 0)
			status = cf_util_get_string (child, &st->pass);
		else if (strcasecmp ("VerifyPeer", child->key) == 0)
			status = cf_util_get_boolean (child, &st->verify_peer);
		else if (strcasecmp ("VerifyHost", child->key) == 0)
			status = cf_util_get_boolean (child, &st->verify_host);
		else if (strcasecmp ("CACert", child->key) == 0)
			status = cf_util_get_string (child, &st->cacert);
		else if (strcasecmp ("Server", child->key) == 0)
			status = cf_util_get_string (child, &st->server);
		else
		{
			WARNING ("apache plugin: Option `%s' not allowed here.",
					child->key);
			status = -1;
		}

		if (status != 0)
			break;
	}

	/* Check if struct is complete.. */
	if ((status == 0) && (st->url == NULL))
	{
		ERROR ("apache plugin: Instance `%s': "
				"No URL has been configured.",
				st->name);
		status = -1;
	}

	if (status == 0)
	{
		user_data_t ud;
		char callback_name[3*DATA_MAX_NAME_LEN];

		memset (&ud, 0, sizeof (ud));
		ud.data = st;
		ud.free_func = (void *) apache_free;

		memset (callback_name, 0, sizeof (callback_name));
		ssnprintf (callback_name, sizeof (callback_name),
				"apache/%s/%s",
				(st->host != NULL) ? st->host : hostname_g,
				(st->name != NULL) ? st->name : "default"),

		status = plugin_register_complex_read (/* group = */ NULL,
				/* name      = */ callback_name,
				/* callback  = */ apache_read_host,
				/* interval  = */ NULL,
				/* user_data = */ &ud);
	}

	if (status != 0)
	{
		apache_free (st);
		return (-1);
	}

	return (0);
} /* int config_add */
Esempio n. 8
0
static int mysql_config (oconfig_item_t *ci) /* {{{ */
{
	mysql_database_t *db;
	int plugin_block;
	int status = 0;
	int i;

	if ((ci->values_num != 1)
	    || (ci->values[0].type != OCONFIG_TYPE_STRING))
	{
		WARNING ("mysql plugin: The `Database' block "
			 "needs exactly one string argument.");
		return (-1);
	}

	db = (mysql_database_t *) malloc (sizeof (*db));
	if (db == NULL)
	{
		ERROR ("mysql plugin: malloc failed.");
		return (-1);
	}
	memset (db, 0, sizeof (*db));

	/* initialize all the pointers */
	db->host     = NULL;
	db->user     = NULL;
	db->pass     = NULL;
	db->database = NULL;
	db->socket   = NULL;
	db->con      = NULL;

	/* trigger a notification, if it's not running */
	db->slave_io_running  = 1;
	db->slave_sql_running = 1;

	plugin_block = 1;
	if (strcasecmp ("Plugin", ci->key) == 0)
	{
		db->instance = NULL;
	}
	else if (strcasecmp ("Database", ci->key) == 0)
	{
		plugin_block = 0;
		status = mysql_config_set_string (&db->instance, ci);
		if (status != 0)
		{
			sfree (db);
			return (status);
		}
		assert (db->instance != NULL);
	}
	else
	{
		ERROR ("mysql plugin: mysql_config: "
				"Invalid key: %s", ci->key);
		return (-1);
	}

	/* Fill the `mysql_database_t' structure.. */
	for (i = 0; i < ci->children_num; i++)
	{
		oconfig_item_t *child = ci->children + i;

		if (strcasecmp ("Host", child->key) == 0)
			status = mysql_config_set_string (&db->host, child);
		else if (strcasecmp ("User", child->key) == 0)
			status = mysql_config_set_string (&db->user, child);
		else if (strcasecmp ("Password", child->key) == 0)
			status = mysql_config_set_string (&db->pass, child);
		else if (strcasecmp ("Port", child->key) == 0)
			status = mysql_config_set_int (&db->port, child);
		else if (strcasecmp ("Socket", child->key) == 0)
			status = mysql_config_set_string (&db->socket, child);
		/* Check if we're currently handling the `Plugin' block. If so,
		 * handle `Database' _blocks_, too. */
		else if ((plugin_block != 0)
				&& (strcasecmp ("Database", child->key) == 0)
				&& (child->children != NULL))
		{
			/* If `plugin_block > 1', there has been at least one
			 * `Database' block */
			plugin_block++;
			status = mysql_config (child);
		}
		/* Now handle ordinary `Database' options (without children) */
		else if ((strcasecmp ("Database", child->key) == 0)
				&& (child->children == NULL))
			status = mysql_config_set_string (&db->database, child);
		else if (strcasecmp ("MasterStats", child->key) == 0)
			status = mysql_config_set_boolean (&db->master_stats, child);
		else if (strcasecmp ("SlaveStats", child->key) == 0)
			status = mysql_config_set_boolean (&db->slave_stats, child);
		else if (strcasecmp ("SlaveNotifications", child->key) == 0)
			status = mysql_config_set_boolean (&db->slave_notif, child);
		else
		{
			WARNING ("mysql plugin: Option `%s' not allowed here.", child->key);
			status = -1;
		}

		if (status != 0)
			break;
	}

	/* Check if there were any `Database' blocks. */
	if (plugin_block > 1)
	{
		/* There were connection blocks. Don't use any legacy stuff. */
		if ((db->host != NULL)
			|| (db->user != NULL)
			|| (db->pass != NULL)
			|| (db->database != NULL)
			|| (db->socket != NULL)
			|| (db->port != 0))
		{
			WARNING ("mysql plugin: At least one <Database> "
					"block has been found. The legacy "
					"configuration will be ignored.");
		}
		mysql_database_free (db);
		return (0);
	}
	else if (plugin_block != 0)
	{
		WARNING ("mysql plugin: You're using the legacy "
				"configuration options. Please consider "
				"updating your configuration!");
	}

	/* Check that all necessary options have been given. */
	while (status == 0)
	{
		/* Zero is allowed and automatically handled by
		 * `mysql_real_connect'. */
		if ((db->port < 0) || (db->port > 65535))
		{
			ERROR ("mysql plugin: Database %s: Port number out "
					"of range: %i",
					(db->instance != NULL)
					? db->instance
					: "<legacy>",
					db->port);
			status = -1;
		}
		break;
	} /* while (status == 0) */

	/* If all went well, register this database for reading */
	if (status == 0)
	{
		user_data_t ud;
		char cb_name[DATA_MAX_NAME_LEN];

		DEBUG ("mysql plugin: Registering new read callback: %s",
				(db->database != NULL) ? db->database : "<default>");

		memset (&ud, 0, sizeof (ud));
		ud.data = (void *) db;
		ud.free_func = mysql_database_free;

		if (db->database != NULL)
			ssnprintf (cb_name, sizeof (cb_name), "mysql-%s",
					db->database);
		else
			sstrncpy (cb_name, "mysql", sizeof (cb_name));

		plugin_register_complex_read (cb_name, mysql_read,
					      /* interval = */ NULL, &ud);
	}
	else
	{
		mysql_database_free (db);
		return (-1);
	}

	return (0);
} /* }}} int mysql_config */
Esempio n. 9
0
static int mysql_read_slave_stats (mysql_database_t *db, MYSQL *con)
{
	MYSQL_RES *res;
	MYSQL_ROW  row;

	char *query;
	int   field_num;

	/* WTF? libmysqlclient does not seem to provide any means to
	 * translate a column name to a column index ... :-/ */
	const int READ_MASTER_LOG_POS_IDX   = 6;
	const int SLAVE_IO_RUNNING_IDX      = 10;
	const int SLAVE_SQL_RUNNING_IDX     = 11;
	const int EXEC_MASTER_LOG_POS_IDX   = 21;
	const int SECONDS_BEHIND_MASTER_IDX = 32;

	query = "SHOW SLAVE STATUS";

	res = exec_query (con, query);
	if (res == NULL)
		return (-1);

	row = mysql_fetch_row (res);
	if (row == NULL)
	{
		ERROR ("mysql plugin: Failed to get slave statistics: "
				"`%s' did not return any rows.", query);
		return (-1);
	}

	field_num = mysql_num_fields (res);
	if (field_num < 33)
	{
		ERROR ("mysql plugin: Failed to get slave statistics: "
				"`%s' returned less than 33 columns.", query);
		return (-1);
	}

	if (db->slave_stats)
	{
		unsigned long long counter;
		double gauge;

		counter = atoll (row[READ_MASTER_LOG_POS_IDX]);
		counter_submit ("mysql_log_position", "slave-read", counter, db);

		counter = atoll (row[EXEC_MASTER_LOG_POS_IDX]);
		counter_submit ("mysql_log_position", "slave-exec", counter, db);

		if (row[SECONDS_BEHIND_MASTER_IDX] != NULL)
		{
			gauge = atof (row[SECONDS_BEHIND_MASTER_IDX]);
			gauge_submit ("time_offset", NULL, gauge, db);
		}
	}

	if (db->slave_notif)
	{
		notification_t n = { 0, time (NULL), "", "",
			"mysql", "", "time_offset", "", NULL };

		char *io, *sql;

		io  = row[SLAVE_IO_RUNNING_IDX];
		sql = row[SLAVE_SQL_RUNNING_IDX];

		set_host (db, n.host, sizeof (n.host));
		set_plugin_instance (db,
				n.plugin_instance, sizeof (n.plugin_instance));

		if (((io == NULL) || (strcasecmp (io, "yes") != 0))
				&& (db->slave_io_running))
		{
			n.severity = NOTIF_WARNING;
			ssnprintf (n.message, sizeof (n.message),
					"slave I/O thread not started or not connected to master");
			plugin_dispatch_notification (&n);
			db->slave_io_running = 0;
		}
		else if (((io != NULL) && (strcasecmp (io, "yes") == 0))
				&& (! db->slave_io_running))
		{
			n.severity = NOTIF_OKAY;
			ssnprintf (n.message, sizeof (n.message),
					"slave I/O thread started and connected to master");
			plugin_dispatch_notification (&n);
			db->slave_io_running = 1;
		}

		if (((sql == NULL) || (strcasecmp (sql, "yes") != 0))
				&& (db->slave_sql_running))
		{
			n.severity = NOTIF_WARNING;
			ssnprintf (n.message, sizeof (n.message),
					"slave SQL thread not started");
			plugin_dispatch_notification (&n);
			db->slave_sql_running = 0;
		}
		else if (((sql != NULL) && (strcasecmp (sql, "yes") == 0))
				&& (! db->slave_sql_running))
		{
			n.severity = NOTIF_OKAY;
			ssnprintf (n.message, sizeof (n.message),
					"slave SQL thread started");
			plugin_dispatch_notification (&n);
			db->slave_sql_running = 0;
		}
	}

	row = mysql_fetch_row (res);
	if (row != NULL)
		WARNING ("mysql plugin: `%s' returned more than one row - "
				"ignoring further results.", query);

	mysql_free_result (res);

	return (0);
} /* mysql_read_slave_stats */
Esempio n. 10
0
static int values_to_kairosdb(char *buffer, size_t buffer_size, /* {{{ */
                              const data_set_t *ds, const value_list_t *vl,
                              int store_rates, size_t ds_idx) {
  size_t offset = 0;
  gauge_t *rates = NULL;

  memset(buffer, 0, buffer_size);

#define BUFFER_ADD(...)                                                        \
  do {                                                                         \
    int status;                                                                \
    status = snprintf(buffer + offset, buffer_size - offset, __VA_ARGS__);     \
    if (status < 1) {                                                          \
      sfree(rates);                                                            \
      return -1;                                                               \
    } else if (((size_t)status) >= (buffer_size - offset)) {                   \
      sfree(rates);                                                            \
      return -ENOMEM;                                                          \
    } else                                                                     \
      offset += ((size_t)status);                                              \
  } while (0)

  if (ds->ds[ds_idx].type == DS_TYPE_GAUGE) {
    if (isfinite(vl->values[ds_idx].gauge)) {
      BUFFER_ADD("[[");
      BUFFER_ADD("%" PRIu64, CDTIME_T_TO_MS(vl->time));
      BUFFER_ADD(",");
      BUFFER_ADD(JSON_GAUGE_FORMAT, vl->values[ds_idx].gauge);
    } else {
      DEBUG("utils_format_kairosdb: invalid vl->values[ds_idx].gauge for "
            "%s|%s|%s|%s|%s",
            vl->plugin, vl->plugin_instance, vl->type, vl->type_instance,
            ds->ds[ds_idx].name);
      return -1;
    }
  } else if (store_rates) {
    if (rates == NULL)
      rates = uc_get_rate(ds, vl);
    if (rates == NULL) {
      WARNING("utils_format_kairosdb: uc_get_rate failed for %s|%s|%s|%s|%s",
              vl->plugin, vl->plugin_instance, vl->type, vl->type_instance,
              ds->ds[ds_idx].name);

      return -1;
    }

    if (isfinite(rates[ds_idx])) {
      BUFFER_ADD("[[");
      BUFFER_ADD("%" PRIu64, CDTIME_T_TO_MS(vl->time));
      BUFFER_ADD(",");
      BUFFER_ADD(JSON_GAUGE_FORMAT, rates[ds_idx]);
    } else {
      WARNING("utils_format_kairosdb: invalid rates[ds_idx] for %s|%s|%s|%s|%s",
              vl->plugin, vl->plugin_instance, vl->type, vl->type_instance,
              ds->ds[ds_idx].name);
      sfree(rates);
      return -1;
    }
  } else if (ds->ds[ds_idx].type == DS_TYPE_COUNTER) {
    BUFFER_ADD("[[");
    BUFFER_ADD("%" PRIu64, CDTIME_T_TO_MS(vl->time));
    BUFFER_ADD(",");
    BUFFER_ADD("%" PRIu64, (uint64_t)vl->values[ds_idx].counter);
  } else if (ds->ds[ds_idx].type == DS_TYPE_DERIVE) {
    BUFFER_ADD("[[");
    BUFFER_ADD("%" PRIu64, CDTIME_T_TO_MS(vl->time));
    BUFFER_ADD(",");
    BUFFER_ADD("%" PRIi64, vl->values[ds_idx].derive);
  } else if (ds->ds[ds_idx].type == DS_TYPE_ABSOLUTE) {
    BUFFER_ADD("[[");
    BUFFER_ADD("%" PRIu64, CDTIME_T_TO_MS(vl->time));
    BUFFER_ADD(",");
    BUFFER_ADD("%" PRIu64, vl->values[ds_idx].absolute);
  } else {
    ERROR("format_kairosdb: Unknown data source type: %i", ds->ds[ds_idx].type);
    sfree(rates);
    return -1;
  }
  BUFFER_ADD("]]");

#undef BUFFER_ADD

  DEBUG("format_kairosdb: values_to_kairosdb: buffer = %s;", buffer);
  sfree(rates);
  return 0;
} /* }}} int values_to_kairosdb */
Esempio n. 11
0
static irqreturn_t davinci_musb_interrupt(int irq, void *__hci)
{
	unsigned long	flags;
	irqreturn_t	retval = IRQ_NONE;
	struct musb	*musb = __hci;
	void __iomem	*tibase = musb->ctrl_base;
	struct cppi	*cppi;
	u32		tmp;

	spin_lock_irqsave(&musb->lock, flags);

	/* NOTE: DaVinci shadows the Mentor IRQs.  Don't manage them through
	 * the Mentor registers (except for setup), use the TI ones and EOI.
	 *
	 * Docs describe irq "vector" registers associated with the CPPI and
	 * USB EOI registers.  These hold a bitmask corresponding to the
	 * current IRQ, not an irq handler address.  Would using those bits
	 * resolve some of the races observed in this dispatch code??
	 */

	/* CPPI interrupts share the same IRQ line, but have their own
	 * mask, state, "vector", and EOI registers.
	 */
	cppi = container_of(musb->dma_controller, struct cppi, controller);
	if (is_cppi_enabled(musb) && musb->dma_controller && !cppi->irq)
		retval = cppi_interrupt(irq, __hci);

	/* ack and handle non-CPPI interrupts */
	tmp = musb_readl(tibase, DAVINCI_USB_INT_SRC_MASKED_REG);
	musb_writel(tibase, DAVINCI_USB_INT_SRC_CLR_REG, tmp);
	DBG(4, "IRQ %08x\n", tmp);

	musb->int_rx = (tmp & DAVINCI_USB_RXINT_MASK)
			>> DAVINCI_USB_RXINT_SHIFT;
	musb->int_tx = (tmp & DAVINCI_USB_TXINT_MASK)
			>> DAVINCI_USB_TXINT_SHIFT;
	musb->int_usb = (tmp & DAVINCI_USB_USBINT_MASK)
			>> DAVINCI_USB_USBINT_SHIFT;

	/* DRVVBUS irqs are the only proxy we have (a very poor one!) for
	 * DaVinci's missing ID change IRQ.  We need an ID change IRQ to
	 * switch appropriately between halves of the OTG state machine.
	 * Managing DEVCTL.SESSION per Mentor docs requires we know its
	 * value, but DEVCTL.BDEVICE is invalid without DEVCTL.SESSION set.
	 * Also, DRVVBUS pulses for SRP (but not at 5V) ...
	 */
	if (tmp & (DAVINCI_INTR_DRVVBUS << DAVINCI_USB_USBINT_SHIFT)) {
		int	drvvbus = musb_readl(tibase, DAVINCI_USB_STAT_REG);
		void __iomem *mregs = musb->mregs;
		u8	devctl = musb_readb(mregs, MUSB_DEVCTL);
		int	err = musb->int_usb & MUSB_INTR_VBUSERROR;

		err = is_host_enabled(musb)
				&& (musb->int_usb & MUSB_INTR_VBUSERROR);
		if (err) {
			/* The Mentor core doesn't debounce VBUS as needed
			 * to cope with device connect current spikes. This
			 * means it's not uncommon for bus-powered devices
			 * to get VBUS errors during enumeration.
			 *
			 * This is a workaround, but newer RTL from Mentor
			 * seems to allow a better one: "re"starting sessions
			 * without waiting (on EVM, a **long** time) for VBUS
			 * to stop registering in devctl.
			 */
			musb->int_usb &= ~MUSB_INTR_VBUSERROR;
			musb->xceiv->state = OTG_STATE_A_WAIT_VFALL;
			mod_timer(&otg_workaround, jiffies + POLL_SECONDS * HZ);
			WARNING("VBUS error workaround (delay coming)\n");
		} else if (is_host_enabled(musb) && drvvbus) {
			MUSB_HST_MODE(musb);
			musb->xceiv->default_a = 1;
			musb->xceiv->state = OTG_STATE_A_WAIT_VRISE;
			portstate(musb->port1_status |= USB_PORT_STAT_POWER);
			del_timer(&otg_workaround);
		} else {
			musb->is_active = 0;
			MUSB_DEV_MODE(musb);
			musb->xceiv->default_a = 0;
			musb->xceiv->state = OTG_STATE_B_IDLE;
			portstate(musb->port1_status &= ~USB_PORT_STAT_POWER);
		}

		/* NOTE:  this must complete poweron within 100 msec
		 * (OTG_TIME_A_WAIT_VRISE) but we don't check for that.
		 */
		davinci_musb_source_power(musb, drvvbus, 0);
		DBG(2, "VBUS %s (%s)%s, devctl %02x\n",
				drvvbus ? "on" : "off",
				otg_state_string(musb),
				err ? " ERROR" : "",
				devctl);
		retval = IRQ_HANDLED;
	}

	if (musb->int_tx || musb->int_rx || musb->int_usb)
		retval |= musb_interrupt(musb);

	/* irq stays asserted until EOI is written */
	musb_writel(tibase, DAVINCI_USB_EOI_REG, 0);

	/* poll for ID change */
	if (is_otg_enabled(musb)
			&& musb->xceiv->state == OTG_STATE_B_IDLE)
		mod_timer(&otg_workaround, jiffies + POLL_SECONDS * HZ);

	spin_unlock_irqrestore(&musb->lock, flags);

	return retval;
}
Esempio n. 12
0
bool connection_open_tcp(connection *con, const char *host, const char *service)
{
    EXPECT_FATAL(con);
    EXPECT_FATAL(host);
    EXPECT_FATAL(service);
    EXPECT_FATAL(sizeof(con->mem) >= sizeof(SOCKET));
    
    if (strnlen(host, 256) > 255) { X(bad_arg, XSTR_LIMIT": host must not exceed 255 octets"); }
    
    SOCKET s = INVALID_SOCKET;
    
    // method e.g. "GET"
    // host e.g. "example.org"
    // rsc e.g.  "/index.html"
    // port e.g. 80
    
    const struct addrinfo hints =
    {
        AI_NUMERICSERV | AI_ADDRCONFIG, // ai_flags
        AF_UNSPEC,   // ai_family: AF_INET | AF_INET6 | AF_UNSPEC
        SOCK_STREAM, // ai_socktype (TCP)
        IPPROTO_TCP, // ai_protocol (TCP)
        0,
        NULL,
        NULL,
        NULL,
    };
    struct addrinfo *result;
    
    int ret = getaddrinfo(host, service, &hints, &result);
    if (ret != 0) { Xf(lookup_address, XSTR_NETWORK": (%s) %s", host, getaddrinfo_strerror(ret)); }
    
    for (struct addrinfo *current = result; current; current = current->ai_next)
    {
        s = socket(current->ai_family, current->ai_socktype, current->ai_protocol);
        if (s == INVALID_SOCKET) { Xf(socket, XSTR_NETWORK ": socket() errno=%d\n", socket_geterr()); }
        
        ret = socket_connect(s, current->ai_addr, current->ai_addrlen);
        if (ret != 0) { Xf(connect, XSTR_NETWORK ": connect() errno=%d\n", socket_geterr()); }
        
        memset(con->address, '\0', CFW_INET6_ADDRSTRLEN);

#       ifndef TARGET_WINDOWS
            if(!inet_ntop(current->ai_family,
                &((struct sockaddr_in *) current->ai_addr)->sin_addr,
                con->address, CFW_INET6_ADDRSTRLEN)
            ) { WARNING("inet_ntop() IP lookup failure"); }
#       endif
        
        // success
        break;
        
        // fallthru
        err_connect:
            socket_close(s);
        err_socket:
            continue;
    }
    
    freeaddrinfo(result);
    
    if (s == INVALID_SOCKET) { X(no_match, "No matching socket"); }
    
    memcpy(con, &s, sizeof(SOCKET));
    strcpy(con->host, host);
    return true;
    
    err_no_match:
        freeaddrinfo(result);
    err_lookup_address:
    err_bad_arg:
        return false;
}
Esempio n. 13
0
int nsc_dclm_pbc(const rvec *coords, real *radius, int nat,
                 int  densit, int mode,
                 real *value_of_area, real **at_area,
                 real *value_of_vol,
                 real **lidots, int *nu_dots,
                 atom_id index[], int ePBC, matrix box)
{
    int         iat, i, ii, iii, ix, iy, iz, ixe, ixs, iye, iys, ize, izs, i_ac;
    int         jat, j, jj, jjj, jx, jy, jz;
    int         distribution;
    int         l;
    int         maxnei, nnei, last, maxdots = 0;
    int        *wkdot = NULL, *wkbox = NULL, *wkat1 = NULL, *wkatm = NULL;
    Neighb     *wknb, *ctnb;
    int         iii1, iii2, iiat, lfnr = 0, i_at, j_at;
    real        dx, dy, dz, dd, ai, aisq, ajsq, aj, as, a;
    real        xi, yi, zi, xs = 0., ys = 0., zs = 0.;
    real        dotarea, area, vol = 0.;
    real       *xus, *dots = NULL, *atom_area = NULL;
    int         nxbox, nybox, nzbox, nxy, nxyz;
    real        xmin = 0, ymin = 0, zmin = 0, xmax, ymax, zmax, ra2max, d;
    const real *pco;
    /* Added DvdS 2006-07-19 */
    t_pbc       pbc;
    rvec        ddx, *x = NULL;
    int         iat_xx, jat_xx;

    distribution = unsp_type(densit);
    if (distribution != -last_unsp || last_cubus != 4 ||
        (densit != last_densit && densit != last_n_dot))
    {
        if (make_unsp(densit, (-distribution), &n_dot, 4))
        {
            return 1;
        }
    }
    xus = xpunsp;

    dotarea = FOURPI/(real) n_dot;
    area    = 0.;

    if (debug)
    {
        fprintf(debug, "nsc_dclm: n_dot=%5d %9.3f\n", n_dot, dotarea);
    }

    /* start with neighbour list */
    /* calculate neighbour list with the box algorithm */
    if (nat == 0)
    {
        WARNING("nsc_dclm: no surface atoms selected");
        return 1;
    }
    if (mode & FLAG_VOLUME)
    {
        vol = 0.;
    }
    if (mode & FLAG_DOTS)
    {
        maxdots = (3*n_dot*nat)/10;
        /* should be set to NULL on first user call */
        if (dots == NULL)
        {
            snew(dots, maxdots);
        }
        else
        {
            srenew(dots, maxdots);
        }

        lfnr = 0;
    }
    if (mode & FLAG_ATOM_AREA)
    {
        /* should be set to NULL on first user call */
        if (atom_area == NULL)
        {
            snew(atom_area, nat);
        }
        else
        {
            srenew(atom_area, nat);
        }
    }

    /* Compute minimum size for grid cells */
    ra2max = radius[index[0]];
    for (iat_xx = 1; (iat_xx < nat); iat_xx++)
    {
        iat    = index[iat_xx];
        ra2max = max(ra2max, radius[iat]);
    }
    ra2max = 2*ra2max;

    /* Added DvdS 2006-07-19 */
    /* Updated 2008-10-09 */
    if (box)
    {
        set_pbc(&pbc, ePBC, box);
        snew(x, nat);
        for (i = 0; (i < nat); i++)
        {
            iat  = index[0];
            copy_rvec(coords[iat], x[i]);
        }
        put_atoms_in_triclinic_unitcell(ecenterTRIC, box, nat, x);
        nxbox = max(1, floor(norm(box[XX])/ra2max));
        nybox = max(1, floor(norm(box[YY])/ra2max));
        nzbox = max(1, floor(norm(box[ZZ])/ra2max));
        if (debug)
        {
            fprintf(debug, "nbox = %d, %d, %d\n", nxbox, nybox, nzbox);
        }
    }
    else
    {
        /* dimensions of atomic set, cell edge is 2*ra_max */
        iat    = index[0];
        xmin   = coords[iat][XX]; xmax = xmin; xs = xmin;
        ymin   = coords[iat][YY]; ymax = ymin; ys = ymin;
        zmin   = coords[iat][ZZ]; zmax = zmin; zs = zmin;

        for (iat_xx = 1; (iat_xx < nat); iat_xx++)
        {
            iat  = index[iat_xx];
            pco  = coords[iat];
            xmin = min(xmin, *pco);     xmax = max(xmax, *pco);
            ymin = min(ymin, *(pco+1)); ymax = max(ymax, *(pco+1));
            zmin = min(zmin, *(pco+2)); zmax = max(zmax, *(pco+2));
            xs   = xs+ *pco; ys = ys+ *(pco+1); zs = zs+ *(pco+2);
        }
        xs = xs/ (real) nat;
        ys = ys/ (real) nat;
        zs = zs/ (real) nat;
        if (debug)
        {
            fprintf(debug, "nsc_dclm: n_dot=%5d ra2max=%9.3f %9.3f\n", n_dot, ra2max, dotarea);
        }

        d    = xmax-xmin; nxbox = (int) max(ceil(d/ra2max), 1.);
        d    = (((real)nxbox)*ra2max-d)/2.;
        xmin = xmin-d; xmax = xmax+d;
        d    = ymax-ymin; nybox = (int) max(ceil(d/ra2max), 1.);
        d    = (((real)nybox)*ra2max-d)/2.;
        ymin = ymin-d; ymax = ymax+d;
        d    = zmax-zmin; nzbox = (int) max(ceil(d/ra2max), 1.);
        d    = (((real)nzbox)*ra2max-d)/2.;
        zmin = zmin-d; zmax = zmax+d;
    }
    /* Help variables */
    nxy  = nxbox*nybox;
    nxyz = nxy*nzbox;

    /* box number of atoms */
    snew(wkatm, nat);
    snew(wkat1, nat);
    snew(wkdot, n_dot);
    snew(wkbox, nxyz+1);

    if (box)
    {
        matrix box_1;
        rvec   x_1;
        int    ix, iy, iz, m;
        m_inv(box, box_1);
        for (i = 0; (i < nat); i++)
        {
            mvmul(box_1, x[i], x_1);
            ix = ((int)floor(x_1[XX]*nxbox) + 2*nxbox) % nxbox;
            iy = ((int)floor(x_1[YY]*nybox) + 2*nybox) % nybox;
            iz = ((int)floor(x_1[ZZ]*nzbox) + 2*nzbox) % nzbox;
            j  =  ix + iy*nxbox + iz*nxbox*nybox;
            if (debug)
            {
                fprintf(debug, "Atom %d cell index %d. x = (%8.3f,%8.3f,%8.3f) fc = (%8.3f,%8.3f,%8.3f)\n",
                        i, j, x[i][XX], x[i][YY], x[i][ZZ], x_1[XX], x_1[YY], x_1[ZZ]);
            }
            range_check(j, 0, nxyz);
            wkat1[i] = j;
            wkbox[j]++;
        }
    }
    else
    {
        /* Put the atoms in their boxes */
        for (iat_xx = 0; (iat_xx < nat); iat_xx++)
        {
            iat           = index[iat_xx];
            pco           = coords[iat];
            i             = (int) max(floor((pco[XX]-xmin)/ra2max), 0);
            i             = min(i, nxbox-1);
            j             = (int) max(floor((pco[YY]-ymin)/ra2max), 0);
            j             = min(j, nybox-1);
            l             = (int) max(floor((pco[ZZ]-zmin)/ra2max), 0);
            l             = min(l, nzbox-1);
            i             = i+j*nxbox+l*nxy;
            wkat1[iat_xx] = i;
            wkbox[i]++;
        }
    }

    /* sorting of atoms in accordance with box numbers */
    j = wkbox[0];
    for (i = 1; i < nxyz; i++)
    {
        j = max(wkbox[i], j);
    }
    for (i = 1; i <= nxyz; i++)
    {
        wkbox[i] += wkbox[i-1];
    }

    /* maxnei = (int) floor(ra2max*ra2max*ra2max*0.5); */
    maxnei = min(nat, 27*j);
    snew(wknb, maxnei);
    for (iat_xx = 0; iat_xx < nat; iat_xx++)
    {
        iat = index[iat_xx];
        range_check(wkat1[iat_xx], 0, nxyz);
        wkatm[--wkbox[wkat1[iat_xx]]] = iat_xx;
        if (debug)
        {
            fprintf(debug, "atom %5d on place %5d\n", iat, wkbox[wkat1[iat_xx]]);
        }
    }

    if (debug)
    {
        fprintf(debug, "nsc_dclm: n_dot=%5d ra2max=%9.3f %9.3f\n",
                n_dot, ra2max, dotarea);
        fprintf(debug, "neighbour list calculated/box(xyz):%d %d %d\n",
                nxbox, nybox, nzbox);

        for (i = 0; i < nxyz; i++)
        {
            fprintf(debug, "box %6d : atoms %4d-%4d    %5d\n",
                    i, wkbox[i], wkbox[i+1]-1, wkbox[i+1]-wkbox[i]);
        }
        for (i = 0; i < nat; i++)
        {
            fprintf(debug, "list place %5d by atom %7d\n", i, index[wkatm[i]]);
        }
    }

    /* calculate surface for all atoms, step cube-wise */
    for (iz = 0; iz < nzbox; iz++)
    {
        iii = iz*nxy;
        if (box)
        {
            izs = iz-1;
            ize = min(iz+2, izs+nzbox);
        }
        else
        {
            izs = max(iz-1, 0);
            ize = min(iz+2, nzbox);
        }
        for (iy = 0; iy < nybox; iy++)
        {
            ii = iy*nxbox+iii;
            if (box)
            {
                iys = iy-1;
                iye = min(iy+2, iys+nybox);
            }
            else
            {
                iys = max(iy-1, 0);
                iye = min(iy+2, nybox);
            }
            for (ix = 0; ix < nxbox; ix++)
            {
                i    = ii+ix;
                iii1 = wkbox[i];
                iii2 = wkbox[i+1];
                if (iii1 >= iii2)
                {
                    continue;
                }
                if (box)
                {
                    ixs = ix-1;
                    ixe = min(ix+2, ixs+nxbox);
                }
                else
                {
                    ixs = max(ix-1, 0);
                    ixe = min(ix+2, nxbox);
                }
                iiat = 0;
                /* make intermediate atom list */
                for (jz = izs; jz < ize; jz++)
                {
                    jjj = ((jz+nzbox) % nzbox)*nxy;
                    for (jy = iys; jy < iye; jy++)
                    {
                        jj = ((jy+nybox) % nybox)*nxbox+jjj;
                        for (jx = ixs; jx < ixe; jx++)
                        {
                            j = jj+((jx+nxbox) % nxbox);
                            for (jat = wkbox[j]; jat < wkbox[j+1]; jat++)
                            {
                                range_check(wkatm[jat], 0, nat);
                                range_check(iiat, 0, nat);
                                wkat1[iiat] = wkatm[jat];
                                iiat++;
                            } /* end of cycle "jat" */
                        }     /* end of cycle "jx" */
                    }         /* end of cycle "jy" */
                }             /* end of cycle "jz" */
                for (iat = iii1; iat < iii2; iat++)
                {
                    i_at = index[wkatm[iat]];
                    ai   = radius[i_at];
                    aisq = ai*ai;
                    pco  = coords[i_at];
                    xi   = pco[XX]; yi = pco[YY]; zi = pco[ZZ];
                    for (i = 0; i < n_dot; i++)
                    {
                        wkdot[i] = 0;
                    }

                    ctnb = wknb; nnei = 0;
                    for (j = 0; j < iiat; j++)
                    {
                        j_at = index[wkat1[j]];
                        if (j_at == i_at)
                        {
                            continue;
                        }

                        aj   = radius[j_at];
                        ajsq = aj*aj;
                        pco  = coords[j_at];

                        /* Added DvdS 2006-07-19 */
                        if (box)
                        {
                            /*rvec xxi;

                               xxi[XX] = xi;
                               xxi[YY] = yi;
                               xxi[ZZ] = zi;
                               pbc_dx(&pbc,pco,xxi,ddx);*/
                            pbc_dx(&pbc, coords[j_at], coords[i_at], ddx);
                            dx = ddx[XX];
                            dy = ddx[YY];
                            dz = ddx[ZZ];
                        }
                        else
                        {
                            dx = pco[XX]-xi;
                            dy = pco[YY]-yi;
                            dz = pco[ZZ]-zi;
                        }
                        dd = dx*dx+dy*dy+dz*dz;
                        as = ai+aj;
                        if (dd > as*as)
                        {
                            continue;
                        }
                        nnei++;
                        ctnb->x   = dx;
                        ctnb->y   = dy;
                        ctnb->z   = dz;
                        ctnb->dot = (dd+aisq-ajsq)/(2.*ai); /* reference dot product */
                        ctnb++;
                    }

                    /* check points on accessibility */
                    if (nnei)
                    {
                        last = 0; i_ac = 0;
                        for (l = 0; l < n_dot; l++)
                        {
                            if (xus[3*l]*(wknb+last)->x+
                                xus[1+3*l]*(wknb+last)->y+
                                xus[2+3*l]*(wknb+last)->z <= (wknb+last)->dot)
                            {
                                for (j = 0; j < nnei; j++)
                                {
                                    if (xus[3*l]*(wknb+j)->x+xus[1+3*l]*(wknb+j)->y+
                                        xus[2+3*l]*(wknb+j)->z > (wknb+j)->dot)
                                    {
                                        last = j;
                                        break;
                                    }
                                }
                                if (j >= nnei)
                                {
                                    i_ac++;
                                    wkdot[l] = 1;
                                }
                            } /* end of cycle j */
                        }     /* end of cycle l */
                    }
                    else
                    {
                        i_ac  = n_dot;
                        for (l = 0; l < n_dot; l++)
                        {
                            wkdot[l] = 1;
                        }
                    }

                    if (debug)
                    {
                        fprintf(debug, "i_ac=%d, dotarea=%8.3f, aisq=%8.3f\n",
                                i_ac, dotarea, aisq);
                    }

                    a    = aisq*dotarea* (real) i_ac;
                    area = area + a;
                    if (mode & FLAG_ATOM_AREA)
                    {
                        range_check(wkatm[iat], 0, nat);
                        atom_area[wkatm[iat]] = a;
                    }
                    if (mode & FLAG_DOTS)
                    {
                        for (l = 0; l < n_dot; l++)
                        {
                            if (wkdot[l])
                            {
                                lfnr++;
                                if (maxdots <= 3*lfnr+1)
                                {
                                    maxdots = maxdots+n_dot*3;
                                    srenew(dots, maxdots);
                                }
                                dots[3*lfnr-3] = ai*xus[3*l]+xi;
                                dots[3*lfnr-2] = ai*xus[1+3*l]+yi;
                                dots[3*lfnr-1] = ai*xus[2+3*l]+zi;
                            }
                        }
                    }
                    if (mode & FLAG_VOLUME)
                    {
                        dx = 0.; dy = 0.; dz = 0.;
                        for (l = 0; l < n_dot; l++)
                        {
                            if (wkdot[l])
                            {
                                dx = dx+xus[3*l];
                                dy = dy+xus[1+3*l];
                                dz = dz+xus[2+3*l];
                            }
                        }
                        vol = vol+aisq*(dx*(xi-xs)+dy*(yi-ys)+dz*(zi-zs)+ai* (real) i_ac);
                    }

                } /* end of cycle "iat" */
            }     /* end of cycle "ix" */
        }         /* end of cycle "iy" */
    }             /* end of cycle "iz" */

    sfree(wkatm);
    sfree(wkat1);
    sfree(wkdot);
    sfree(wkbox);
    sfree(wknb);
    if (box)
    {
        sfree(x);
    }
    if (mode & FLAG_VOLUME)
    {
        vol           = vol*FOURPI/(3.* (real) n_dot);
        *value_of_vol = vol;
    }
    if (mode & FLAG_DOTS)
    {
        *nu_dots = lfnr;
        *lidots  = dots;
    }
    if (mode & FLAG_ATOM_AREA)
    {
        *at_area = atom_area;
    }
    *value_of_area = area;

    if (debug)
    {
        fprintf(debug, "area=%8.3f\n", area);
    }

    return 0;
}
Esempio n. 14
0
int make_unsp(int densit, int mode, int * num_dot, int cubus)
{
    int  *ico_wk, *ico_pt;
    int   ndot, ico_cube_cb, i, j, k, l, ijk, tn, tl, tl2;
    real *xus;
    int  *work;
    real  x, y, z;

    if (xpunsp)
    {
        free(xpunsp);
    }

    k = 1; if (mode < 0)
    {
        k = 0; mode = -mode;
    }
    if (mode == UNSP_ICO_ARC)
    {
        ndot = ico_dot_arc(densit);
    }
    else if (mode == UNSP_ICO_DOD)
    {
        ndot = ico_dot_dod(densit);
    }
    else
    {
        WARNING("make_unsp: mode %c%d not allowed", (k) ? '+' : '-', mode);
        return 1;
    }

    last_n_dot = ndot; last_densit = densit; last_unsp = mode;
    *num_dot   = ndot; if (k)
    {
        return 0;
    }

    /* in the following the dots of the unit sphere may be resorted */
    last_unsp = -last_unsp;

    /* determine distribution of points in elementary cubes */
    if (cubus)
    {
        ico_cube = cubus;
    }
    else
    {
        last_cubus = 0;
        i          = 1;
        while (i*i*i*2 < ndot)
        {
            i++;
        }
        ico_cube = max(i-1, 0);
    }
    ico_cube_cb = ico_cube*ico_cube*ico_cube;
    del_cube    = 2./((real)ico_cube);
    snew(work, ndot);
    xus = xpunsp;
    for (l = 0; l < ndot; l++)
    {
        i = max((int) floor((1.+xus[3*l])/del_cube), 0);
        if (i >= ico_cube)
        {
            i = ico_cube-1;
        }
        j = max((int) floor((1.+xus[1+3*l])/del_cube), 0);
        if (j >= ico_cube)
        {
            j = ico_cube-1;
        }
        k = max((int) floor((1.+xus[2+3*l])/del_cube), 0);
        if (k >= ico_cube)
        {
            k = ico_cube-1;
        }
        ijk     = i+j*ico_cube+k*ico_cube*ico_cube;
        work[l] = ijk;
    }

    snew(ico_wk, 2*ico_cube_cb+1);

    ico_pt = ico_wk+ico_cube_cb;
    for (l = 0; l < ndot; l++)
    {
        ico_wk[work[l]]++; /* dots per elementary cube */
    }

    /* reordering of the coordinate array in accordance with box number */
    tn = 0;
    for (i = 0; i < ico_cube; i++)
    {
        for (j = 0; j < ico_cube; j++)
        {
            for (k = 0; k < ico_cube; k++)
            {
                tl            = 0;
                tl2           = tn;
                ijk           = i+ico_cube*j+ico_cube*ico_cube*k;
                *(ico_pt+ijk) = tn;
                for (l = tl2; l < ndot; l++)
                {
                    if (ijk == work[l])
                    {
                        x          = xus[3*l]; y = xus[1+3*l]; z = xus[2+3*l];
                        xus[3*l]   = xus[3*tn];
                        xus[1+3*l] = xus[1+3*tn]; xus[2+3*l] = xus[2+3*tn];
                        xus[3*tn]  = x; xus[1+3*tn] = y; xus[2+3*tn] = z;
                        ijk        = work[l]; work[l] = work[tn]; work[tn] = ijk;
                        tn++; tl++;
                    }
                }
                *(ico_wk+ijk) = tl;
            } /* cycle k */
        }     /* cycle j */
    }         /* cycle i */
    sfree(ico_wk);
    sfree(work);

    return 0;
}
Esempio n. 15
0
File: xml.c Progetto: steev/libiio
static struct iio_context * iio_create_xml_context_helper(xmlDoc *doc)
{
    unsigned int i;
    xmlNode *root, *n;
    xmlAttr *attr;
    int err = ENOMEM;
    struct iio_context *ctx = calloc(1, sizeof(*ctx));
    if (!ctx)
        goto err_set_errno;

    ctx->name = "xml";
    ctx->ops = &xml_ops;

    root = xmlDocGetRootElement(doc);
    if (strcmp((char *) root->name, "context")) {
        ERROR("Unrecognized XML file\n");
        err = EINVAL;
        goto err_free_ctx;
    }

    for (attr = root->properties; attr; attr = attr->next) {
        if (!strcmp((char *) attr->name, "description"))
            ctx->description = _strdup(
                                   (char *) attr->children->content);
        else if (strcmp((char *) attr->name, "name"))
            WARNING("Unknown parameter \'%s\' in <context>\n",
                    (char *) attr->children->content);
    }

    for (n = root->children; n; n = n->next) {
        struct iio_device **devs, *dev;

        if (strcmp((char *) n->name, "device")) {
            if (strcmp((char *) n->name, "text"))
                WARNING("Unknown children \'%s\' in "
                        "<context>\n", n->name);
            continue;
        }

        dev = create_device(ctx, n);
        if (!dev) {
            ERROR("Unable to create device\n");
            goto err_free_devices;
        }

        devs = realloc(ctx->devices, (1 + ctx->nb_devices) *
                       sizeof(struct iio_device *));
        if (!devs) {
            ERROR("Unable to allocate memory\n");
            free(dev);
            goto err_free_devices;
        }

        devs[ctx->nb_devices++] = dev;
        ctx->devices = devs;
    }

    iio_context_init(ctx);
    return ctx;

err_free_devices:
    for (i = 0; i < ctx->nb_devices; i++)
        free_device(ctx->devices[i]);
    if (ctx->nb_devices)
        free(ctx->devices);
err_free_ctx:
    free(ctx);
err_set_errno:
    errno = err;
    return NULL;
}
Esempio n. 16
0
static int csnmp_config_add_data (oconfig_item_t *ci)
{
  data_definition_t *dd;
  int status = 0;
  int i;

  if ((ci->values_num != 1)
      || (ci->values[0].type != OCONFIG_TYPE_STRING))
  {
    WARNING ("snmp plugin: The `Data' config option needs exactly one string argument.");
    return (-1);
  }

  dd = (data_definition_t *) malloc (sizeof (data_definition_t));
  if (dd == NULL)
    return (-1);
  memset (dd, '\0', sizeof (data_definition_t));

  dd->name = strdup (ci->values[0].value.string);
  if (dd->name == NULL)
  {
    free (dd);
    return (-1);
  }
  dd->scale = 1.0;
  dd->shift = 0.0;

  for (i = 0; i < ci->children_num; i++)
  {
    oconfig_item_t *option = ci->children + i;
    status = 0;

    if (strcasecmp ("Type", option->key) == 0)
      status = csnmp_config_add_data_type (dd, option);
    else if (strcasecmp ("Table", option->key) == 0)
      status = csnmp_config_add_data_table (dd, option);
    else if (strcasecmp ("Instance", option->key) == 0)
      status = csnmp_config_add_data_instance (dd, option);
    else if (strcasecmp ("InstancePrefix", option->key) == 0)
      status = csnmp_config_add_data_instance_prefix (dd, option);
    else if (strcasecmp ("Values", option->key) == 0)
      status = csnmp_config_add_data_values (dd, option);
    else if (strcasecmp ("Shift", option->key) == 0)
      status = csnmp_config_add_data_shift (dd, option);
    else if (strcasecmp ("Scale", option->key) == 0)
      status = csnmp_config_add_data_scale (dd, option);
    else
    {
      WARNING ("snmp plugin: Option `%s' not allowed here.", option->key);
      status = -1;
    }

    if (status != 0)
      break;
  } /* for (ci->children) */

  while (status == 0)
  {
    if (dd->type == NULL)
    {
      WARNING ("snmp plugin: `Type' not given for data `%s'", dd->name);
      status = -1;
      break;
    }
    if (dd->values == NULL)
    {
      WARNING ("snmp plugin: No `Value' given for data `%s'", dd->name);
      status = -1;
      break;
    }

    break;
  } /* while (status == 0) */

  if (status != 0)
  {
    sfree (dd->name);
    sfree (dd->instance_prefix);
    sfree (dd->values);
    sfree (dd);
    return (-1);
  }

  DEBUG ("snmp plugin: dd = { name = %s, type = %s, is_table = %s, values_len = %i }",
      dd->name, dd->type, (dd->is_table != 0) ? "true" : "false", dd->values_len);

  if (data_head == NULL)
    data_head = dd;
  else
  {
    data_definition_t *last;
    last = data_head;
    while (last->next != NULL)
      last = last->next;
    last->next = dd;
  }

  return (0);
} /* int csnmp_config_add_data */
Esempio n. 17
0
LRESULT CFrameHolder::OnPaint(HWND hWnd, HDC hdc, UINT uMsg)
{
	if (hdc == NULL)
	{
		LRESULT lRc = 0;
		PAINTSTRUCT ps = {0};
		hdc = BeginPaint(hWnd, &ps);

		if (hdc != NULL)
		{
			lRc = OnPaint(hWnd, hdc, uMsg);

			EndPaint(hWnd, &ps);
		}
		else
		{
			_ASSERTE(hdc != NULL);
		}

		return lRc;
	}

	#ifdef _DEBUG
	RECT rcClientReal = {}; GetClientRect(hWnd, &rcClientReal);
	MapWindowPoints(hWnd, NULL, (LPPOINT)&rcClientReal, 2);
	#endif

	// Если "завис" PostUpdate
	if (gpConEmu->mp_TabBar->NeedPostUpdate())
		gpConEmu->mp_TabBar->Update();

	// Go

	RECT wr, cr;

	RecalculateFrameSizes();

	wr = gpConEmu->GetGuiClientRect();

	#ifdef _DEBUG
	wchar_t szPaint[140];
	_wsprintf(szPaint, SKIPCOUNT(szPaint) L"MainClient %s at {%i,%i}-{%i,%i} screen coords, size (%ix%i) calc (%ix%i)",
		(uMsg == WM_PAINT) ? L"WM_PAINT" : (uMsg == WM_PRINTCLIENT) ? L"WM_PRINTCLIENT" : L"UnknownMsg",
		LOGRECTCOORDS(rcClientReal), LOGRECTSIZE(rcClientReal), LOGRECTSIZE(wr));
	DEBUGSTRPAINT(szPaint);
	#endif

#if defined(CONEMU_TABBAR_EX)
#ifdef RED_CLIENT_FILL
	HBRUSH h = CreateSolidBrush(RGB(255,0,0));
	FillRect(hdc, &wr, h);
	DeleteObject(h);
	return 0;
#endif
#endif

	if (gpSet->isStatusBarShow)
	{
		int nHeight = gpSet->StatusBarHeight();
		if (nHeight < (wr.bottom - wr.top))
		{
			RECT rcStatus = {wr.left, wr.bottom - nHeight, wr.right, wr.bottom};
			gpConEmu->mp_Status->PaintStatus(hdc, &rcStatus);
			wr.bottom = rcStatus.top;
		}
	}

	cr = wr;

	DEBUGTEST(FrameDrawStyle dt = gpConEmu->DrawType());


#if defined(CONEMU_TABBAR_EX)
	RECT tr = {};

	if (!gpSet->isTabsInCaption)
	{
		_ASSERTE(gpConEmu->GetDwmClientRectTopOffset() == 0); // CheckIt, must be zero

		if (gpSet->isTabs)
		{
			RECT captrect = gpConEmu->CalcRect(CER_TAB, wr, CER_MAINCLIENT);
			//CalculateCaptionPosition(cr, &captrect);
			CalculateTabPosition(cr, captrect, &tr);

			PaintDC dc = {false};
			RECT pr = {captrect.left, 0, captrect.right, captrect.bottom};
			gpConEmu->BeginBufferedPaint(hdc, pr, dc);

			gpConEmu->mp_TabBar->PaintTabs(dc, captrect, tr);

			gpConEmu->EndBufferedPaint(dc, TRUE);
		}

	}
	else if (dt == fdt_Aero || dt == fdt_Win8)
	{
		_ASSERTE(gpSet->isTabsInCaption);

		int nOffset = gpConEmu->GetDwmClientRectTopOffset();
		// "Рамка" расширена на клиентскую область, поэтому
		// нужно зарисовать заголовок черной кистью, иначе идет
		// искажение цвета для кнопок Min/Max/Close

		if (gpSet->isTabs)
		{
			RECT captrect = gpConEmu->CalcRect(CER_TAB, wr, CER_MAINCLIENT);
			//CalculateCaptionPosition(cr, &captrect);
			CalculateTabPosition(cr, captrect, &tr);

			PaintDC dc = {false};
			RECT pr = {captrect.left, 0, captrect.right, captrect.bottom};
			gpConEmu->BeginBufferedPaint(hdc, pr, dc);

			gpConEmu->mp_TabBar->PaintTabs(dc, captrect, tr);

			gpConEmu->EndBufferedPaint(dc, TRUE);

			// There is no "Glass" in Win8
			mb_WasGlassDraw = IsWindows7 && !IsWindows8;
		}

		cr.top += nOffset;
	}
#endif

	#ifdef _DEBUG
	int nWidth = (cr.right-cr.left);
	int nHeight = (cr.bottom-cr.top);
	#endif

	WARNING("Пока табы рисуем не сами и ExtendDWM отсутствует - дополнительные изыски с временным DC не нужны");
#if 0
	if (!gpSet->isTabsInCaption)
	{
		//OnPaintClient(hdc/*, nWidth, nHeight*/);
	}
	else
	// Создадим временный DC, для удобства отрисовки в Glass-режиме и для фикса глюка DWM(?) см.ниже
	// В принципе, для режима Win2k/XP временный DC можно не создавать, если это будет тормозить
	{
		//_ASSERTE(FALSE && "Need to be rewritten");

		HDC hdcPaint = CreateCompatibleDC(hdc);
		HBITMAP hbmp = CreateCompatibleBitmap(hdc, nWidth, nHeight);
		HBITMAP hOldBmp = (HBITMAP)SelectObject(hdcPaint, hbmp);

		//OnPaintClient(hdcPaint/*, nWidth, nHeight*/);

		if ((dt == fdt_Aero) || !(mb_WasGlassDraw && gpConEmu->isZoomed()))
		{
			BitBlt(hdc, cr.left, cr.top, nWidth, nHeight, hdcPaint, 0, 0, SRCCOPY);
		}
		else
		{
			//mb_WasGlassDraw = FALSE;
			// Какой-то странный глюк DWM. При отключении Glass несколько верхних строк
			// клиентской области оказываются "разрушенными" - у них остается атрибут "прозрачности"
			// хотя прозрачность (Glass) уже отключена. В результате эти строки - белесые

			BITMAPINFOHEADER bi = {sizeof(BITMAPINFOHEADER)};
			bi.biWidth = cr.right-cr.left+1;
			bi.biHeight = GetFrameHeight()+1;
			bi.biPlanes = 1;
			bi.biBitCount = 32;
			COLORREF *pPixels = NULL;
			HDC hdcTmp = CreateCompatibleDC(hdc);
			HBITMAP hTmp = CreateDIBSection(hdcTmp, (BITMAPINFO*)&bi, DIB_RGB_COLORS, (void**)&pPixels, NULL, 0);
			if (hTmp == NULL)
			{
				_ASSERTE(hTmp == NULL);
				BitBlt(hdc, cr.left, cr.top, nWidth, nHeight, hdcPaint, 0, 0, SRCCOPY);
			}
			else
			{
				HBITMAP hOldTmp = (HBITMAP)SelectObject(hdcTmp, hTmp);

				BitBlt(hdcTmp, 0, 0, bi.biWidth, bi.biHeight, hdcPaint, 0, 0, SRCCOPY);

				int i = 0;
				for (int y = 0; y < bi.biHeight; y++)
				{
					for (int x = 0; x < bi.biWidth; x++)
					{
						pPixels[i++] |= 0xFF000000;
					}
				}

				BitBlt(hdc, cr.left, cr.top, bi.biWidth, bi.biHeight, hdcTmp, 0, 0, SRCCOPY);
				if (nHeight > bi.biHeight)
					BitBlt(hdc, cr.left, cr.top+bi.biHeight, nWidth, nHeight-bi.biHeight, hdcPaint, 0, bi.biHeight, SRCCOPY);

				SelectObject(hdcTmp, hOldTmp);
				DeleteObject(hbmp);
			}
			DeleteDC(hdcTmp);
		}

		SelectObject(hdcPaint, hOldBmp);
		DeleteObject(hbmp);
		DeleteDC(hdcPaint);
	}
#endif

	return 0;
}
Esempio n. 18
0
static int csnmp_config_add_host (oconfig_item_t *ci)
{
  host_definition_t *hd;
  int status = 0;
  int i;

  /* Registration stuff. */
  char cb_name[DATA_MAX_NAME_LEN];
  user_data_t cb_data;
  struct timespec cb_interval;

  if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
  {
    WARNING ("snmp plugin: `Host' needs exactly one string argument.");
    return (-1);
  }

  hd = (host_definition_t *) malloc (sizeof (host_definition_t));
  if (hd == NULL)
    return (-1);
  memset (hd, '\0', sizeof (host_definition_t));
  hd->version = 2;
  C_COMPLAIN_INIT (&hd->complaint);

  hd->name = strdup (ci->values[0].value.string);
  if (hd->name == NULL)
  {
    free (hd);
    return (-1);
  }

  hd->sess_handle = NULL;
  hd->interval = 0;

  for (i = 0; i < ci->children_num; i++)
  {
    oconfig_item_t *option = ci->children + i;
    status = 0;

    if (strcasecmp ("Address", option->key) == 0)
      status = csnmp_config_add_host_address (hd, option);
    else if (strcasecmp ("Community", option->key) == 0)
      status = csnmp_config_add_host_community (hd, option);
    else if (strcasecmp ("Version", option->key) == 0)
      status = csnmp_config_add_host_version (hd, option);
    else if (strcasecmp ("Collect", option->key) == 0)
      csnmp_config_add_host_collect (hd, option);
    else if (strcasecmp ("Interval", option->key) == 0)
      cf_util_get_cdtime (option, &hd->interval);
    else
    {
      WARNING ("snmp plugin: csnmp_config_add_host: Option `%s' not allowed here.", option->key);
      status = -1;
    }

    if (status != 0)
      break;
  } /* for (ci->children) */

  while (status == 0)
  {
    if (hd->address == NULL)
    {
      WARNING ("snmp plugin: `Address' not given for host `%s'", hd->name);
      status = -1;
      break;
    }
    if (hd->community == NULL)
    {
      WARNING ("snmp plugin: `Community' not given for host `%s'", hd->name);
      status = -1;
      break;
    }

    break;
  } /* while (status == 0) */

  if (status != 0)
  {
    csnmp_host_definition_destroy (hd);
    return (-1);
  }

  DEBUG ("snmp plugin: hd = { name = %s, address = %s, community = %s, version = %i }",
      hd->name, hd->address, hd->community, hd->version);

  ssnprintf (cb_name, sizeof (cb_name), "snmp-%s", hd->name);

  memset (&cb_data, 0, sizeof (cb_data));
  cb_data.data = hd;
  cb_data.free_func = csnmp_host_definition_destroy;

  CDTIME_T_TO_TIMESPEC (hd->interval, &cb_interval);

  status = plugin_register_complex_read (/* group = */ NULL, cb_name,
      csnmp_read_host, /* interval = */ &cb_interval,
      /* user_data = */ &cb_data);
  if (status != 0)
  {
    ERROR ("snmp plugin: Registering complex read function failed.");
    csnmp_host_definition_destroy (hd);
    return (-1);
  }

  return (0);
} /* int csnmp_config_add_host */
Esempio n. 19
0
/**
 *  Static: Rename a data file.
 *
 *  This function will rename a raw data file into the datastream directory
 *  using the datastream name and begin_time to give it a fully qualified
 *  ARM name.
 *
 *  The begin_time will be validated using:
 *
 *      dsproc_validate_datastream_data_time()
 *
 *  If the end_time is specified, this function will verify that it is greater
 *  than the begin_time and is not in the future. If only one record was found
 *  in the raw file, the end_time argument must be set to NULL.
 *
 *  If the output file exists and has the same MD5 as the input file,
 *  the input file will be removed and a warning message will be generated.
 *
 *  If the output file exists and has a different MD5 than the input
 *  file, the rename will fail.
 *
 *  If an error occurs in this function it will be appended to the log and
 *  error mail messages, and the process status will be set appropriately.
 *
 *  @param  ds_id      - datastream ID
 *  @param  file_path  - path to the directory the file is in
 *  @param  file_name  - name of the file to rename
 *  @param  begin_time - time of the first record in the file
 *  @param  end_time   - time of the last record in the file
 *  @param  extension  - extension to use when renaming the file, or NULL to
 *                       use the default extension for the datastream format.
 *
 *  @return
 *    - 1 if successful
 *    - 0 if an error occurred
 */
static int _dsproc_rename(
    int              ds_id,
    const char      *file_path,
    const char      *file_name,
    const timeval_t *begin_time,
    const timeval_t *end_time,
    const char      *extension)
{
    DataStream *ds         = _DSProc->datastreams[ds_id];
    time_t      now        = time(NULL);
    int         force_mode = dsproc_get_force_mode();
    char        src_file[PATH_MAX];
    struct stat src_stats;
    char        src_md5[64];
    char        done_dir[PATH_MAX];
    char       *dest_path;
    char        dest_name[256];
    char        dest_file[PATH_MAX];
    char        dest_md5[64];
    struct tm   time_stamp_tm;
    char        time_stamp[32];
    char        time_string1[32];
    char        time_string2[32];
    const char *preserve;
    int         dot_count;
    char        rename_error[2*PATH_MAX];
    int         rename_file;

    memset(&time_stamp_tm, 0, sizeof(struct tm));

    DEBUG_LV1( DSPROC_LIB_NAME,
        "%s: Renaming file: %s/%s\n",
        ds->name, file_path, file_name);

    /************************************************************
    *  Get source file stats
    *************************************************************/

    snprintf(src_file, PATH_MAX, "%s/%s", file_path, file_name);

    if (access(src_file, F_OK) != 0) {

        if (errno == ENOENT) {

            ERROR( DSPROC_LIB_NAME,
                "Could not rename file: %s\n"
                " -> file does not exist\n", src_file);

            dsproc_set_status(DSPROC_ENOSRCFILE);
        }
        else {

            ERROR( DSPROC_LIB_NAME,
                "Could not access file: %s\n"
                " -> %s\n", src_file, strerror(errno));

            dsproc_set_status(DSPROC_EACCESS);
        }

        return(0);
    }

    if (stat(src_file, &src_stats) < 0) {

        ERROR( DSPROC_LIB_NAME,
            "Could not rename file: %s\n"
            " -> stat error: %s\n", src_file, strerror(errno));

        dsproc_set_status(DSPROC_EFILESTATS);
        return(0);
    }

    /************************************************************
    *  Validate datastream times
    *************************************************************/

    /* validate begin time */

    if (!force_mode) {

        if (!begin_time || !begin_time->tv_sec) {

            ERROR( DSPROC_LIB_NAME,
                "Could not rename file: %s\n"
                " -> file time not specified\n", src_file);

            dsproc_set_status(DSPROC_ENOFILETIME);
            return(0);
        }

        if (!dsproc_validate_datastream_data_time(ds_id, begin_time)) {

            ERROR( DSPROC_LIB_NAME,
                "Could not rename file: %s\n"
                " -> time validation error\n", src_file);

            return(0);
        }

        /* validate end time */

        if (end_time && end_time->tv_sec) {

            if (TV_LTEQ(*end_time, *begin_time)) {

                format_timeval(begin_time, time_string2);
                format_timeval(end_time,   time_string1);

                ERROR( DSPROC_LIB_NAME,
                    "Could not rename file: %s\n"
                    " -> end time '%s' <= begin time '%s'\n",
                    src_file, time_string1, time_string2);

                dsproc_set_status(DSPROC_ETIMEORDER);
                return(0);
            }
            else if (end_time->tv_sec > now) {

                format_timeval(end_time, time_string1);
                format_secs1970(now, time_string2);

                ERROR( DSPROC_LIB_NAME,
                    "Could not rename file: %s\n"
                    " -> data time '%s' is in the future (current time is: %s)\n",
                    src_file, time_string1, time_string2);

                dsproc_disable(DSPROC_EFUTURETIME);
                return(0);
            }
        }
    }

    /************************************************************
    *  Determine the portion of the original file name to preserve
    *************************************************************/

    preserve = (const char *)NULL;

    if (ds->preserve_dots > 0) {

        dot_count = 0;

        for (preserve = file_name + strlen(file_name) - 1;
             preserve != file_name;
             preserve--) {

            if (*preserve == '.') {
                dot_count++;
                if (dot_count == ds->preserve_dots) {
                    preserve++;
                    break;
                }
            }
        }
    }

    /************************************************************
    *  Get the full path to the destination directory
    *************************************************************/

    snprintf(done_dir, PATH_MAX, "%s/.done", file_path);

    if (access(done_dir, F_OK) == 0) {
        dest_path = done_dir;
    }
    else if (errno != ENOENT) {

        ERROR( DSPROC_LIB_NAME,
            "Could not access directory: %s\n"
            " -> %s\n", done_dir, strerror(errno));

        dsproc_set_status(DSPROC_EACCESS);
        return(0);
    }
    else {

        dest_path = ds->dir->path;

        /* Make sure the destination directory exists */

        if (!make_path(dest_path, 0775)) {

            ERROR( DSPROC_LIB_NAME,
                "Could not rename file: %s\n"
                " -> make_path failed for: %s\n",
                src_file, dest_path);

            dsproc_set_status(DSPROC_EDESTDIRMAKE);
            return(0);
        }
    }

    /************************************************************
    *  Create the time stamp for the destination file
    *************************************************************/

    if (!gmtime_r(&begin_time->tv_sec, &time_stamp_tm)) {

        ERROR( DSPROC_LIB_NAME,
            "Could not rename file: %s\n"
            " -> gmtime error: %s\n",
            src_file, strerror(errno));

        dsproc_set_status(DSPROC_ETIMECALC);
        return(0);
    }

    strftime(time_stamp, 32, "%Y%m%d.%H%M%S", &time_stamp_tm);

    /************************************************************
    *  Create the output file name
    *************************************************************/

    if (!extension) {
        extension = ds->extension;
    }

    if (preserve) {
        snprintf(dest_name, 256, "%s.%s.%s.%s",
            ds->name, time_stamp, extension, preserve);
    }
    else {
        snprintf(dest_name, 256, "%s.%s.%s",
            ds->name, time_stamp, extension);
    }

    snprintf(dest_file, PATH_MAX, "%s/%s", dest_path, dest_name);

    /************************************************************
    *  Check if the output file already exists
    *************************************************************/

    rename_file = 1;

    if (access(dest_file, F_OK) == 0) {

        sprintf(rename_error,
            "\n"
            "Found existing destination file while renaming source file:\n"
            " -> from: %s\n"
            " -> to:   %s\n",
            src_file, dest_file);

        /* Check the MD5s */

        if (!file_get_md5(src_file, src_md5)) {

            ERROR( DSPROC_LIB_NAME,
                "%s -> could not get source file MD5\n",
                rename_error);

            dsproc_set_status(DSPROC_EFILEMD5);
            return(0);
        }

        if (!file_get_md5(dest_file, dest_md5)) {

            ERROR( DSPROC_LIB_NAME,
                "%s -> could not get destination file MD5\n",
                rename_error);

            dsproc_set_status(DSPROC_EFILEMD5);
            return(0);
        }

        if (strcmp(src_md5, dest_md5) == 0) {

            /* The MD5s match so delete the input file */

            if (unlink(src_file) < 0) {

                ERROR( DSPROC_LIB_NAME,
                    "%s"
                    " -> source and destination files have matching MD5s\n"
                    " -> could not delete source file: %s\n",
                    rename_error, strerror(errno));

                dsproc_set_status(DSPROC_EUNLINK);
                return(0);
            }

            WARNING( DSPROC_LIB_NAME,
                "%s"
                " -> source and destination files have matching MD5s\n"
                " -> deleted source file\n",
                rename_error);

            rename_file = 0;
        }
        else {

            /* The MD5s do not match */

            ERROR( DSPROC_LIB_NAME,
                "%s"
                " -> source and destination files have different MD5s\n",
                rename_error);

            dsproc_set_status(DSPROC_EMD5CHECK);
            return(0);
        }
    }
    else if (errno != ENOENT) {

        ERROR( DSPROC_LIB_NAME,
            "Could not access file: %s\n"
            " -> %s\n", dest_file, strerror(errno));

        dsproc_set_status(DSPROC_EACCESS);
        return(0);
    }

    /************************************************************
    *  Rename the file
    *************************************************************/

    if (rename_file) {

        LOG( DSPROC_LIB_NAME,
            "Renaming:   %s\n"
            " -> to:     %s\n",
            src_file, dest_file);

        if (!file_move(src_file, dest_file, FC_CHECK_MD5)) {
            dsproc_set_status(DSPROC_EFILEMOVE);
            return(0);
        }

        /* Update the access and modification times */

        utime(dest_file, NULL);
    }

    /************************************************************
    *  Update the datastream file stats
    *************************************************************/

    dsproc_update_datastream_file_stats(
        ds_id, (double)src_stats.st_size, begin_time, end_time);

    return(1);
}
Esempio n. 20
0
/* TODO: Check if negative values wrap around. Problem: negative temperatures. */
static value_t csnmp_value_list_to_value (struct variable_list *vl, int type,
    double scale, double shift,
    const char *host_name, const char *data_name)
{
  value_t ret;
  uint64_t tmp_unsigned = 0;
  int64_t tmp_signed = 0;
  _Bool defined = 1;
  /* Set to true when the original SNMP type appears to have been signed. */
  _Bool prefer_signed = 0;

  if ((vl->type == ASN_INTEGER)
      || (vl->type == ASN_UINTEGER)
      || (vl->type == ASN_COUNTER)
#ifdef ASN_TIMETICKS
      || (vl->type == ASN_TIMETICKS)
#endif
      || (vl->type == ASN_GAUGE))
  {
    tmp_unsigned = (uint32_t) *vl->val.integer;
    tmp_signed = (int32_t) *vl->val.integer;

    if ((vl->type == ASN_INTEGER)
        || (vl->type == ASN_GAUGE))
      prefer_signed = 1;

    DEBUG ("snmp plugin: Parsed int32 value is %"PRIu64".", tmp_unsigned);
  }
  else if (vl->type == ASN_COUNTER64)
  {
    tmp_unsigned = (uint32_t) vl->val.counter64->high;
    tmp_unsigned = tmp_unsigned << 32;
    tmp_unsigned += (uint32_t) vl->val.counter64->low;
    tmp_signed = (int64_t) tmp_unsigned;
    DEBUG ("snmp plugin: Parsed int64 value is %"PRIu64".", tmp_unsigned);
  }
  else if (vl->type == ASN_OCTET_STR)
  {
    /* We'll handle this later.. */
  }
  else
  {
    char oid_buffer[1024];

    memset (oid_buffer, 0, sizeof (oid_buffer));
    snprint_objid (oid_buffer, sizeof (oid_buffer) - 1,
        vl->name, vl->name_length);

#ifdef ASN_NULL
    if (vl->type == ASN_NULL)
      INFO ("snmp plugin: OID \"%s\" is undefined (type ASN_NULL)",
          oid_buffer);
    else
#endif
      WARNING ("snmp plugin: I don't know the ASN type #%i "
               "(OID: \"%s\", data block \"%s\", host block \"%s\")",
          (int) vl->type, oid_buffer,
          (data_name != NULL) ? data_name : "UNKNOWN",
          (host_name != NULL) ? host_name : "UNKNOWN");

    defined = 0;
  }

  if (vl->type == ASN_OCTET_STR)
  {
    int status = -1;

    if (vl->val.string != NULL)
    {
      char string[64];
      size_t string_length;

      string_length = sizeof (string) - 1;
      if (vl->val_len < string_length)
        string_length = vl->val_len;

      /* The strings we get from the Net-SNMP library may not be null
       * terminated. That is why we're using `memcpy' here and not `strcpy'.
       * `string_length' is set to `vl->val_len' which holds the length of the
       * string.  -octo */
      memcpy (string, vl->val.string, string_length);
      string[string_length] = 0;

      status = parse_value (string, &ret, type);
      if (status != 0)
      {
        ERROR ("snmp plugin: csnmp_value_list_to_value: Parsing string as %s failed: %s",
            DS_TYPE_TO_STRING (type), string);
      }
    }

    if (status != 0)
    {
      switch (type)
      {
        case DS_TYPE_COUNTER:
        case DS_TYPE_DERIVE:
        case DS_TYPE_ABSOLUTE:
          memset (&ret, 0, sizeof (ret));
          break;

        case DS_TYPE_GAUGE:
          ret.gauge = NAN;
          break;

        default:
          ERROR ("snmp plugin: csnmp_value_list_to_value: Unknown "
              "data source type: %i.", type);
          ret.gauge = NAN;
      }
    }
  } /* if (vl->type == ASN_OCTET_STR) */
  else if (type == DS_TYPE_COUNTER)
  {
    ret.counter = tmp_unsigned;
  }
  else if (type == DS_TYPE_GAUGE)
  {
    if (!defined)
      ret.gauge = NAN;
    else if (prefer_signed)
      ret.gauge = (scale * tmp_signed) + shift;
    else
      ret.gauge = (scale * tmp_unsigned) + shift;
  }
  else if (type == DS_TYPE_DERIVE)
  {
    if (prefer_signed)
      ret.derive = (derive_t) tmp_signed;
    else
      ret.derive = (derive_t) tmp_unsigned;
  }
  else if (type == DS_TYPE_ABSOLUTE)
  {
    ret.absolute = (absolute_t) tmp_unsigned;
  }
  else
  {
    ERROR ("snmp plugin: csnmp_value_list_to_value: Unknown data source "
        "type: %i.", type);
    ret.gauge = NAN;
  }

  return (ret);
} /* value_t csnmp_value_list_to_value */
Esempio n. 21
0
/* initialize curl for each host */
static int init_host (apache_t *st) /* {{{ */
{
	assert (st->url != NULL);
	/* (Assured by `config_add') */

	if (st->curl != NULL)
	{
		curl_easy_cleanup (st->curl);
		st->curl = NULL;
	}

	if ((st->curl = curl_easy_init ()) == NULL)
	{
		ERROR ("apache plugin: init_host: `curl_easy_init' failed.");
		return (-1);
	}

	curl_easy_setopt (st->curl, CURLOPT_NOSIGNAL, 1L);
	curl_easy_setopt (st->curl, CURLOPT_WRITEFUNCTION, apache_curl_callback);
	curl_easy_setopt (st->curl, CURLOPT_WRITEDATA, st);

	/* not set as yet if the user specified string doesn't match apache or
	 * lighttpd, then ignore it. Headers will be parsed to find out the
	 * server type */
	st->server_type = -1;

	if (st->server != NULL)
	{
		if (strcasecmp(st->server, "apache") == 0)
			st->server_type = APACHE;
		else if (strcasecmp(st->server, "lighttpd") == 0)
			st->server_type = LIGHTTPD;
		else if (strcasecmp(st->server, "ibm_http_server") == 0)
			st->server_type = APACHE;
		else
			WARNING ("apache plugin: Unknown `Server' setting: %s",
					st->server);
	}

	/* if not found register a header callback to determine the server_type */
	if (st->server_type == -1)
	{
		curl_easy_setopt (st->curl, CURLOPT_HEADERFUNCTION, apache_header_callback);
		curl_easy_setopt (st->curl, CURLOPT_WRITEHEADER, st);
	}

	curl_easy_setopt (st->curl, CURLOPT_USERAGENT, COLLECTD_USERAGENT);
	curl_easy_setopt (st->curl, CURLOPT_ERRORBUFFER, st->apache_curl_error);

	if (st->user != NULL)
	{
#ifdef HAVE_CURLOPT_USERNAME
		curl_easy_setopt (st->curl, CURLOPT_USERNAME, st->user);
		curl_easy_setopt (st->curl, CURLOPT_PASSWORD,
				(st->pass == NULL) ? "" : st->pass);
#else
		static char credentials[1024];
		int status;

		status = ssnprintf (credentials, sizeof (credentials), "%s:%s",
				st->user, (st->pass == NULL) ? "" : st->pass);
		if ((status < 0) || ((size_t) status >= sizeof (credentials)))
		{
			ERROR ("apache plugin: init_host: Returning an error "
					"because the credentials have been "
					"truncated.");
			curl_easy_cleanup (st->curl);
			st->curl = NULL;
			return (-1);
		}

		curl_easy_setopt (st->curl, CURLOPT_USERPWD, credentials);
#endif
	}

	curl_easy_setopt (st->curl, CURLOPT_URL, st->url);
	curl_easy_setopt (st->curl, CURLOPT_FOLLOWLOCATION, 1L);
	curl_easy_setopt (st->curl, CURLOPT_MAXREDIRS, 50L);

	curl_easy_setopt (st->curl, CURLOPT_SSL_VERIFYPEER,
			(long) st->verify_peer);
	curl_easy_setopt (st->curl, CURLOPT_SSL_VERIFYHOST,
			st->verify_host ? 2L : 0L);
	if (st->cacert != NULL)
		curl_easy_setopt (st->curl, CURLOPT_CAINFO, st->cacert);

	return (0);
} /* }}} int init_host */
Esempio n. 22
0
static int interface_read (void)
{
#if HAVE_GETIFADDRS
	struct ifaddrs *if_list;
	struct ifaddrs *if_ptr;

/* Darin/Mac OS X and possible other *BSDs */
#if HAVE_STRUCT_IF_DATA
#  define IFA_DATA if_data
#  define IFA_RX_BYTES ifi_ibytes
#  define IFA_TX_BYTES ifi_obytes
#  define IFA_RX_PACKT ifi_ipackets
#  define IFA_TX_PACKT ifi_opackets
#  define IFA_RX_ERROR ifi_ierrors
#  define IFA_TX_ERROR ifi_oerrors
/* #endif HAVE_STRUCT_IF_DATA */

#elif HAVE_STRUCT_NET_DEVICE_STATS
#  define IFA_DATA net_device_stats
#  define IFA_RX_BYTES rx_bytes
#  define IFA_TX_BYTES tx_bytes
#  define IFA_RX_PACKT rx_packets
#  define IFA_TX_PACKT tx_packets
#  define IFA_RX_ERROR rx_errors
#  define IFA_TX_ERROR tx_errors
#else
#  error "No suitable type for `struct ifaddrs->ifa_data' found."
#endif

	struct IFA_DATA *if_data;

	if (getifaddrs (&if_list) != 0)
		return (-1);

	for (if_ptr = if_list; if_ptr != NULL; if_ptr = if_ptr->ifa_next)
	{
		if ((if_data = (struct IFA_DATA *) if_ptr->ifa_data) == NULL)
			continue;

		if_submit (if_ptr->ifa_name, "if_octets",
				if_data->IFA_RX_BYTES,
				if_data->IFA_TX_BYTES);
		if_submit (if_ptr->ifa_name, "if_packets",
				if_data->IFA_RX_PACKT,
				if_data->IFA_TX_PACKT);
		if_submit (if_ptr->ifa_name, "if_errors",
				if_data->IFA_RX_ERROR,
				if_data->IFA_TX_ERROR);
	}

	freeifaddrs (if_list);
/* #endif HAVE_GETIFADDRS */

#elif KERNEL_LINUX
	FILE *fh;
	char buffer[1024];
	unsigned long long incoming, outgoing;
	char *device;
	
	char *dummy;
	char *fields[16];
	int numfields;

	if ((fh = fopen ("/proc/net/dev", "r")) == NULL)
	{
		char errbuf[1024];
		WARNING ("interface plugin: fopen: %s",
				sstrerror (errno, errbuf, sizeof (errbuf)));
		return (-1);
	}

	while (fgets (buffer, 1024, fh) != NULL)
	{
		if (!(dummy = strchr(buffer, ':')))
			continue;
		dummy[0] = '\0';
		dummy++;

		device = buffer;
		while (device[0] == ' ')
			device++;

		if (device[0] == '\0')
			continue;
		
		numfields = strsplit (dummy, fields, 16);

		if (numfields < 11)
			continue;

		incoming = atoll (fields[0]);
		outgoing = atoll (fields[8]);
		if_submit (device, "if_octets", incoming, outgoing);

		incoming = atoll (fields[1]);
		outgoing = atoll (fields[9]);
		if_submit (device, "if_packets", incoming, outgoing);

		incoming = atoll (fields[2]);
		outgoing = atoll (fields[10]);
		if_submit (device, "if_errors", incoming, outgoing);
	}

	fclose (fh);
/* #endif KERNEL_LINUX */

#elif HAVE_LIBKSTAT
	int i;
	unsigned long long rx;
	unsigned long long tx;

	if (kc == NULL)
		return (-1);

	for (i = 0; i < numif; i++)
	{
		if (kstat_read (kc, ksp[i], NULL) == -1)
			continue;

		rx = get_kstat_value (ksp[i], "rbytes");
		tx = get_kstat_value (ksp[i], "obytes");
		if ((rx != -1LL) || (tx != -1LL))
			if_submit (ksp[i]->ks_name, "if_octets", rx, tx);

		rx = get_kstat_value (ksp[i], "ipackets");
		tx = get_kstat_value (ksp[i], "opackets");
		if ((rx != -1LL) || (tx != -1LL))
			if_submit (ksp[i]->ks_name, "if_packets", rx, tx);

		rx = get_kstat_value (ksp[i], "ierrors");
		tx = get_kstat_value (ksp[i], "oerrors");
		if ((rx != -1LL) || (tx != -1LL))
			if_submit (ksp[i]->ks_name, "if_errors", rx, tx);
	}
/* #endif HAVE_LIBKSTAT */

#elif defined(HAVE_LIBSTATGRAB)
	sg_network_io_stats *ios;
	int i, num;

	ios = sg_get_network_io_stats (&num);

	for (i = 0; i < num; i++)
		if_submit (ios[i].interface_name, "if_octets", ios[i].rx, ios[i].tx);
#endif /* HAVE_LIBSTATGRAB */

	return (0);
} /* int interface_read */
Esempio n. 23
0
int alsa_init(audiodevice_t *dev, int cardno, int pcmdev, int mixdev, boolean automix) {
	snd_ctl_t *ctl_handle;
	snd_ctl_hw_info_t *hwinfo;
	audio_alsa05_t *alsa;
	int i, j, ncards;
	snd_pcm_t *pcm_handle;
	
	/* サウンドカードが存在するかチェック */
	ncards = snd_cards();
	if (ncards < 1) {
		WARNING("No ALSA device found\n");
		return NG;
	}
	
	if (cardno == -1 && pcmdev == -1) {
		/* 最初に見つかった使用可能なカード */
		if (NULL == (hwinfo = (snd_ctl_hw_info_t *)malloc(sizeof(*hwinfo) * ncards))) {
			NOMEMERR();
			return NG;
		}
		for (i = 0; i < ncards; i++) {
			if (0 > snd_ctl_open(&ctl_handle, i)) {
				WARNING("Can't Open Card %d\n", i);
				free(hwinfo);
				return NG;
			}
			if (0 > snd_ctl_hw_info(ctl_handle, hwinfo + i)) {
				WARNING("Can't Get Card(%d) info\n", i);
				free(hwinfo);
				return NG;
			}
			snd_ctl_close(ctl_handle);
			for (j = 0; j < hwinfo[i].pcmdevs; j++) {
				//open してチェック OK なら outへ
				if (0 > snd_pcm_open(&pcm_handle, i, j, SND_PCM_OPEN_PLAYBACK)) continue;
				cardno = i; pcmdev  = j;
				snd_pcm_close(pcm_handle);
				NOTICE("ALSA Use(%d:%d) device\n", i, j);
				goto out;
			}
		}
		// 使用可能なデバイスが1つもない場合
		WARNING("Can't Get Card(%d) info\n", i);
		return NG;
	out:
		free(hwinfo);
	} else {
		/* 指定のカード */
		if (0 > snd_ctl_open(&ctl_handle, cardno)) {
			WARNING("Can't Open Card %d\n", cardno);
			return NG;
		}
		snd_ctl_close(ctl_handle);
		
		/* 指定の pcmdevice がカードの中にあるかどうか */
		if (pcmdev >= 0 && pcmdev < hwinfo[cardno].pcmdevs) {
			//opne してチェック
			if (0 > snd_pcm_open(&pcm_handle, cardno, pcmdev, SND_PCM_OPEN_PLAYBACK)) {
				WARNING("Can't Open (%d:%d)\n", cardno, pcmdev);
				return NG;
			}
			snd_pcm_close(pcm_handle);
			NOTICE("ALSA Use(%d:%d) device\n", cardno, pcmdev);
		} else {
			WARNING("Can't Open (%d:%d)\n", cardno, pcmdev);
			return NG;
		}
	}
	
	if (mixer_init(dev, cardno, mixdev, &hwinfo) < 0) {
		return NG;
	}
	
	alsa = g_new0(audio_alsa05_t, 1);
	
	alsa->card = cardno;
	alsa->pcm_dev = pcmdev;
	alsa->automixer = automix;
	
	dev->data_pcm = alsa;
	
	dev->id      = AUDIO_PCM_ALSA;
	dev->fd      = -1;
	dev->open    = audio_open;
	dev->close   = audio_close;
	dev->write   = audio_write;
	dev->mix_set = mixer_set_level;
	dev->mix_get = mixer_get_level;
	dev->exit    = alsa_exit;
	
	NOTICE("ALSA Initilize OK\n");
	return 0;
}
Esempio n. 24
0
static int redis_config_node (oconfig_item_t *ci) /* {{{ */
{
  redis_node_t rn;
  redis_query_t *rq;
  int i;
  int status;
  int timeout;

  memset (&rn, 0, sizeof (rn));
  sstrncpy (rn.host, REDIS_DEF_HOST, sizeof (rn.host));
  rn.port = REDIS_DEF_PORT;
  rn.timeout.tv_usec = REDIS_DEF_TIMEOUT;
  rn.queries = NULL;

  status = cf_util_get_string_buffer (ci, rn.name, sizeof (rn.name));
  if (status != 0)
    return (status);

  for (i = 0; i < ci->children_num; i++)
  {
    oconfig_item_t *option = ci->children + i;

    if (strcasecmp ("Host", option->key) == 0)
      status = cf_util_get_string_buffer (option, rn.host, sizeof (rn.host));
    else if (strcasecmp ("Port", option->key) == 0)
    {
      status = cf_util_get_port_number (option);
      if (status > 0)
      {
        rn.port = status;
        status = 0;
      }
    }
    else if (strcasecmp ("Query", option->key) == 0)
    {
      rq = redis_config_query(option);
      if (rq == NULL) {
          status =1;
      } else {
          rq->next = rn.queries;
          rn.queries = rq;
      }
    }
    else if (strcasecmp ("Timeout", option->key) == 0)
    {
      status = cf_util_get_int (option, &timeout);
      if (status == 0) rn.timeout.tv_usec = timeout;
    }
    else if (strcasecmp ("Password", option->key) == 0)
      status = cf_util_get_string_buffer (option, rn.passwd, sizeof (rn.passwd));
    else
      WARNING ("redis plugin: Option `%s' not allowed inside a `Node' "
          "block. I'll ignore this option.", option->key);

    if (status != 0)
      break;
  }

  if (status != 0)
    return (status);

  return (redis_node_add (&rn));
} /* }}} int redis_config_node */
static s32 goodix_tool_write(struct file *filp, const char __user *buff, unsigned long len, void *data)
{
    DEBUG_ARRAY((u8*)buff, len);
    
    copy_from_user(&cmd_head, buff, CMD_HEAD_LENGTH);

    DEBUG("wr  :0x%02x\n", cmd_head.wr);
    DEBUG("flag:0x%02x\n", cmd_head.flag);
    DEBUG("flag addr:0x%02x%02x\n", cmd_head.flag_addr[0], cmd_head.flag_addr[1]);
    DEBUG("flag val:0x%02x\n", cmd_head.flag_val);
    DEBUG("flag rel:0x%02x\n", cmd_head.flag_relation);
    DEBUG("circle  :%d\n", (s32)cmd_head.circle);
    DEBUG("times   :%d\n", (s32)cmd_head.times);
    DEBUG("retry   :%d\n", (s32)cmd_head.retry);
    DEBUG("delay   :%d\n", (s32)cmd_head.delay);
    DEBUG("data len:%d\n", (s32)cmd_head.data_len);
    DEBUG("addr len:%d\n", (s32)cmd_head.addr_len);
    DEBUG("addr:0x%02x%02x\n", cmd_head.addr[0], cmd_head.addr[1]);
    DEBUG("len:%d\n", (s32)len);
    DEBUG("buf[20]:0x%02x\n", buff[CMD_HEAD_LENGTH]);
    
    if (1 == cmd_head.wr)
    {
      //  copy_from_user(&cmd_head.data[cmd_head.addr_len], &buff[CMD_HEAD_LENGTH], cmd_head.data_len);
        copy_from_user(&cmd_head.data[ADDR_MAX_LENGTH], &buff[CMD_HEAD_LENGTH], cmd_head.data_len);
        memcpy(&cmd_head.data[ADDR_MAX_LENGTH - cmd_head.addr_len], cmd_head.addr, cmd_head.addr_len);

        DEBUG_ARRAY(cmd_head.data, cmd_head.data_len + cmd_head.addr_len);
        DEBUG_ARRAY((u8*)&buff[CMD_HEAD_LENGTH], cmd_head.data_len);
        
        if (1 == cmd_head.flag)
        {
            if (fail == comfirm())
            {
                WARNING("[WRITE]Comfirm fail!\n");
                return fail;
            }
        }
        else if (2 == cmd_head.flag)
        {
            //Need interrupt!
        }
        if (tool_i2c_write(&cmd_head.data[ADDR_MAX_LENGTH - cmd_head.addr_len],
            cmd_head.data_len + cmd_head.addr_len) <= 0)
        {
            WARNING("[WRITE]Write data failed!\n");
            return fail;
        }

        DEBUG_ARRAY(&cmd_head.data[ADDR_MAX_LENGTH - cmd_head.addr_len],cmd_head.data_len + cmd_head.addr_len);
        if (cmd_head.delay)
        {
            msleep(cmd_head.delay);
        }

        return cmd_head.data_len + CMD_HEAD_LENGTH;
    }
    else if (3 == cmd_head.wr)
    {
        memcpy(IC_TYPE, cmd_head.data, cmd_head.data_len);
        register_i2c_func();

        return cmd_head.data_len + CMD_HEAD_LENGTH;
    }
    else if (5 == cmd_head.wr)
    {
        //memcpy(IC_TYPE, cmd_head.data, cmd_head.data_len);

        return cmd_head.data_len + CMD_HEAD_LENGTH;
    }

    return CMD_HEAD_LENGTH;
}
Esempio n. 26
0
/** @todo Выбирать путь к pid файлу из опций configure
*/
int main (int argc, char *argv[])
{
  int commands;
  int parse_errors = 0;
  int c;
  int err;
  uint dbglevel = 0;
  bool wait_myself = false;
  string optname = "";
  string logfilename = "";
  DateFilter *dateFilter = NULL;
  UserFilter *userFilter = NULL;
  bool verbose = false;
  string log_engine = "";
  string config_file = SYSCONFDIR;
  config_file += "/sams2.conf";

  static struct option long_options[] = {
    {"help",        0, 0, 'h'},    // Показывает справку по опциям командной строки и завершает работу
    {"version",     0, 0, 'V'},    // Показывает версию программы и завершает работу
    {"update",      0, 0, 'u'},    // Обновляет кэш в БД и счетчики пользователей
    {"export",      0, 0, 'e'},    // Экспортирует кэш в файл
    {"clear",       0, 0, 'c'},    // Очищает счетчики пользователей
    {"truncate",    0, 0, 't'},    // Очищает кэш в БД
    {"file",        1, 0, 'f'},    // Имя файла для импорта или экспорта
    {"user",        1, 0, 'U'},    // Фильтр по пользователям
    {"date",        1, 0, 'D'},    // Фильтр по датам
    {"verbose",     0, 0, 'v'},    // Устанавливает режим многословности
    {"debug",       1, 0, 'd'},    // Устанавливает уровень отладки
    {"logger",      1, 0, 'l'},    // Устанавливает движок вывода сообщений
    {"config",      1, 0, 'C'},    // Использовать альтернативный конфигурационный файл
    {"wait-myself", 0, 0, 'w'},    // Устанавливает движок вывода сообщений
    {0, 0, 0, 0}
  };

  commands = CMD_NONE;
  while (1)
    {
      int option_index = 0;

      c = getopt_long (argc, argv, "hVuectf:U:D:vd:l:C:w", long_options, &option_index);
      if (c == -1)              // no more options
        break;
      switch (c)
        {
        case 0:
          optname = long_options[option_index].name;
          break;
        case 'h':
          usage ();
          exit (0);
          break;
        case 'V':
          version ();
          exit (0);
          break;
        case 'u':
          commands += CMD_UPDATE;
          break;
        case 'e':
          commands += CMD_EXPORT;
          break;
        case 'c':
          commands += CMD_CLEAR;
          break;
        case 't':
          commands += CMD_TRUNCATE;
          break;
        case 'f':
          logfilename = optarg;
          break;
        case 'U':
          WARNING ("Filter for users is NOT implemented.");
          userFilter = new UserFilter (optarg);
          break;
        case 'D':
          dateFilter = new DateFilter (optarg);
          break;
        case 'v':
          verbose = true;
          break;
        case 'd':
          if (sscanf (optarg, "%d", &dbglevel) != 1)
            dbglevel = 0;
          break;
        case 'l':
          log_engine = optarg;
          break;
        case 'C':
          config_file = optarg;
          break;
        case 'w':
          wait_myself = true;
          break;
        case '?':
          break;
        default:
          printf ("?? getopt return character code 0%o ??\n", c);
        }
    }

  Logger::setSender("samsparser");
  SamsConfig::useFile (config_file);

  // Сначала прочитаем конфигурацию, параметры командной строки
  // имеют приоритет, потому анализируются позже
  SamsConfig::reload ();

  Logger::setEngine (log_engine);
  Logger::setVerbose (verbose);
  Logger::setDebugLevel (dbglevel);

  if (parse_errors > 0)
    {
      usage ();
      exit (parse_errors);
    }

  string squidlogdir = SamsConfig::getString (defSQUIDLOGDIR, err);
  string squidcachefile = SamsConfig::getString (defSQUIDCACHEFILE, err);

  if (squidlogdir.empty () || squidcachefile.empty ())
    {
      ERROR ("Either " << defSQUIDLOGDIR << " or " << defSQUIDCACHEFILE << " not defined. Check config file.");
      exit (1);
    }

  int proxyid = SamsConfig::getInt (defPROXYID, err);
  if (err != ERR_OK)
    {
      ERROR ("No proxyid defined. Check " << defPROXYID << " in config file.");
      exit (1);
    }

  ProcessManager process;

  if (!process.start ("samsparser", wait_myself))
    {
      exit (2);
    }

  SquidLogParser *parser = NULL;
  DBCleaner *cleaner = NULL;

  if ((commands & CMD_CLEAR) == CMD_CLEAR || (commands & CMD_TRUNCATE) == CMD_TRUNCATE)
    {
      cleaner = new DBCleaner ();
      cleaner->setDateFilter (dateFilter);
      cleaner->setUserFilter (userFilter);
    }

  if (commands == CMD_NONE)
    commands += CMD_UPDATE;

  bool parseFromBegin = true;
  while (commands != CMD_NONE)
    {
      if ((commands & CMD_UPDATE) == CMD_UPDATE)
        {
          INFO ("+++ Updating database");
          if (logfilename.empty ())
            {
              logfilename = squidlogdir + "/" + squidcachefile;
              parseFromBegin = false;
            }

          parser = new SquidLogParser (proxyid);

          parser->setDateFilter (dateFilter);
          parser->setUserFilter (userFilter);
          parser->parseFile (logfilename, parseFromBegin);

          delete parser;

          commands -= CMD_UPDATE;
        }
      else if ((commands & CMD_EXPORT) == CMD_EXPORT)
        {
          INFO ("+++ Exporting to the file");
          if (logfilename.empty ())
            logfilename = "squid.log";

          commands -= CMD_EXPORT;
        }
      else if ((commands & CMD_CLEAR) == CMD_CLEAR)
        {
          INFO ("+++ Clearing user's counters");
          cleaner->clearCounters ();
          commands -= CMD_CLEAR;
        }
      else if ((commands & CMD_TRUNCATE) == CMD_TRUNCATE)
        {
          INFO ("+++ Truncating cache in the database");
          cleaner->clearCache ();
          commands -= CMD_TRUNCATE;
        }
      else if (commands != CMD_NONE)
        {
          WARNING ("Unknown command[s] " << commands << " left unprocessed.");
          commands = CMD_NONE;
        }
    }

  if (cleaner != NULL)
    delete cleaner;

  process.stop ();

  LocalNetworks::destroy ();
  TemplateList::destroy ();
  SAMSUserList::destroy ();
  Proxy::destroy ();
  Logger::destroy ();
  SamsConfig::destroy ();
}
static int __init multi_bind(struct usb_composite_dev *cdev)
{
	struct usb_gadget *gadget = cdev->gadget;
	int status, gcnum;

	if (!can_support_ecm(cdev->gadget)) {
		dev_err(&gadget->dev, "controller '%s' not usable\n",
		        gadget->name);
		return -EINVAL;
	}

	/* set up network link layer */
	status = gether_setup(cdev->gadget, hostaddr);
	if (status < 0)
		return status;

	/* set up serial link layer */
	status = gserial_setup(cdev->gadget, 1);
	if (status < 0)
		goto fail0;

	/* set up mass storage function */
	fsg_common = fsg_common_from_params(0, cdev, &mod_data);
	if (IS_ERR(fsg_common)) {
		status = PTR_ERR(fsg_common);
		goto fail1;
	}


	gcnum = usb_gadget_controller_number(gadget);
	if (gcnum >= 0)
		device_desc.bcdDevice = cpu_to_le16(0x0300 | gcnum);
	else {
		/* We assume that can_support_ecm() tells the truth;
		 * but if the controller isn't recognized at all then
		 * that assumption is a bit more likely to be wrong.
		 */
		WARNING(cdev, "controller '%s' not recognized\n",
		        gadget->name);
		device_desc.bcdDevice = cpu_to_le16(0x0300 | 0x0099);
	}


	/* Allocate string descriptor numbers ... note that string
	 * contents can be overridden by the composite_dev glue.
	 */

	/* device descriptor strings: manufacturer, product */
	snprintf(manufacturer, sizeof manufacturer, "%s %s with %s",
	         init_utsname()->sysname, init_utsname()->release,
	         gadget->name);
	status = usb_string_id(cdev);
	if (status < 0)
		goto fail2;
	strings_dev[STRING_MANUFACTURER_IDX].id = status;
	device_desc.iManufacturer = status;

	status = usb_string_id(cdev);
	if (status < 0)
		goto fail2;
	strings_dev[STRING_PRODUCT_IDX].id = status;
	device_desc.iProduct = status;

#ifdef USB_ETH_RNDIS
	/* register our first configuration */
	status = usb_add_config(cdev, &rndis_config_driver);
	if (status < 0)
		goto fail2;
#endif

#ifdef CONFIG_USB_G_MULTI_CDC
	/* register our second configuration */
	status = usb_add_config(cdev, &cdc_config_driver);
	if (status < 0)
		goto fail2;
#endif

	dev_info(&gadget->dev, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
	fsg_common_put(fsg_common);
	return 0;

fail2:
	fsg_common_put(fsg_common);
fail1:
	gserial_cleanup();
fail0:
	gether_cleanup();
	return status;
}
Esempio n. 28
0
File: xml.c Progetto: steev/libiio
static struct iio_device * create_device(struct iio_context *ctx, xmlNode *n)
{
    xmlAttr *attr;
    struct iio_device *dev = calloc(1, sizeof(*dev));
    if (!dev)
        return NULL;

    dev->ctx = ctx;

    for (attr = n->properties; attr; attr = attr->next) {
        if (!strcmp((char *) attr->name, "name")) {
            dev->name = _strdup((char *) attr->children->content);
        } else if (!strcmp((char *) attr->name, "id")) {
            dev->id = _strdup((char *) attr->children->content);
        } else {
            WARNING("Unknown attribute \'%s\' in <device>\n",
                    attr->name);
        }
    }

    if (!dev->id) {
        ERROR("Unable to read device ID\n");
        goto err_free_device;
    }

    for (n = n->children; n; n = n->next) {
        if (!strcmp((char *) n->name, "channel")) {
            struct iio_channel **chns,
                   *chn = create_channel(dev, n);
            if (!chn) {
                ERROR("Unable to create channel\n");
                goto err_free_device;
            }

            chns = realloc(dev->channels, (1 + dev->nb_channels) *
                           sizeof(struct iio_channel *));
            if (!chns) {
                ERROR("Unable to allocate memory\n");
                free(chn);
                goto err_free_device;
            }

            chns[dev->nb_channels++] = chn;
            dev->channels = chns;
        } else if (!strcmp((char *) n->name, "attribute")) {
            if (add_attr_to_device(dev, n, false) < 0)
                goto err_free_device;
        } else if (!strcmp((char *) n->name, "debug-attribute")) {
            if (add_attr_to_device(dev, n, true) < 0)
                goto err_free_device;
        } else if (strcmp((char *) n->name, "text")) {
            WARNING("Unknown children \'%s\' in <device>\n",
                    n->name);
            continue;
        }
    }

    dev->words = (dev->nb_channels + 31) / 32;
    if (dev->words) {
        dev->mask = calloc(dev->words, sizeof(*dev->mask));
        if (!dev->mask) {
            errno = ENOMEM;
            goto err_free_device;
        }
    }

    return dev;

err_free_device:
    free_device(dev);
    return NULL;
}
Esempio n. 29
0
int main(int argc, char *argv[])
{
	const char *fs = NULL;

	setlocale(LC_CTYPE, "");
	setlocale(LC_NUMERIC, "C"); /* for parsing cmdline & prog */
	cmdname = argv[0];
	if (argc == 1) {
		fprintf(stderr, "Usage: %s [-f programfile | 'program'] [-Ffieldsep] [-v var=value] [files]\n", cmdname);
		exit(1);
	}
	signal(SIGFPE, fpecatch);
	yyin = NULL;
	symtab = makesymtab(NSYMTAB);
	while (argc > 1 && argv[1][0] == '-' && argv[1][1] != '\0') {
		if (strcmp(argv[1], "--") == 0) {	/* explicit end of args */
			argc--;
			argv++;
			break;
		}
		switch (argv[1][1]) {
		case 's':
			if (strcmp(argv[1], "-safe") == 0)
				safe = 1;
			break;
		case 'f':	/* next argument is program filename */
			argc--;
			argv++;
			if (argc <= 1)
				FATAL("no program filename");
			if (npfile >= MAX_PFILE - 1)
				FATAL("too many -f options"); 
			pfile[npfile++] = argv[1];
			break;
		case 'F':	/* set field separator */
			if (argv[1][2] != 0) {	/* arg is -Fsomething */
				if (argv[1][2] == 't' && argv[1][3] == 0)	/* wart: t=>\t */
					fs = "\t";
				else if (argv[1][2] != 0)
					fs = &argv[1][2];
			} else {		/* arg is -F something */
				argc--; argv++;
				if (argc > 1 && argv[1][0] == 't' && argv[1][1] == 0)	/* wart: t=>\t */
					fs = "\t";
				else if (argc > 1 && argv[1][0] != 0)
					fs = &argv[1][0];
			}
			if (fs == NULL || *fs == '\0')
				WARNING("field separator FS is empty");
			break;
		case 'v':	/* -v a=1 to be done NOW.  one -v for each */
			if (argv[1][2] == '\0' && --argc > 1 && isclvar((++argv)[1]))
				setclvar(argv[1]);
			break;
		case 'm':	/* more memory: -mr=record, -mf=fields */
				/* no longer supported */
			WARNING("obsolete option %s ignored", argv[1]);
			break;
		case 'd':
			dbg = atoi(&argv[1][2]);
			if (dbg == 0)
				dbg = 1;
			printf("awk %s\n", version);
			break;
		case 'V':	/* added for exptools "standard" */
			printf("awk %s\n", version);
			exit(0);
			break;
		default:
			WARNING("unknown option %s ignored", argv[1]);
			break;
		}
		argc--;
		argv++;
	}
	/* argv[1] is now the first argument */
	if (npfile == 0) {	/* no -f; first argument is program */
		if (argc <= 1) {
			if (dbg)
				exit(0);
			FATAL("no program given");
		}
		   dprintf( ("program = |%s|\n", argv[1]) );
		lexprog = argv[1];
		argc--;
		argv++;
	}
	recinit(recsize);
	syminit();
	compile_time = 1;
	argv[0] = cmdname;	/* put prog name at front of arglist */
	   dprintf( ("argc=%d, argv[0]=%s\n", argc, argv[0]) );
	arginit(argc, argv);
	if (!safe)
		envinit(environ);
	yyparse();
	setlocale(LC_NUMERIC, ""); /* back to whatever it is locally */
	if (fs)
		*FS = qstring(fs, '\0');
	   dprintf( ("errorflag=%d\n", errorflag) );
	if (errorflag == 0) {
		compile_time = 0;
		run(winner);
	} else
		bracecheck();
	return(errorflag);
}
/****** qmaster/sge_mod_configuration() ****************************************
*  NAME
*     sge_mod_configuration() -- modify cluster configuration
*
*  SYNOPSIS
*     int sge_mod_configuration(lListElem *aConf, lList **anAnswer, char *aUser,
*                               char *aHost)
*
*  FUNCTION
*     Modify cluster configuration. 'confp' is a pointer to a 'CONF_Type' list
*     element and does contain the modified configuration entry. Adding a new
*     configuration entry is also viewed as a modification.
*
*  INPUTS
*     lListElem *aConf  - CONF_Type element containing the modified conf
*     lList **anAnswer  - answer list
*     char *aUser       - target user
*     char *aHost       - target host
*
*  RESULT
*     int - 0 success
*          -1 error
*
*  NOTES
*     MT-NOTE: sge_mod_configuration() is MT safe 
*
*******************************************************************************/
int sge_mod_configuration(sge_gdi_ctx_class_t *ctx, lListElem *aConf, lList **anAnswer, char *aUser, char *aHost)
{
   lListElem *old_conf;
   const char *tmp_name = NULL;
   char unique_name[CL_MAXHOSTLEN];
   int ret = -1;
   const char *cell_root = ctx->get_cell_root(ctx);
   const char *qualified_hostname = ctx->get_qualified_hostname(ctx);
   u_long32 progid = ctx->get_who(ctx);

   DENTER(TOP_LAYER, "sge_mod_configuration");

   if (!aConf || !aUser || !aHost) {
      CRITICAL((SGE_EVENT, MSG_SGETEXT_NULLPTRPASSED_S, SGE_FUNC));
      answer_list_add(anAnswer, SGE_EVENT, STATUS_EUNKNOWN, ANSWER_QUALITY_ERROR);
      DRETURN(STATUS_EUNKNOWN);
   }

   if ((tmp_name = lGetHost(aConf, CONF_name)) == NULL) {
      CRITICAL((SGE_EVENT, MSG_SGETEXT_MISSINGCULLFIELD_SS, lNm2Str(CONF_name), SGE_FUNC));
      answer_list_add(anAnswer, SGE_EVENT, STATUS_EUNKNOWN, ANSWER_QUALITY_ERROR);
      DRETURN(STATUS_EUNKNOWN);
   }

   if ((ret = sge_resolve_hostname(tmp_name, unique_name, EH_name, sizeof(unique_name)))
       != CL_RETVAL_OK) {
      DPRINTF(("%s: error %s resolving host %s\n", SGE_FUNC, cl_get_error_text(ret), tmp_name));
      ERROR((SGE_EVENT, MSG_SGETEXT_CANTRESOLVEHOST_S, tmp_name));
      answer_list_add(anAnswer, SGE_EVENT, STATUS_EUNKNOWN, ANSWER_QUALITY_ERROR);
      DRETURN(STATUS_EUNKNOWN);
   }
   
   if ((ret = check_config(anAnswer, aConf))) {
      DRETURN(ret); 
   }

   if ((old_conf = sge_get_configuration_for_host(unique_name)) != NULL) {
      int ret = -1;
      
      ret = do_mod_config(ctx, unique_name, old_conf, aConf, anAnswer);
      
      lFreeElem(&old_conf);
      
      if (ret == 0) {    
         INFO((SGE_EVENT, MSG_SGETEXT_MODIFIEDINLIST_SSSS, aUser, aHost, unique_name, MSG_OBJ_CONF));
         answer_list_add(anAnswer, SGE_EVENT, STATUS_OK, ANSWER_QUALITY_INFO);
      } else {
         DRETURN(STATUS_EUNKNOWN);
      }
   } else {
      do_add_config(ctx, unique_name, aConf, anAnswer);
            
      INFO((SGE_EVENT, MSG_SGETEXT_ADDEDTOLIST_SSSS, aUser, aHost, unique_name, MSG_OBJ_CONF));            
      answer_list_add(anAnswer, SGE_EVENT, STATUS_OK, ANSWER_QUALITY_INFO);
   }
   
   if (strcmp(SGE_GLOBAL_NAME, unique_name) == 0) {
      sge_add_event(0, sgeE_GLOBAL_CONFIG, 0, 0, NULL, NULL, NULL, NULL);
   }

   /*
   ** is the configuration change relevant for the qmaster itsself?
   ** if so, initialise conf struct anew
   */
   if (strcmp(unique_name, SGE_GLOBAL_NAME) == 0 || sge_hostcmp(unique_name, qualified_hostname) == 0) {
      lListElem *local = NULL;
      lListElem *global = NULL;
      lList *answer_list = NULL;
      char* qmaster_params = NULL;
      int accounting_flush_time = mconf_get_accounting_flush_time();

      if ((local = sge_get_configuration_for_host(qualified_hostname)) == NULL) {
         WARNING((SGE_EVENT, MSG_CONF_NOLOCAL_S, qualified_hostname));
      }
      
      if ((global = sge_get_configuration_for_host(SGE_GLOBAL_NAME)) == NULL) {
         ERROR((SGE_EVENT, SFNMAX, MSG_CONF_NOGLOBAL));
      }
            
      if (merge_configuration(&answer_list, progid, cell_root, global, local, NULL) != 0) {
         ERROR((SGE_EVENT, MSG_CONF_CANTMERGECONFIGURATIONFORHOST_S, qualified_hostname));
      }
      answer_list_output(&answer_list);

      /* Restart the accounting flush event if needed. */
      if ((accounting_flush_time == 0) &&
          (mconf_get_accounting_flush_time() != 0)) {
         te_event_t ev = te_new_event(time(NULL), TYPE_ACCOUNTING_TRIGGER, ONE_TIME_EVENT, 1, 0, NULL);
         te_add_event(ev);
         te_free_event(&ev);
      }
      
      lFreeElem(&local);
      lFreeElem(&global);
      
      sge_show_conf();

      /* 'max_unheard' may have changed */
      cl_commlib_set_connection_param(cl_com_get_handle("qmaster", 1), HEARD_FROM_TIMEOUT, mconf_get_max_unheard());

      /* fetching qmaster_params and begin to parse */
      qmaster_params = mconf_get_qmaster_params();

      /* updating the commlib paramterlist and gdi_timeout with new or changed parameters */
      cl_com_update_parameter_list(qmaster_params);

      sge_free(&qmaster_params);
   }
    
   /* invalidate configuration cache */
   mconf_set_new_config(true);
   
   DRETURN(STATUS_OK);
}