/** * Initialises the sFlow filter device for receiving packet samples. */ void openFilter(HSP *sp) { sp->filter.dev = INVALID_HANDLE_VALUE; // Open the device sp->filter.dev = CreateFileW(SFLOW_FILTER_DEVICE, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if (sp->filter.dev == INVALID_HANDLE_VALUE) { DWORD error = GetLastError(); if (error == ERROR_FILE_NOT_FOUND) { myLog(LOG_ERR, "openFilter: sFlow Hyper-V switch extension not found (Windows Server 2012 Hyper-V not running or sFlow extension not installed). Monitoring host performance only"); } else { myLog(LOG_ERR, "openFilter: could not open device file %S: %ld. Monitoring host performance only.", SFLOW_FILTER_DEVICE, error); } } else { myLog(debug, "openFilter: attached to sFlow Hyper-V Switch extension"); //Create the ioctl overlaps for communication with the device sp->filter.ioctlOverlap.Internal = 0; sp->filter.ioctlOverlap.InternalHigh = 0; sp->filter.ioctlOverlap.Pointer = NULL; sp->filter.ioctlOverlap.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); createOverlaps(sp); if (queueReads(sp) != 0) { CloseHandle(sp->filter.dev); sp->filter.dev = INVALID_HANDLE_VALUE; myLog(LOG_ERR, "openFilter: could not queue initial read requests"); } else { setFilterSamplingParams(sp); } } }
void ServiceMain(int argc, char** argv) { ServiceStatus.dwServiceType = SERVICE_WIN32; ServiceStatus.dwCurrentState = SERVICE_START_PENDING; ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; ServiceStatus.dwWin32ExitCode = 0; ServiceStatus.dwServiceSpecificExitCode = 0; ServiceStatus.dwCheckPoint = 0; ServiceStatus.dwWaitHint = 0; if (isService) { hStatus = RegisterServiceCtrlHandler(HSP_SERVICE_NAME, (LPHANDLER_FUNCTION)ControlHandler); if (hStatus == 0) { return; } } // Test for only one instance is running HANDLE mutex = CreateMutex(NULL, TRUE, instanceMutexName); DWORD err = GetLastError(); if (mutex != NULL && err == ERROR_ALREADY_EXISTS || mutex == NULL && err == ERROR_ACCESS_DENIED) { // Mutex found, so another instance is running if (hStatus != 0) { ServiceStatus.dwCurrentState = SERVICE_STOPPED; ServiceStatus.dwWin32ExitCode = ERROR_SINGLE_INSTANCE_APP; SetServiceStatus(hStatus, &ServiceStatus); } else { myLog(LOG_ERR, "%s.ServiceMain: only one instance can run, existing instance found", HSP_SERVICE_NAME); } return; } else { ServiceStatus.dwCurrentState = SERVICE_RUNNING; if (hStatus != 0) { // We are the first instance, report the running status to SCM. SetServiceStatus (hStatus, &ServiceStatus); } } wchar_t programDataDir[MAX_PATH]; if (!initialiseProgramDataDir(programDataDir, MAX_PATH)) { *programDataDir = NULL; } char mbcLogFilename[MAX_PATH]; if (isService && *programDataDir != NULL) { //set the log file name to the default. size_t dirLen = 0; if (0 == wcstombs_s(&dirLen, mbcLogFilename, MAX_PATH, programDataDir, wcslen(programDataDir))) { PathAppend(mbcLogFilename, HSP_DEFAULT_LOGFILE); logFilename = mbcLogFilename; } else { logFilename = NULL; } } if (logFilename != NULL) { // Logging on errno_t error = fopen_s(&logFile, logFilename, "wt"); if (error != 0) { logFile = stderr; myLog(LOG_ERR, "%s.ServiceMain: could not open log file %s: error %d\n", HSP_SERVICE_NAME, logFilename, error); } logFilename = NULL; } myLog(debug, "-------------Starting %s %s--------------", HSP_SERVICE_NAME, HSP_VERSION); fflush(logFile); HRESULT initComHr = initCom(); if (FAILED(initComHr)) { myLog(LOG_ERR, "%s.ServiceMain: cannot initialize COM for WMI error=0x%x", HSP_SERVICE_NAME, initComHr); if (hStatus != 0) { ServiceStatus.dwCurrentState = SERVICE_STOPPED; ServiceStatus.dwWin32ExitCode = ERROR_APP_INIT_FAILURE; SetServiceStatus(hStatus, &ServiceStatus); } return; } HSP sp = { 0 }; sp.DNSSD_startDelay = HSP_DEFAULT_DNSSD_STARTDELAY; sp.DNSSD_retryDelay = HSP_DEFAULT_DNSSD_RETRYDELAY; // look up host-id fields at startup only (hostname // may change dynamically so will have to revisit this $$$) sp.host_hid.hostname.str = (char *)my_calloc(SFL_MAX_HOSTNAME_CHARS+1); sp.host_hid.os_release.str = (char *)my_calloc(SFL_MAX_OSRELEASE_CHARS+1); readHidCounters(&sp, &sp.host_hid); sp.nio_polling_secs = HSP_NIO_POLLING_SECS_32BIT; readInterfaces(&sp, TRUE); if (!readConfig(&sp)) { myLog(LOG_ERR, "%s.ServiceMain: invalid configuration", HSP_SERVICE_NAME); if (hStatus != 0) { ServiceStatus.dwCurrentState = SERVICE_STOPPED; ServiceStatus.dwWin32ExitCode = ERROR_INVALID_PARAMETER; SetServiceStatus(hStatus, &ServiceStatus); } return; } sp.hyperV = testForHyperv(); if (sp.hyperV) { myLog(debug, "%s.ServiceMain Hyper-V services are running", HSP_SERVICE_NAME); if (programDataDir == NULL || !initialiseProgramDataFiles(&sp, programDataDir)) { myLog(LOG_ERR, "%s.ServiceMain: cannot initialise switch port and VM state files", HSP_SERVICE_NAME); if (hStatus != 0) { ServiceStatus.dwCurrentState = SERVICE_STOPPED; ServiceStatus.dwWin32ExitCode = ERROR_FILE_NOT_FOUND; SetServiceStatus(hStatus, &ServiceStatus); } return; } readGuidStore(sp.f_vmStore, sp.vmStoreFile, &sp.vmStore, &sp.maxDsIndex); readGuidStore(sp.f_portStore, sp.portStoreFile, &sp.portStore, &sp.maxIfIndex); } if (sp.DNSSD) { //start the DNS thread and loop waiting until we have the config from DNSSD HANDLE dnsSDThread; unsigned threadID; dnsSDThread = (HANDLE)_beginthreadex(NULL, 0, &runDNSSD, &sp, 0, &threadID); BOOL gotConfig = FALSE; while (!gotConfig) { HSPSFlowSettings *settings = sp.sFlow->sFlowSettings; if (newerSettingsAvailable(settings)) { HSPSFlowSettings *newSettings = newSFlowSettings(); if (readSFlowSettings(newSettings)) { //we have the config now gotConfig = TRUE; if (settings != NULL) { freeSFlowSettings(settings); } sp.sFlow->sFlowSettings = newSettings; myLog(debug, "%s.ServiceMain: DNS-SD enabled. Initial sFlow settings from registry currentconfig", HSP_SERVICE_NAME); } else { freeSFlowSettings(newSettings); myLog(LOG_ERR, "%s.ServiceMain: invalid DNS-SD discovered sFlow settings", HSP_SERVICE_NAME); if (hStatus != 0) { ServiceStatus.dwCurrentState = SERVICE_STOPPED; ServiceStatus.dwWin32ExitCode = ERROR_INVALID_PARAMETER; SetServiceStatus(hStatus, &ServiceStatus); } return; } } else { Sleep(sp.DNSSD_startDelay*1000); } } } else { // read the manual config HSPSFlowSettings *newSettings = newSFlowSettings(); if (readSFlowSettings(newSettings)) { sp.sFlow->sFlowSettings = newSettings; } else { myLog(LOG_ERR, "%s.ServiceMain: invalid sFlow configuration in registry", HSP_SERVICE_NAME); if (hStatus != 0) { ServiceStatus.dwCurrentState = SERVICE_STOPPED; ServiceStatus.dwWin32ExitCode = ERROR_INVALID_PARAMETER; SetServiceStatus(hStatus, &ServiceStatus); } return; } } openFilter(&sp); //try to initialise the sFlow filter for sampling initAgent(&sp); logSFlowSettings(sp.sFlow); // initialize the clock so we can detect second boundaries sp.clk = time(NULL); // main loop BOOL dataAvailable = true; uint32_t currReadNum = 0; while (ServiceStatus.dwCurrentState == SERVICE_RUNNING && dataAvailable) { // check for second boundaries and generate ticks for the sFlow library time_t now = time(NULL); if ((now < sp.clk) || (now - sp.clk) > HSP_MAX_TICKS) { // avoid a busy-loop of ticks if time jumps myLog(LOG_INFO, "%s.ServiceMain: time jump detected", HSP_SERVICE_NAME); sp.clk = now - 1; } while (sp.clk < now) { //only happens on second boundary //start critical if (sp.sFlow->sFlowSettings) { if (sp.clk%5 == 0 && newerSettingsAvailable(sp.sFlow->sFlowSettings)) { //get the new config HSPSFlowSettings *newSettings = newSFlowSettings(); if (readSFlowSettings(newSettings)) { //we have the config now BOOL pollingChanged = sp.sFlow->sFlowSettings->pollingInterval != newSettings->pollingInterval; BOOL samplingChanged = sp.sFlow->sFlowSettings->samplingRate != newSettings->samplingRate; freeSFlowSettings(sp.sFlow->sFlowSettings); sp.sFlow->sFlowSettings = newSettings; myLog(debug, "%s.ServiceMain: updated configuration settings", HSP_SERVICE_NAME); logSFlowSettings(sp.sFlow); if (pollingChanged) { for (SFLPoller *poller = sp.sFlow->agent->pollers; poller; poller = poller->nxt) { sfl_poller_set_sFlowCpInterval(poller, sp.sFlow->sFlowSettings->pollingInterval); } } if (samplingChanged && HSP_FILTER_ACTIVE(sp.filter)) { setFilterSamplingParams(&sp); } } else { freeSFlowSettings(newSettings); } } tick(&sp); } //end critical sp.clk++; } DWORD result; //process a queued counter poller processQueuedPoller(&sp); //timeout is set so that we loop around checking for ticks and samples //several times/s. //calculate timeout 200 if the counter poller queue is empty, 0 otherwise DWORD timeout = sp.pollerQHead == NULL ? HSP_TIMEOUT : 0; if (HSP_FILTER_ACTIVE(sp.filter)) { result = WaitForSingleObject(sp.filter.overlaps[currReadNum].hEvent, timeout); if (result == WAIT_OBJECT_0) { dataAvailable = sp.filter.overlaps[currReadNum].Internal == ERROR_SUCCESS; if (dataAvailable && sp.filter.overlaps[currReadNum].InternalHigh > 0) { //process the sample info in sp.filter.buffers[currReadNum] readPackets(&sp, sp.filter.buffers[currReadNum]); } // Re-queue this read queueRead(sp.filter.dev, sp.filter.buffers[currReadNum], sizeof(sp.filter.buffers[currReadNum]), &sp.filter.overlaps[currReadNum]); //set the next buffer to read currReadNum = (currReadNum+1)%numConcurrentReads; } } else { Sleep(timeout); } } return; }