bool WuResubmit(const char *wuid)
{
    Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
    Owned<IWorkUnit> wu = factory->updateWorkUnit(wuid);
    if (!wu)
    {
        ERRLOG("WuResubmit(%s): could not find workunit",wuid);
        return false;
    }
    if (wu->getState()!=WUStateFailed)
    {
        ERRLOG("WuResubmit(%s): could not resubmit as workunit state is '%s'", wuid, wu->queryStateDesc());
        return false;
    }
    SCMStringBuffer token;
    wu->getSecurityToken(token);
    SCMStringBuffer user;
    SCMStringBuffer password;
    extractToken(token.str(), wuid, user, password);
    wu->resetWorkflow();
    wu->setState(WUStateSubmitted);
    wu->commit();
    wu.clear();
    submitWorkUnit(wuid,user.str(),password.str());

    PROGLOG("WuResubmit(%s): resubmitted",wuid);
    return true;
}
Пример #2
0
IOReturn
IOI2CDevice::unlockI2CBus(
	UInt32	clientKey)
{
	IOReturn	status;

	if (ml_at_interrupt_context())
	{
		ERRLOG("IOI2CDevice@%lx::unlockI2CBus from primary interrupt context not permitted\n", fI2CAddress);
		return kIOReturnNotPermitted;
	}

	if (isI2COffline())
	{
		ERRLOG("IOI2CDevice@%lx::unlockI2CBus device is offline\n", fI2CAddress);
		return kIOReturnOffline;
	}

	status = fProvider->callPlatformFunction(symUnlockI2CBus, false, (void *)0, (void *)clientKey, (void *)0, (void *)0);
	if (kIOReturnSuccess != status)
	{
		ERRLOG("IOI2CDevice@%lx::unlockI2CBus controller unlock failed key:%lx status:0x%x\n", fI2CAddress, clientKey, status);
		return status;
	}

//	DLOG("IOI2CDevice@%lx::unlockI2CBus - device UNLOCKED key:%lx\n", fI2CAddress, clientKey);

	I2CUNLOCK;

	return status;
}
//Called when Logging manager is created. Create logging agents based on settings
bool CLoggingManager::init(IPropertyTree* cfg, const char* service)
{
    if (!cfg)
    {
        ERRLOG(EspLoggingErrors::ConfigurationFileEntryError, "Logging Manager setting not found for %s", service);
        return false;
    }

    Owned<IPTreeIterator> loggingAgentSettings = cfg->getElements("LogAgent");
    ForEach(*loggingAgentSettings)
    {
        IPropertyTree& loggingAgentTree = loggingAgentSettings->query();
        const char* agentName = loggingAgentTree.queryProp("@name");
        const char* agentType = loggingAgentTree.queryProp("@type");
        const char* agentPlugin = loggingAgentTree.queryProp("@plugin");
        if (!agentName || !*agentName || !agentPlugin || !*agentPlugin)
            continue;

        IEspLogAgent* loggingAgent = loadLoggingAgent(agentName, agentPlugin, service, cfg);
        if (!loggingAgent)
        {
            ERRLOG(-1, "Failed to create logging agent for %s", agentName);
            continue;
        }
        loggingAgent->init(agentName, agentType, &loggingAgentTree, service);
        IUpdateLogThread* logThread = createUpdateLogThread(&loggingAgentTree, service, agentName, loggingAgent);
        if(!logThread)
            throw MakeStringException(-1, "Failed to create update log thread for %s", agentName);
        loggingAgentThreads.push_back(logThread);
    }

    initialized = true;
    return !loggingAgentThreads.empty();
}
Пример #4
0
int ptm_lib_complete_msg(ptm_lib_handle_t *hdl, void *ctxt, char *buf, int *len)
{
	ptm_lib_msg_ctxt_t *p_ctxt = ctxt;
	csv_t *csv;
	csv_record_t *rec;

	if (!p_ctxt) {
		ERRLOG("%s: no context \n", __FUNCTION__);
		return -1;
	}

	csv = p_ctxt->csv;
	rec = csv_record_iter(csv);

	_ptm_lib_encode_header(csv, rec, (csvlen(csv) - PTMLIB_MSG_HDR_LEN),
			       PTMLIB_MSG_VERSION, p_ctxt->type, p_ctxt->cmd_id,
			       hdl->client_name);

	/* parse csv contents into string */
	if (buf && len) {
		if (csv_serialize(csv, buf, *len)) {
			ERRLOG("%s: cannot serialize\n", __FUNCTION__);
			return -1;
		}
		*len = csvlen(csv);
	}

	csv_clean(csv);
	csv_free(csv);
	free(p_ctxt);

	return 0;
}
Пример #5
0
		int CMainLoop::Init(const char *szConfigFile,const char *szBinName)
		{
			if (NULL == szConfigFile || NULL == szBinName)
				return -1;

			int iRet;

			// prepare;
			if (NULL != m_buff)
				delete[]m_buff;
			m_buff = new char[COMMON_BUFF_SIZE];

			// read config;
			strncpy(m_stConfig.m_szBinName, szBinName, sizeof(m_stConfig.m_szBinName) - 1);
			strncpy(m_szConfigFile,szConfigFile, sizeof(m_szConfigFile) - 1);
			iRet = ReadConfig();
			if (iRet)
			{
				ERRLOG("ReadConfig fail!ret[%d]",iRet);
				return -1;
			}

			// init log;
			_releaseMem(m_pLog);
			m_pLog = new ns::common::CLog();

			char temp[256];

			snprintf(temp, sizeof(temp), "../log/%s", m_stConfig.m_szBinName);
			m_pLog->init(temp, 1000, 10, ns::common::CLog::LOG_MODE_ERROR);

			// init thread;
			iRet = CreateThread();
			if (iRet)
			{
				ERRLOG("CreateThread fail!ret[%d]",iRet);
				return -1;
			}

			// init listen socket;
			m_pSocket = new TSocket[m_stConfig.m_iTcpListenPortNum];

			// init epoll;
			iRet = m_epollMng.Init(100);
			if (iRet)
			{
				ERRLOG("m_epollMng init fail!ret[%d]", iRet);
				return -1;
			}

			// begin listen;
			iRet = InitListenPort();
			if (iRet)
			{
				ERRLOG("InitListenPort fail!ret[%d]",iRet);
				return -1;
			}

			return 0;
		}
Пример #6
0
bool CLoggingManager::saveToTankFile(IEspUpdateLogRequestWrap& logRequest, CLogRequestInFile* reqInFile)
{
    if (!logFailSafe.get())
    {
        ERRLOG("CLoggingManager::saveToTankFile: logFailSafe not configured.");
        return false;
    }

    unsigned startTime = (getEspLogLevel()>=LogNormal) ? msTick() : 0;

    StringBuffer GUID;
    logFailSafe->GenerateGUID(GUID, NULL);
    reqInFile->setGUID(GUID);
    reqInFile->setOption(logRequest.getOption());

    StringBuffer reqBuf;
    Owned<IEspUpdateLogRequestWrap> logRequestFiltered = logContentFilter.filterLogContent(&logRequest);
    if (!serializeLogRequestContent(logRequestFiltered, GUID, reqBuf))
    {
        ERRLOG("CLoggingManager::saveToTankFile: failed in serializeLogRequestContent().");
        return false;
    }

    logFailSafe->AddACK(GUID);//Ack this logging request since the task will be done as soon as the next line is called.
    logFailSafe->Add(GUID, reqBuf, reqInFile);

    ESPLOG(LogNormal, "LThread:saveToTankFile: %dms\n", msTick() - startTime);
    return true;
}
Пример #7
0
bool CLogThread::FetchTransactionSeed(StringBuffer& TransactionSeedID)
{
    try{
        Owned<IClientTransactionSeedRequest> pSeedReq = m_pLoggingService->createTransactionSeedRequest();
        Owned<IClientTransactionSeedResponse> pSeedResp = m_pLoggingService->TransactionSeed(pSeedReq.get());
        //if we get to here then we have made the request but no seeds are available
        bMadeSeedRequest = true;
        if(pSeedResp->getSeedAvailable()==true)
        {
            TransactionSeedID.appendf("%s",pSeedResp->getSeedId());
            return true;
        }
        else
            return false;
    }
    catch(IException* ex)
    {
        StringBuffer errorStr;
        ex->errorMessage(errorStr);
        ERRLOG("Exception caught generating transaction seed (%d) %s",ex->errorCode(),errorStr.str());
        ex->Release();
    }
    catch(...)
    {
        ERRLOG("Unknown exception caught generating transaction seed");
    }
    return false;
}
Пример #8
0
		int CMainLoop::CreateThread()
		{
			if (m_stConfig.m_iThreadNum < 0)
				return -1;
			int iRet;

			_releaseMem(m_pThreadArray);
			m_pThreadArray = new (std::nothrow)ThreadLoop[m_stConfig.m_iThreadNum];
			if (NULL == m_pThreadArray)
			{
				ERRLOG("New ThreadLoop fail!");
				return -1;
			}

			m_pAuxConsumeMessageCount = new (std::nothrow)uint64_t[m_stConfig.m_iThreadNum];
			if (NULL == m_pAuxConsumeMessageCount)
			{
				ERRLOG("new m_pAuxConsumeMessageCount fail\n");
				return -2;
			}

			for (int i = 0; i < m_stConfig.m_iThreadNum; i++)
			{
				iRet = m_pThreadArray[i].Init(i,this);
				if (iRet)
				{
					ERRLOG("Init Thread[%d] fail!ret[%d]",i,iRet);
					return -1;
				}

				m_pAuxConsumeMessageCount[i] = 0;
			}

			return 0;
		}
Пример #9
0
void Java_org_deadc0de_apple2ix_Apple2Preferences_nativeSetTouchJoystickButtonTypes(JNIEnv *env, jclass cls, jint touchDownButton, jint northButton, jint southButton) {
    LOG(": %d,%d,%d", touchDownButton, northButton, southButton);

    touchDownButton -= 1;
    northButton -= 1;
    southButton -= 1;
    if (touchDownButton < TOUCH_NONE || touchDownButton > TOUCH_BOTH) {
        ERRLOG("OOPS, invalid parameter!");
        return;
    }
    if (northButton < TOUCH_NONE || northButton > TOUCH_BOTH) {
        ERRLOG("OOPS, invalid parameter!");
        return;
    }
    if (southButton < TOUCH_NONE || southButton > TOUCH_BOTH) {
        ERRLOG("OOPS, invalid parameter!");
        return;
    }

    uint8_t rosetteChars[ROSETTE_COLS * ROSETTE_ROWS];
    int rosetteScancodes[ROSETTE_COLS * ROSETTE_ROWS];
    rosetteChars[ROSETTE_NORTHWEST] = ' ';                      rosetteScancodes[ROSETTE_NORTHWEST] = -1;
    rosetteChars[ROSETTE_NORTH]     = (uint8_t)MOUSETEXT_UP;    rosetteScancodes[ROSETTE_NORTH]     = -1;
    rosetteChars[ROSETTE_NORTHEAST] = ' ';                      rosetteScancodes[ROSETTE_NORTHEAST] = -1;
    rosetteChars[ROSETTE_WEST]      = (uint8_t)MOUSETEXT_LEFT;  rosetteScancodes[ROSETTE_WEST]      = -1;
    rosetteChars[ROSETTE_CENTER]    = '+';                      rosetteScancodes[ROSETTE_CENTER]    = -1;
    rosetteChars[ROSETTE_EAST]      = (uint8_t)MOUSETEXT_RIGHT; rosetteScancodes[ROSETTE_EAST]      = -1;
    rosetteChars[ROSETTE_SOUTHWEST] = ' ';                      rosetteScancodes[ROSETTE_SOUTHWEST] = -1;
    rosetteChars[ROSETTE_SOUTH]     = (uint8_t)MOUSETEXT_DOWN;  rosetteScancodes[ROSETTE_SOUTH]     = -1;
    rosetteChars[ROSETTE_SOUTHEAST] = ' ';                      rosetteScancodes[ROSETTE_SOUTHEAST] = -1;
    joydriver_setTouchAxisTypes(rosetteChars, rosetteScancodes);
    joydriver_setTouchButtonTypes((touchjoy_button_type_t)touchDownButton, -1, (touchjoy_button_type_t)northButton, -1, (touchjoy_button_type_t)southButton, -1);
}
Пример #10
0
void initTimeEvent(struct aeEventLoop* eventLoop) {
    struct time_ev_priv_data* background_time_ev_data = zmalloc(sizeof(struct time_ev_priv_data));
    if (NULL == background_time_ev_data)
    {
        ERRLOG("memory is not enough.");
        exit(1);
    }
    background_time_ev_data->id = 0;
    if (aeCreateTimeEvent(eventLoop, 1, tBackgroundTask, background_time_ev_data, tEventFinalizerProc) == AE_ERR) {
        ERRLOG("Can't create the tBackgroundTask time event.");
        exit(1);
    }

    struct time_ev_priv_data* echo_task_data = zmalloc(sizeof(struct time_ev_priv_data));
    if (NULL == echo_task_data)
    {
        ERRLOG("memory is not enough.");
        exit(1);
    }
    echo_task_data->id = 1;
    if (aeCreateTimeEvent(eventLoop, 1, tEchoTask, echo_task_data, tEventFinalizerProc) == AE_ERR) {
        ERRLOG("Can't create the tEchoTask time event.");
        exit(1);
    }
}
Пример #11
0
void tWriteProc(struct aeEventLoop* eventLoop, int fd, void* clientData, int mask) {
    char pageBuf[512] = {0};
    char contentBuf[256] = {0};
    client_data_t *c = (client_data_t *)clientData;

    snprintf(contentBuf,
        sizeof(contentBuf),
        "<html>Hello, <a href=\"https://github.com/pandyxu/enhanced-redis-event-lib\">enhanced-redis-event-lib</a> example.<br /><br />%s</html>",
        server.backgroundBuf);

    snprintf(pageBuf, sizeof(pageBuf),
        "HTTP/1.1 200 OK\r\nContent-Length: %ld\r\n\r\n%s",
        strlen(contentBuf), contentBuf);
    int data_size = strlen(pageBuf);

    size_t available = sizeof(c->writeBuf)-c->writeBufPos;
    if (data_size > available)
    {
        ERRLOG("writeBuf not enough.");
        aeDeleteFileEvent(eventLoop, fd, AE_WRITABLE);
        free_client(c);
        return;
    }

    memcpy(c->writeBuf+c->writeBufPos, pageBuf, data_size);
    c->writeBufPos += data_size;

    int nwritten = 0;
    while(c->writeBufPos > 0) {
        nwritten = write(fd, c->writeBuf + c->sentlen, c->writeBufPos - c->sentlen);
        if (nwritten <= 0)
        {
            break;
        }
        c->sentlen += nwritten;

        /* If the buffer was sent, set writeBufPos to zero to continue with
         * the remainder of the reply. */
        if (c->sentlen == c->writeBufPos) {
            c->writeBufPos = 0;
            c->sentlen = 0;
        }
    }

    if (nwritten == -1) {
        if (errno == EAGAIN) {
            nwritten = 0;
        } else {
            ERRLOG("Error writing to client: %s", strerror(errno));
            aeDeleteFileEvent(eventLoop, fd, AE_WRITABLE);
            free_client(c);
            return;
        }
    }

    aeDeleteFileEvent(eventLoop, fd, AE_WRITABLE);
    free_client(c);
}
Пример #12
0
void CEclAgentExecutionServer::start(StringBuffer & codeDir)
{
    if (started)
    {
        WARNLOG("START called when already started\n");
        assert(false);
    }

    codeDirectory = codeDir;
    StringBuffer propertyFile = codeDirectory;
    addPathSepChar(propertyFile);
    propertyFile.append("agentexec.xml");

    Owned<IPropertyTree> properties;
    try
    {
        DBGLOG("AgentExec: Loading properties file '%s'\n", propertyFile.str());
        properties.setown(createPTreeFromXMLFile(propertyFile.str()));
    }
    catch (IException *e) 
    {
        EXCLOG(e, "Error processing properties file\n");
        throwUnexpected();
    }

    {
        //Build logfile from component properties settings
        Owned<IComponentLogFileCreator> lf = createComponentLogFileCreator(properties, "eclagent");
        lf->setCreateAliasFile(false);
        lf->setMsgFields(MSGFIELD_timeDate | MSGFIELD_msgID | MSGFIELD_process | MSGFIELD_thread | MSGFIELD_code);
        lf->beginLogging();
        PROGLOG("Logging to %s",lf->queryLogFileSpec());
    }

    //get name of workunit job queue
    StringBuffer sb;
    properties->getProp("@name", sb.clear());
    agentName.set(sb);
    if (!agentName.length())
    {
        ERRLOG("'name' not specified in properties file\n");
        throwUnexpected();
    }

    //get dali server(s)
    properties->getProp("@daliServers", daliServers);
    if (!daliServers.length())
    {
        ERRLOG("'daliServers' not specified in properties file\n");
        throwUnexpected();
    }

    started = true;
    Thread::start();
    Thread::join();
}
Пример #13
0
int
create_proc_name(char **name, char *host, int port, char *trailer)
{
  uint64_t usec;
  pid_t pid;
  struct timeval tv;
  int s, len, trailer_len = 0;
  char *client_name;
  char buf[256];

  if (host == NULL) {
    if (0 != gethostname(buf, sizeof(buf))) {
      ERRLOG(errno, "gethostname");
      return -1;
    }
    host = buf;
  }
  if (0 != gettimeofday(&tv, NULL)) {
    ERRLOG(errno, "gettimeofday");
    return -1;
  }
  usec = (uint64_t)tv.tv_sec * 1000000 + (uint64_t)tv.tv_usec;
  pid = getpid();

  len = 512;
  if (trailer) {
    trailer_len = strlen(trailer);
    len += trailer_len;
  }
  client_name = malloc(len);
  if (client_name == NULL) {
    ERRLOG(errno, "malloc");
    return -1;
  }
  memset(client_name, 0, len);
  s = snprintf(client_name, len, "%s:%d-%d-%llx", host, port, pid,
    (long long unsigned)usec);
  if (s <= 0 || s >= len) {
    free(client_name);
    return -1;
  }  
  if (trailer) {
    len -= s;
    if (trailer_len+2 >= len) {
      free(client_name);
      return -1;
    }
    client_name[s++] = '-';
    memcpy(&client_name[s], trailer, trailer_len+1);
  }
  
  *name = client_name;
  return 0;
}
Пример #14
0
int ptm_lib_init_msg(ptm_lib_handle_t *hdl, int cmd_id, int type, void *in_ctxt,
		     void **out_ctxt)
{
	ptm_lib_msg_ctxt_t *p_ctxt;
	ptm_lib_msg_ctxt_t *p_in_ctxt = in_ctxt;
	csv_t *csv;
	csv_record_t *rec, *d_rec;

	/* Initialize csv for using discrete record buffers */
	csv = csv_init(NULL, NULL, PTMLIB_MSG_SZ);

	if (!csv) {
		ERRLOG("%s: Could not allocate csv \n", __FUNCTION__);
		return -1;
	}

	rec = _ptm_lib_encode_header(csv, NULL, 0, PTMLIB_MSG_VERSION, type,
				     cmd_id, hdl->client_name);

	if (!rec) {
		ERRLOG("%s: Could not allocate record \n", __FUNCTION__);
		csv_clean(csv);
		csv_free(csv);
		return -1;
	}

	p_ctxt = calloc(1, sizeof(*p_ctxt));
	if (!p_ctxt) {
		ERRLOG("%s: Could not allocate context \n", __FUNCTION__);
		csv_clean(csv);
		csv_free(csv);
		return -1;
	}

	p_ctxt->csv = csv;
	p_ctxt->cmd_id = cmd_id;
	p_ctxt->type = type;

	*(ptm_lib_msg_ctxt_t **)out_ctxt = p_ctxt;

	/* caller supplied a context to initialize with? */
	if (p_in_ctxt) {
		/* insert the hdr rec */
		rec = csv_record_iter(p_in_ctxt->csv);
		csv_clone_record(p_in_ctxt->csv, rec, &d_rec);
		csv_insert_record(csv, d_rec);
		/* insert the data rec */
		rec = csv_record_iter_next(rec);
		csv_clone_record(p_in_ctxt->csv, rec, &d_rec);
		csv_insert_record(csv, d_rec);
	}
	return 0;
}
Пример #15
0
PlayQueue_s *playq_createPlayQueue(const long *nodeIdPtr, unsigned long numBuffers) {
    PlayQueue_s *playq = NULL;

    assert(numBuffers <= MAX_PLAYQ_BUFFERS);

    do {
        playq = calloc(1, sizeof(PlayQueue_s));
        if (!playq) {
            ERRLOG("no memory");
            break;
        }

        PQList_s *list = calloc(1, sizeof(PQList_s));
        playq->_internal = list;
        if (!list) {
            ERRLOG("no memory");
            break;
        }

        bool allocSuccess = true;
        for (unsigned long i=0; i<numBuffers; i++) {
            PQListNode_s *listNode = calloc(1, sizeof(PQListNode_s));
            LOG("CREATING PlayNode_s node ID: %ld", nodeIdPtr[i]);
            listNode->node.nodeId = nodeIdPtr[i];
            if (!listNode) {
                ERRLOG("no memory");
                allocSuccess = false;
                break;
            }
            listNode->next = list->availNodes;
            list->availNodes = listNode;
        }
        if (!allocSuccess) {
            break;
        }

        playq->Enqueue = &playq_enqueue;
        playq->Dequeue = &playq_dequeue;
        playq->Remove  = &playq_remove;
        playq->Drain   = &playq_drain;
        playq->GetHead = &playq_getHead;
        playq->Get     = &playq_get;
        playq->CanEnqueue = &playq_canEnqueue;

        return playq;
    } while (0);

    if (playq) {
        playq_destroyPlayQueue(&playq);
    }

    return NULL;
}
Пример #16
0
		int CMainLoop::AcceptConnection()
		{
			int iConnectClientNum = 0;
			long long key;
			int iEpollEventFlag;
			while (0 == m_epollMng.GetReadyEvent(key, iEpollEventFlag) && iConnectClientNum <= 100)
			{
				// new socket connect;
				if (iEpollEventFlag & EPOLLIN)
				{
					// accept socket and send to aux process 
					if (key < 0 || key >= m_stConfig.m_iTcpListenPortNum)
					{
						ERRLOG("unknow epoll key [%lld]", key);
						continue;
					}

					TSocket & socket_node = m_pSocket[key];
					struct sockaddr_in  sock_addr;
					socklen_t isockaddr_len = sizeof(sockaddr_in);
					int client_sock_fd = accept(socket_node.socket_fd,
						(struct sockaddr *)&sock_addr,
						&isockaddr_len);

					if (client_sock_fd < 0)
					{
						ERRLOG("accept socket error errno[%d]", errno);
						continue;
					}

					TMessageQueueHeader *pHeader = (TMessageQueueHeader *)m_buff;
					pHeader->message_type = common_data;
					pHeader->us_client_ip_net_order = sock_addr.sin_addr.s_addr;
					pHeader->us_client_port = sock_addr.sin_port;
					pHeader->us_listen_port = m_stConfig.m_tcpListenPort[key].unPort;
					pHeader->data.new_sock_fd = client_sock_fd;

					m_pThreadArray[SelectAux()].Queue().push_back((char*)pHeader, sizeof(TMessageQueueHeader));
					iConnectClientNum++;
					DEBUGLOG("new client connect,fd[%d]", client_sock_fd);
				}

				// error;
				if ((iEpollEventFlag & EPOLLHUP) || (iEpollEventFlag &EPOLLERR))
				{
					ERRLOG("epoll wait error ,need reconncet listen port?");
				}
			}

			m_consumeMessage += iConnectClientNum;
			return 0;
		}
Пример #17
0
void CLogThread::checkRollOver()
{
    if(!m_LogFailSafe.get())
        return;

    try
    {
        time_t tNow;
        time(&tNow);
        struct tm ltNow;
        localtime_r(&tNow, &ltNow);
        if(ltNow.tm_year != m_startTime.tm_year || ltNow.tm_yday != m_startTime.tm_yday)
        {
            localtime_r(&tNow, &m_startTime);  // reset the start time for next rollover check
            int numNewArrivals = m_pServiceLog.ordinality();
            {
                MTimeSection mt(NULL, "Tank file rollover");
                m_LogFailSafe->SafeRollover();
            }
            if(numNewArrivals > 0)
            {
                DBGLOG("writing %d requests in the queue to the rolled over tank file.", numNewArrivals);
                for(int i = 0; i < numNewArrivals; i++)
                {
                    IClientLOGServiceUpdateRequest* pRequest = m_pServiceLog.item(i);
                    if (pRequest)
                    {
                        IEspLOGServiceUpdateRequest* pEspRequest = dynamic_cast<IEspLOGServiceUpdateRequest*>(pRequest);
                        if(pEspRequest)
                        {
                            const char* guid = pEspRequest->getGUID();
                            if(guid)
                                m_LogFailSafe->Add(guid,*pRequest);
                        }
                    }
                }
            }
        }
    }
    catch(IException* Ex)
    {
        StringBuffer str;
        Ex->errorMessage(str);
        ERRLOG("Exception thrown during tank file rollover: %s",str.str());
        Ex->Release();
    }
    catch(...)
    {
        ERRLOG("Unknown exception thrown during tank file rollover.");
    }
}
Пример #18
0
void CEclAgentExecutionServer::start()
{
    if (started)
    {
        WARNLOG("START called when already started\n");
        assert(false);
    }

    Owned<IPropertyTree> properties;
    try
    {
        DBGLOG("AgentExec: Loading properties file 'agentexec.xml'");
        properties.setown(createPTreeFromXMLFile("agentexec.xml"));
    }
    catch (IException *e) 
    {
        EXCLOG(e, "Error processing properties file\n");
        throwUnexpected();
    }

    {
        //Build logfile from component properties settings
        Owned<IComponentLogFileCreator> lf = createComponentLogFileCreator(properties, "eclagent");
        lf->setCreateAliasFile(false);
        lf->beginLogging();
        PROGLOG("Logging to %s",lf->queryLogFileSpec());
    }

    //get name of workunit job queue
    StringBuffer sb;
    properties->getProp("@name", sb.clear());
    agentName.set(sb);
    if (!agentName.length())
    {
        ERRLOG("'name' not specified in properties file\n");
        throwUnexpected();
    }
    setStatisticsComponentName(SCThthor, agentName, true);

    //get dali server(s)
    properties->getProp("@daliServers", daliServers);
    if (!daliServers.length())
    {
        ERRLOG("'daliServers' not specified in properties file\n");
        throwUnexpected();
    }

    started = true;
    Thread::start();
    Thread::join();
}
Пример #19
0
 bool doSwap(const char *oldip, const char *newip)
 {
     Owned<INode> newNode = createINode(newip);
     Owned<INode> oldNode = createINode(oldip);
     if (!group->isMember(oldNode)) {
         ERRLOG("Node %s is not part of group %s", oldip, groupName.get());
         return false;
     }
     if (group->isMember(newNode)) {
         ERRLOG("Node %s is already part of group %s", newip, groupName.get());
         return false;
     }
     queryNamedGroupStore().swapNode(oldNode->endpoint(),newNode->endpoint());
     return true;
 }
Пример #20
0
bool processArgvFilenamesFromFile(IFileArray & filenames, const char * filename)
{
    char buffer[255];
    FILE * in = fopen(filename, "r");
    if (!in)
    {
        ERRLOG("Error: File '%s' does not exist", filename);
        return false;
    }

    while (!feof(in))
    {
        if (fgets(buffer, sizeof(buffer), in))
        {
            unsigned len = strlen(buffer);
            while (len && !isprint(buffer[len-1]))
                len--;
            buffer[len] = 0;
            if (len)
                processArgvFilename(filenames, filename);           //Potential for infinite recursion if user is daft
        }
    }
    fclose(in);
    return true;
}
Пример #21
0
static int
_extract_event (void *arg, int len, ptm_event_t *ev)
{
    char abuf[INET6_ADDRSTRLEN + 1];
    struct ptm_quagga_msg *msg = (struct ptm_quagga_msg *)arg;

    ev->module = QUAGGA_MODULE;

    if (len < sizeof(struct sockaddr_in)) {
        return -1;
    }

    inet_ntop(msg->lin.sin_family, (const void *)&msg->lin.sin_addr,
              abuf, sizeof(abuf));

    switch(ntohs(msg->lin.sin_family)) {
    case AF_INET6:
        ev->rv6addr = strdup(abuf);
        break;
    case AF_INET:
        ev->rv4addr = strdup(abuf);
        break;
    default:
        ERRLOG("Quagga socket sent bad address family\n");
        break;
    }
    ev->liface = strdup(msg->lport);

    /* make event coherent for fields that are not indicated */
    ev->riface = NULL;
    ev->rmac = NULL; /* this needs to be pulled out */
    return (0);
}
Пример #22
0
bool CESPServerLoggingAgent::updateLog(IEspUpdateLogRequestWrap& req, IEspUpdateLogResponse& resp)
{
    try
    {
        StringBuffer soapreq(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\""
            " xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\">"
            " <soap:Body>"
            );
        soapreq.append(req.getUpdateLogRequest());
        soapreq.append("</soap:Body></soap:Envelope>");

        StringBuffer status, respStr;
        if (sendHTTPRequest(soapreq, respStr, status) && status.length() && strieq(status, "200 OK"))
            resp.setStatusCode(0);
        else if (status.length() && !strieq(status, "200 OK"))
            throw MakeStringException(EspLoggingErrors::UpdateLogFailed, "%s", status.str());
        else if (respStr.length())
            throw MakeStringException(EspLoggingErrors::UpdateLogFailed, "%s", respStr.str());
        else
            throw MakeStringException(EspLoggingErrors::UpdateLogFailed, "Failed to send update log request to %s", serverUrl.str());
    }
    catch (IException* e)
    {//retry will be in update log queue.
        StringBuffer errorStr, errorMessage;
        errorMessage.append("Failed to update log: error code ").append(e->errorCode()).append(", error message ").append(e->errorMessage(errorStr));
        ERRLOG("%s", errorMessage.str());
        resp.setStatusCode(-1);
        resp.setStatusMessage(errorMessage.str());
        e->Release();
    }
    return true;
}
Пример #23
0
static int _ptm_lib_read_ptm_socket(int fd, char *buf, int len)
{
	int retries = 0, rc;
	int bytes_read = 0;

	while (bytes_read != len) {
		rc = recv(fd, (void *)(buf + bytes_read), (len - bytes_read),
			  MSG_DONTWAIT);
		if (rc <= 0) {
			if (errno && (errno != EAGAIN)
			    && (errno != EWOULDBLOCK)) {
				ERRLOG("fatal recv error(%s), closing connection, rc %d\n",
				       strerror(errno), rc);
				return (rc);
			} else {
				if (retries++ < 2) {
					usleep(10000);
					continue;
				}
				DLOG("max retries - recv error(%d - %s) bytes read %d (%d)\n",
				     errno, strerror(errno), bytes_read, len);
				return (bytes_read);
			}
			break;
		} else {
			bytes_read += rc;
		}
	}

	return bytes_read;
}
Пример #24
0
    void logResult(const char* buffer, DeserializationResult result) const
    {
        bool success = false;
        if (Deserialization_SUCCESS == result)
#if !defined(_DEBUG)
            return;
#else
            success = true;
#endif

        const char* typeStr = typeid(TValue).name();
        const char* resultStr = NULL;

        switch (result)
        {
        case Deserialization_UNKNOWN:       resultStr = "unknown"; break;
        case Deserialization_SUCCESS:       resultStr = "success"; break;
        case Deserialization_BAD_TYPE:      resultStr = "bad type"; break;
        case Deserialization_UNSUPPORTED:   resultStr = "unsupported"; break;
        case Deserialization_INVALID_TOKEN: resultStr = "invalid token"; break;
        case Deserialization_NOT_A_NUMBER:  resultStr = "not a number"; break;
        case Deserialization_OVERFLOW:      resultStr = "overflow"; break;
        case Deserialization_UNDERFLOW:     resultStr = "underflow"; break;
        default:                            resultStr = "unexpected"; break;
        }

        if (success)
            DBGLOG("Result of deserializing '%s' to type '%s': %s", buffer, typeStr, resultStr);
        else
            ERRLOG("Result of deserializing '%s' to type '%s': %s", buffer, typeStr, resultStr);
    }
Пример #25
0
int main(int argc, char** argv) {
    signal(SIGABRT, &sighandler);
    signal(SIGTERM, &sighandler);
    signal(SIGINT, &sighandler);

    initServer();

    aeEventLoop* eventLoop = aeCreateEventLoop(server.max_process_client + SHTTPSVR_EVENTLOOP_FDSET_INCR);
    server.el = eventLoop;

    int listen_socket = anetTcpServer(NULL, 80, NULL, server.tcp_backlog);
    anetNonBlock(NULL, listen_socket);

    if (listen_socket > 0
        && AE_ERR == aeCreateFileEvent(eventLoop, listen_socket, AE_READABLE, tAcceptProc, NULL)) {
        ERRLOG("aeCreateFileEvent error!");
        exit(1);
    }

    aeSetBeforeSleepProc(eventLoop, tBeforeSleepProc);
    initTimeEvent(eventLoop);
    aeMain(eventLoop);
    aeDeleteEventLoop(eventLoop);
    return 0;
}
bool CLoggingManager::getTransactionSeed(IEspGetTransactionSeedRequest& req, IEspGetTransactionSeedResponse& resp)
{
    if (!initialized)
        throw MakeStringException(-1,"LoggingManager not initialized");

    bool bRet = false;
    try
    {
        for (unsigned int x = 0; x < loggingAgentThreads.size(); x++)
        {
            IUpdateLogThread* loggingThread = loggingAgentThreads[x];
            if (!loggingThread->hasService(LGSTGetTransactionSeed))
                continue;

            IEspLogAgent* loggingAgent = loggingThread->getLogAgent();
            bRet = loggingAgent->getTransactionSeed(req, resp);
            if (bRet)
                break;
        }
    }
    catch (IException* e)
    {
        StringBuffer errorStr;
        e->errorMessage(errorStr);
        ERRLOG("Failed to get Transaction Seed: %s",errorStr.str());
        resp.setStatusCode(-1);
        resp.setStatusMessage(errorStr.str());
        e->Release();
    }

    return bRet;
}
Пример #27
0
jlib_decl bool interrupt_program(HANDLE handle, bool stopChildren, int signum)
{
    if (signum==0)
        return TerminateProcess(handle,1)!=FALSE;
    ERRLOG("interrupt_program signal %d not supported in windows",signum);
    return false;
}
Пример #28
0
bool CWsLoggingServiceEx::onGetTransactionSeed(IEspContext& context, IEspGetTransactionSeedRequest& req, IEspGetTransactionSeedResponse& resp)
{
    bool bRet = false;
    try
    {
        if (!context.validateFeatureAccess(WSLOGGING_ACCESS, SecAccess_Write, false))
            throw MakeStringException(EspLoggingErrors::WSLoggingAccessDenied, "Failed to get transaction  seed. Permission denied.");

        LOGServiceType serviceType = LGSTGetTransactionSeed;
        for (unsigned int x = 0; x < loggingAgentThreads.size(); x++)
        {
            IUpdateLogThread* loggingThread = loggingAgentThreads[x];
            if (!loggingThread->hasService(serviceType))
                continue;

            IEspLogAgent* loggingAgent = loggingThread->getLogAgent();
            bRet = loggingAgent->getTransactionSeed(req, resp);
            break;
        }
    }
    catch (IException* e)
    {
        StringBuffer errorStr;
        e->errorMessage(errorStr);
        errorStr.insert(0, "Failed to get Transaction Seed: ");
        ERRLOG("%s", errorStr.str());
        resp.setStatusCode(-1);
        resp.setStatusMessage(errorStr.str());
        e->Release();
    }
    return bRet;
}
Пример #29
0
 int run()
 {
     while (getRandom()%711!=0) getRandom(); // look busy
     ERRLOG("Server fault %d",(int)err);
     while (getRandom()%7!=0) Sleep(1);
     exit(0);
 }
Пример #30
0
bool CWsLoggingServiceEx::onUpdateLog(IEspContext& context, IEspUpdateLogRequest& req, IEspUpdateLogResponse& resp)
{
    try
    {
        if (!context.validateFeatureAccess(WSLOGGING_ACCESS, SecAccess_Write, false))
            throw MakeStringException(EspLoggingErrors::WSLoggingAccessDenied, "Failed to update log. Permission denied.");

        for (unsigned int x = 0; x < loggingAgentThreads.size(); x++)
        {
            IUpdateLogThread* loggingThread = loggingAgentThreads[x];
            if (!loggingThread->hasService(LGSTUpdateLOG))
                continue;
            loggingThread->queueLog(&req);
        }
        resp.setStatusCode(0);
        resp.setStatusMessage("Log will be updated.");
    }
    catch (IException* e)
    {
        StringBuffer errorStr;
        e->errorMessage(errorStr);
        ERRLOG("Failed to update log: cannot add to log queue: %s",errorStr.str());
        resp.setStatusCode(-1);
        resp.setStatusMessage(errorStr.str());
        e->Release();
    }
    return true;
}