/*
         * This function simply restarts the service s.
         * @param s A Service_T object
         */

        private static void _doRestart(Service_T s)
        {
            if (s.restart != null)
            {
                Logger.Log.InfoFormat("'{0}' restart", s.name);
                Util.ResetInfo(s);
                if (s.type == MonitServiceType.Service_Process)
                {
                    try
                    {
                        s.restart();
                        Event.Post(s, MonitEventType.Event_Exec, MonitStateType.State_Succeeded, s.action_EXEC,
                                   "restarted");
                    }
                    catch (Exception e)
                    {
                        Event.Post(s, MonitEventType.Event_Exec, MonitStateType.State_Failed, s.action_EXEC,
                                   "failed to restart -- {0}", e.Message);
                    }
                }
            }
            else
            {
                Logger.Log.DebugFormat("'{0}' restart skipped -- method not defined", s.name);
            }
            Util.MonitorSet(s);
        }
        /*
         * This is an in-fix recursive function called before s is started to
         * stop every service that depends on s, in reverse order *or* after s
         * was started to start again every service that depends on s. The
         * action parametere controls if this function should start or stop
         * the procceses that depends on s.
         * @param s A Service_T object
         * @param action An action to do on the dependant services
         * @param flag A Custom flag
         */

        private static void _doDepend(Service_T s, MonitActionType action, bool flag)
        {
            foreach (var child in MonitWindowsAgent.servicelist)
            {
                if (child.dependantlist != null)
                {
                    foreach (var d in child.dependantlist)
                    {
                        if (d == s.name)
                        {
                            if (action == MonitActionType.Action_Start)
                            {
                                _doStart(child);
                            }
                            else if (action == MonitActionType.Action_Monitor)
                            {
                                _doMonitor(child, flag);
                            }
                            _doDepend(child, action, flag);
                            if (action == MonitActionType.Action_Stop)
                            {
                                _doStop(child, flag);
                            }
                            else if (action == MonitActionType.Action_Unmonitor)
                            {
                                _doUnmonitor(child, flag);
                            }
                            break;
                        }
                    }
                }
            }
        }
Example #3
0
        public static void AddFilesystem(Service_T service)
        {
            var drives = DriveInfo.GetDrives();

            if (service.type == MonitServiceType.Service_Filesystem)
            {
                var foundServices =
                    drives.Where(
                        sc =>
                        (sc.IsReady && sc.DriveType == DriveType.Fixed)
                                ? sc.VolumeLabel.ToLower() == service.name
                                : false).ToList();
                if (foundServices != null && foundServices.Count() > 0)
                {
                    foundServices.ForEach(sc =>
                    {
                        service.name = sc.VolumeLabel.ToLower() + " (" + sc.DriveFormat.ToUpper() + ")";
                        service.inf  = new FileSystemInfo_T
                        {
                            f_blocks          = sc.TotalSize,
                            f_blocksfreetotal = sc.TotalFreeSpace,
                            space_total       = sc.TotalSize,
                            space_percent     = ((sc.TotalSize == 0) ? 0 : (1 - (sc.TotalFreeSpace / (float)sc.TotalSize)) * 100)
                        };
                        AddService(service);
                    });
                }
            }
        }
        /*
         * Add a new filesystem to the current service's filesystem list
         */

        public static void AddFilesystem(Service_T s, Filesystem_T ds)
        {
            if (s.filesystemlist == null)
            {
                s.filesystemlist = new List <Filesystem_T>();
            }
            s.filesystemlist.Insert(0, ds);
        }
 public static void AddResource(Service_T s, Resource_T rr)
 {
     if (s.resourcelist == null)
     {
         s.resourcelist = new List <Resource_T>();
     }
     s.resourcelist.Insert(0, rr);
 }
 public static void MonitorSet(Service_T s)
 {
     if (s.monitor == MonitMonitorStateType.Monitor_Not)
     {
         s.monitor = MonitMonitorStateType.Monitor_Init;
         Logger.Log.DebugFormat("'{0}' monitoring enabled", s.name);
     }
 }
        /*
         * This is a function for disabling monitoring
         * @param s A Service_T object
         * @param flag A Custom flag
         */

        private static void _doUnmonitor(Service_T s, bool flag)
        {
            if (s.depend_visited)
            {
                return;
            }
            s.depend_visited = true;
            Util.MonitorUnset(s);
        }
Example #8
0
        public static Service_T GetSource(Event_T E)
        {
            Service_T S = null;

            if ((S = Util.GetService(E.source)) == null)
            {
                Logger.Log.Error(string.Format("Service {0} not found in monit configuration", E.source));
            }

            return(S);
        }
        public static Service_T GetService(string name)
        {
            Service_T S = null;

            MonitWindowsAgent.servicelist.ForEach(s =>
            {
                if (s.name == name)
                {
                    S = s;
                }
            });
            return(S);
        }
Example #10
0
        /*
         * This function simply stops the service p.
         * @param s A Service_T object
         * @param flag true if the monitoring should be disabled or false if monitoring should continue (when stop is part of restart)
         * @return true if the service was stopped otherwise false
         */

        private static bool _doStop(Service_T s, bool flag)
        {
            var rv = true;

            if (s.depend_visited)
            {
                return(rv);
            }
            s.depend_visited = true;
            if (s.stop != null)
            {
                if (s.type != MonitServiceType.Service_Process || Util.IsProcessRunning(s, false) != 0)
                {
                    Logger.Log.InfoFormat("'{0}' stop", s.name);
                    var pid = Util.IsProcessRunning(s, true);
                    if (s.type == MonitServiceType.Service_Process)
                    {
                        try
                        {
                            s.stop();
                            Event.Post(s, MonitEventType.Event_Exec, MonitStateType.State_Succeeded, s.action_EXEC,
                                       "stopped");
                        }
                        catch (Exception e)
                        {
                            rv = false;
                            Event.Post(s, MonitEventType.Event_Exec, MonitStateType.State_Failed, s.action_EXEC,
                                       "failed to stop -- {0}", e.Message);
                        }
                    }
                }
            }
            else
            {
                Logger.Log.DebugFormat("'{0}' stop skipped -- method not defined", s.name);
            }
            if (flag)
            {
                Util.MonitorUnset(s);
            }
            else
            {
                Util.ResetInfo(s);
            }

            return(rv);
        }
Example #11
0
        /*
         * This is a post- fix recursive function for enabling monitoring every service
         * that s depends on before monitor s.
         * @param s A Service_T object
         * @param flag A Custom flag
         */

        private static void _doMonitor(Service_T s, bool flag)
        {
            if (s.visited)
            {
                return;
            }
            s.visited = true;
            if (s.dependantlist != null)
            {
                foreach (var d in s.dependantlist)
                {
                    var parent = Util.GetService(d);
                    _doMonitor(parent, flag);
                }
            }
            Util.MonitorSet(s);
        }
        /*
         * Add a new object to the current service actionrate list
         */

        public static void AddActionRate(Service_T s, ActionRate_T ar)
        {
            if (ar.count > ar.cycle)
            {
                Logger.Log.Error("The number of restarts must be less than poll cycles");
            }
            if (ar.count <= 0 || ar.cycle <= 0)
            {
                Logger.Log.Error("Zero or negative values not allowed in a action rate statement");
            }

            if (s.actionratelist == null)
            {
                s.actionratelist = new List <ActionRate_T>();
            }
            s.actionratelist.Insert(0, ar);
        }
Example #13
0
        public static int IsProcessRunning(Service_T s, bool refresh)
        {
            //TODO
            return(ProcessHelper.GetController(s.name).Status == ServiceControllerStatus.Running ? 1 : 0);

            var pid = -1;

            //        if (s.matchlist) {
            //                if (refresh || ! ptree || ! ptreesize)
            //                        initprocesstree(&ptree, &ptreesize, &oldptree, &oldptreesize);
            //                /* The process table read may sporadically fail during read, because we're using glob on some platforms which may fail if the proc filesystem
            //                 * which it traverses is changed during glob (process stopped). Note that the glob failure is rare and temporary - it will be OK on next cycle.
            //                 * We skip the process matching that cycle however because we don't have process informations - will retry next cycle */
            //                if (Run.doprocess) {
            //                        for (int i = 0; i < ptreesize; i++) {
            //                                boolean_t found = false;
            //                                if (ptree[i].cmdline) {
            //#ifdef HAVE_REGEX_H
            //                                        found = regexec(s.matchlist.regex_comp, ptree[i].cmdline, 0, NULL, 0) ? false : true;
            //#else
            //                                        found = strstr(ptree[i].cmdline, s.matchlist.match_string) ? true : false;
            //#endif
            //                                }
            //                                if (found) {
            //                                        pid = ptree[i].pid;
            //                                        break;
            //                                }
            //                        }
            //                } else {
            //                        DEBUG("Process information not available -- skipping service %s process existence check for this cycle\n", s.name);
            //                        /* Return value is NOOP - it is based on existing errors bitmap so we don't generate false recovery/failures */
            //                        return ! (s.error & Event_Nonexist);
            //                }
            //        } else {
            pid = GetPid(s.path);
            //}
            if (pid > 0)
            {
                //if (getpgid(pid) > -1)
                return(pid);
                //ChMonitoring.Helpers.Logger.Log.DebugFormat("'{0}' process test failed [pid={1}]", s.name, pid);
            }
            ResetInfo(s);
            return(0);
        }
Example #14
0
        public static void AddProcess(Service_T service)
        {
            var services = ServiceController.GetServices();

            if (service.type == MonitServiceType.Service_Process)
            {
                var foundServices = services.Where(sc => sc.ServiceName.ToLower() == service.name).ToList();
                if (foundServices != null && foundServices.Count() > 0)
                {
                    foundServices.ForEach(sc =>
                    {
                        service.start = sc.Start;
                        service.stop  = sc.Stop;
                        AddService(service);
                    });
                }
            }
        }
Example #15
0
 public static void MonitorUnset(Service_T s)
 {
     if (s.monitor != MonitMonitorStateType.Monitor_Not)
     {
         s.monitor = MonitMonitorStateType.Monitor_Not;
         Logger.Log.DebugFormat("'{0}' monitoring disabled", s.name);
     }
     s.nstart = 0;
     s.ncycle = 0;
     if (s.every.type == MonitEveryType.Every_SkipCycles)
     {
         var cycle = s.every as CycleEvery_T;
         cycle.counter = 0;
     }
     s.error = (int)MonitEventType.Event_Null;
     //if (s.eventlist)
     //    s.eventlist = null;
     ResetInfo(s);
 }
        public static void AddProcess(Service_T service)
        {
            var services = ServiceController.GetServices();

            if (service.type == MonitServiceType.Service_Process)
            {
                var foundServices = services.Where(sc => sc.ServiceName.ToLower() == service.name).ToList();
                if (foundServices != null && foundServices.Count() > 0)
                {
                    foundServices.ForEach(sc =>
                    {
                        service.start = () =>
                        {
                            try
                            {
                                sc.Start();
                                sc.WaitForStatus(ServiceControllerStatus.Running, new System.TimeSpan(0, 0, 10));
                                return(true);
                            }
                            catch (System.Exception e)
                            {
                                return(false);
                            }
                        };
                        service.stop = () =>
                        {
                            try
                            {
                                sc.Stop();
                                sc.WaitForStatus(ServiceControllerStatus.Stopped, new System.TimeSpan(0, 0, 10));
                                return(true);
                            }
                            catch (System.Exception e)
                            {
                                return(false);
                            }
                        };
                        AddService(service);
                    });
                }
            }
        }
Example #17
0
        /*
         * This is a post- fix recursive function for starting every service
         * that s depends on before starting s.
         * @param s A Service_T object
         */

        private static void _doStart(Service_T s)
        {
            if (s.visited)
            {
                return;
            }
            s.visited = true;
            if (s.dependantlist != null)
            {
                foreach (var d in s.dependantlist)
                {
                    var parent = Util.GetService(d);
                    _doStart(parent);
                }
            }
            if (s.start != null)
            {
                if (s.type != MonitServiceType.Service_Process || Util.IsProcessRunning(s, false) == 0)
                {
                    Logger.Log.InfoFormat("'{0}' start", s.name);
                    if (s.type == MonitServiceType.Service_Process)
                    {
                        try
                        {
                            s.start();
                            Event.Post(s, MonitEventType.Event_Exec, MonitStateType.State_Succeeded, s.action_EXEC,
                                       "started");
                        }
                        catch (Exception e)
                        {
                            Event.Post(s, MonitEventType.Event_Exec, MonitStateType.State_Failed, s.action_EXEC,
                                       "failed to start -- {0}", e.Message);
                        }
                    }
                }
            }
            else
            {
                Logger.Log.DebugFormat("'{0}' start skipped -- method not defined", s.name);
            }
            Util.MonitorSet(s);
        }
Example #18
0
        public static void ResetInfo(Service_T s)
        {
            switch (s.type)
            {
            case MonitServiceType.Service_Filesystem:
                var filesystem = s.inf as FileSystemInfo_T;
                filesystem.f_bsize           = 0;
                filesystem.f_blocks          = 0;
                filesystem.f_blocksfree      = 0;
                filesystem.f_blocksfreetotal = 0;
                filesystem.f_files           = 0;
                filesystem.f_filesfree       = 0;
                filesystem.inode_percent     = 0;
                filesystem.inode_total       = 0;
                filesystem.space_percent     = 0;
                filesystem.space_total       = 0;
                filesystem._flags            = -1;
                filesystem.flags             = -1;
                filesystem.mode = 0;
                filesystem.uid  = 0;
                filesystem.gid  = 0;
                break;

            case MonitServiceType.Service_File:
                var file = s.inf as FileInfo_T;
                // persistent: st_inode, readpos
                file.size       = 0;
                file.inode_prev = 0;
                file.mode       = 0;
                file.uid        = 0;
                file.gid        = 0;
                file.timestamp  = DateTime.MinValue;
                file.cs_sum     = "";
                break;

            case MonitServiceType.Service_Directory:
                var directory = s.inf as DirectoryInfo_T;
                directory.mode      = 0;
                directory.uid       = 0;
                directory.gid       = 0;
                directory.timestamp = DateTime.MinValue;
                break;

            case MonitServiceType.Service_Fifo:
                var fifo = s.inf as FiFoInfo_T;
                fifo.mode      = 0;
                fifo.uid       = 0;
                fifo.gid       = 0;
                fifo.timestamp = DateTime.MinValue;
                break;

            case MonitServiceType.Service_Process:
                var process = s.inf as ProcessInfo_T;
                process._pid              = -1;
                process._ppid             = -1;
                process.pid               = -1;
                process.ppid              = -1;
                process.uid               = -1;
                process.euid              = -1;
                process.gid               = -1;
                process.zombie            = false;
                process.children          = 0;
                process.mem_kbyte         = 0L;
                process.total_mem_kbyte   = 0L;
                process.mem_percent       = 0;
                process.total_mem_percent = 0;
                process.cpu_percent       = 0;
                process.total_cpu_percent = 0;
                process.uptime            = TimeSpan.MinValue;
                break;

            case MonitServiceType.Service_Net:
                var net = s.inf as NetInfo_T;
                //if (net.stats)
                //        Link_reset(net.stats);
                break;

            default:
                break;
            }
        }
Example #19
0
        private static void statusService(Service_T S, StringBuilder B, MonitLevelType L, int V)
        {
            var serviceXmlBuilder = new OutputBuilder(Resources.ServiceXml);

            var timeval    = S.collected;
            var headString = new StringBuilder();

            if (V == 2)
            {
                headString.AppendFormat("<service name=\"{0}\"><type>{1}</type>", S.name, (int)S.type);
            }
            else
            {
                headString.AppendFormat("<service type=\"{0}\"><name>{1}</name>", (int)S.type, S.name);
            }

            var everyString = new StringBuilder();

            if (S.every.type != MonitEveryType.Every_Cycle)
            {
                everyString.AppendFormat("<every><type>{0}</type>", (int)S.every.type);
                if (S.every.type == MonitEveryType.Every_SkipCycles)
                {
                    var cycle = S.every as CycleEvery_T;
                    everyString.AppendFormat("<counter>{0}</counter><number>{1}</number>", cycle.counter, cycle.number);
                }
                else
                {
                    var cron = S.every as CronEvery_T;
                    everyString.AppendFormat("<cron>{0}</cron>", cron.cron);
                }
                everyString.Append("</every>");
            }

            var centerString = new StringBuilder();

            if (L == MonitLevelType.Level_Full)
            {
                if (Util.HasServiceStatus(S))
                {
                    switch (S.type)
                    {
                    case MonitServiceType.Service_File:
                        var file = S.inf as FileInfo_T;
                        //centerString.AppendFormat(@"<mode>%o</mode>"
                        //        "<uid>%d</uid>"
                        //        "<gid>%d</gid>"
                        //        "<timestamp>%lld</timestamp>"
                        //        "<size>%llu</size>",
                        //        file.mode & 07777,
                        //        (int)file.uid,
                        //        (int)file.gid,
                        //        (long long)file.timestamp,
                        //        (unsigned long long)file.size);
                        //if (S.checksum)
                        //        centerString.AppendFormat(B, "<checksum type=\"%s\">%s</checksum>", checksumnames[S.checksum.type], file.cs_sum);
                        break;

                    case MonitServiceType.Service_Directory:
                        var directory = S.inf as DirectoryInfo_T;
                        //centerString.AppendFormat(@"<mode>%o</mode>"
                        //        "<uid>%d</uid>"
                        //        "<gid>%d</gid>"
                        //        "<timestamp>%lld</timestamp>",
                        //        directory.mode & 07777,
                        //        (int)directory.uid,
                        //        (int)directory.gid,
                        //        (long long)directory.timestamp);
                        break;

                    case MonitServiceType.Service_Fifo:
                        var fifo = S.inf as FiFoInfo_T;
                        //centerString.AppendFormat(@"<mode>%o</mode>"
                        //        "<uid>%d</uid>"
                        //        "<gid>%d</gid>"
                        //        "<timestamp>%lld</timestamp>",
                        //        fifo.mode & 07777,
                        //        (int)fifo.uid,
                        //        (int)fifo.gid,
                        //        (long long)fifo.timestamp);
                        break;

                    case MonitServiceType.Service_Filesystem:
                        var filesystem = S.inf as FileSystemInfo_T;
                        centerString.AppendFormat(
                            "<mode>{0}</mode><uid>{1}</uid><gid>{2}</gid><flags>{3}</flags><block><percent>{4}</percent><usage>{5}</usage><total>{6}</total></block>",
                            filesystem.mode,
                            filesystem.uid,
                            filesystem.gid,
                            filesystem.flags,
                            filesystem.space_percent,
                            filesystem.f_bsize > 0 ? filesystem.space_total / 1048576.0 * filesystem.f_bsize : 0,
                            filesystem.f_bsize > 0 ? filesystem.f_blocks / 1048576.0 * filesystem.f_bsize : 0);
                        if (filesystem.f_files > 0)
                        {
                            centerString.AppendFormat(
                                "<inode><percent>{0}</percent><usage>{1}</usage><total>{2}</total></inode>",
                                filesystem.inode_percent,
                                filesystem.inode_total,
                                filesystem.f_files);
                        }
                        break;

                    case MonitServiceType.Service_Net:
                        var net = S.inf as NetInfo_T;
                        //centerString.AppendFormat(@"<link>"
                        //        "<state>%d</state>"
                        //        "<speed>%lld</speed>"
                        //        "<duplex>%d</duplex>"
                        //        "<download>"
                        //        "<packets>"
                        //        "<now>%lld</now>"
                        //        "<total>%lld</total>"
                        //        "</packets>"
                        //        "<bytes>"
                        //        "<now>%lld</now>"
                        //        "<total>%lld</total>"
                        //        "</bytes>"
                        //        "<errors>"
                        //        "<now>%lld</now>"
                        //        "<total>%lld</total>"
                        //        "</errors>"
                        //        "</download>"
                        //        "<upload>"
                        //        "<packets>"
                        //        "<now>%lld</now>"
                        //        "<total>%lld</total>"
                        //        "</packets>"
                        //        "<bytes>"
                        //        "<now>%lld</now>"
                        //        "<total>%lld</total>"
                        //        "</bytes>"
                        //        "<errors>"
                        //        "<now>%lld</now>"
                        //        "<total>%lld</total>"
                        //        "</errors>"
                        //        "</upload>"
                        //        "</link>",
                        //        Link_getState(net.stats),
                        //        Link_getSpeed(net.stats),
                        //        Link_getDuplex(net.stats),
                        //        Link_getPacketsInPerSecond(net.stats),
                        //        Link_getPacketsInTotal(net.stats),
                        //        Link_getBytesInPerSecond(net.stats),
                        //        Link_getBytesInTotal(net.stats),
                        //        Link_getErrorsInPerSecond(net.stats),
                        //        Link_getErrorsInTotal(net.stats),
                        //        Link_getPacketsOutPerSecond(net.stats),
                        //        Link_getPacketsOutTotal(net.stats),
                        //        Link_getBytesOutPerSecond(net.stats),
                        //        Link_getBytesOutTotal(net.stats),
                        //        Link_getErrorsOutPerSecond(net.stats),
                        //        Link_getErrorsOutTotal(net.stats));
                        break;

                    case MonitServiceType.Service_Process:
                        var process = S.inf as ProcessInfo_T;
                        centerString.AppendFormat(
                            "<pid>{0}</pid><ppid>{1}</ppid><uid>{2}</uid><euid>{3}</euid><gid>{4}</gid><uptime>{5}</uptime>",
                            process.pid,
                            process.ppid,
                            process.uid,
                            process.euid,
                            process.gid,
                            process.uptime);
                        if (MonitWindowsAgent.Run.doprocess)
                        {
                            centerString.AppendFormat(
                                "<children>{0}</children><memory><percent>{1}</percent><percenttotal>{2}</percenttotal><kilobyte>{3}</kilobyte><kilobytetotal>{4}</kilobytetotal></memory><cpu><percent>{5}</percent><percenttotal>{6}</percenttotal></cpu>",
                                process.children,
                                process.mem_percent,
                                process.total_mem_percent,
                                process.mem_kbyte,
                                process.total_mem_kbyte,
                                process.cpu_percent,
                                process.total_cpu_percent);
                        }
                        break;

                    default:
                        break;
                    }
                    //for (Icmp_T i = S.icmplist; i; i = i.next) {
                    //        centerString.AppendFormat(@"<icmp>"
                    //                            "<type>%s</type>"
                    //                            "<responsetime>%.3f</responsetime>"
                    //                            "</icmp>",
                    //                            icmpnames[i.type],
                    //                            i.is_available ? i.response : -1.);
                    //}
                    //for (Port_T p = S.portlist; p; p = p.next) {
                    //        centerString.AppendFormat(@"<port>"
                    //                            "<hostname>%s</hostname>"
                    //                            "<portnumber>%d</portnumber>"
                    //                            "<request><![CDATA[%s]]></request>"
                    //                            "<protocol>%s</protocol>"
                    //                            "<type>%s</type>"
                    //                            "<responsetime>%.3f</responsetime>"
                    //                            "</port>",
                    //                            p.hostname ? p.hostname : "",
                    //                            p.port,
                    //                            p.request ? p.request : "",
                    //                            p.protocol.name ? p.protocol.name : "",
                    //                            Util_portTypeDescription(p),
                    //                            p.is_available ? p.response : -1.);
                    //}
                    //for (Port_T p = S.socketlist; p; p = p.next) {
                    //        centerString.AppendFormat(@"<unix>"
                    //                            "<path>%s</path>"
                    //                            "<protocol>%s</protocol>"
                    //                            "<responsetime>%.3f</responsetime>"
                    //                            "</unix>",
                    //                            p.pathname ? p.pathname : "",
                    //                            p.protocol.name ? p.protocol.name : "",
                    //                            p.is_available ? p.response : -1.);
                    //}
                    if (S.type == MonitServiceType.Service_System && MonitWindowsAgent.Run.doprocess)
                    {
                        centerString.AppendFormat(
                            "<system><load><avg01>{0}</avg01><avg05>{1}</avg05><avg15>{2}</avg15></load><cpu><user>{3}</user><system>{4}</system></cpu><memory><percent>{5}</percent><kilobyte>{6}</kilobyte></memory><swap><percent>{7}</percent><kilobyte>{8}</kilobyte></swap></system>",
                            MonitWindowsAgent.systeminfo.loadavg[0],
                            MonitWindowsAgent.systeminfo.loadavg[1],
                            MonitWindowsAgent.systeminfo.loadavg[2],
                            MonitWindowsAgent.systeminfo.total_cpu_user_percent > 0
                                ? MonitWindowsAgent.systeminfo.total_cpu_user_percent
                                : 0,
                            MonitWindowsAgent.systeminfo.total_cpu_syst_percent > 0
                                ? MonitWindowsAgent.systeminfo.total_cpu_syst_percent
                                : 0,
                            MonitWindowsAgent.systeminfo.total_mem_percent,
                            MonitWindowsAgent.systeminfo.total_mem_kbyte,
                            MonitWindowsAgent.systeminfo.total_swap_percent,
                            MonitWindowsAgent.systeminfo.total_swap_kbyte);
                    }
                    if (S.type == MonitServiceType.Service_Program && S.program.started != null)
                    {
                        centerString.AppendFormat(
                            "<program><started>{0}</started><status>{1}</status><output><![CDATA[",
                            Timing.GetTimestamp(S.program.started),
                            S.program.exitStatus);
                        centerString.Append(_escapeCDATA(S.program.output.ToString()));
                        centerString.Append("]]></output></program>");
                    }
                }
            }

            serviceXmlBuilder.ReplaceAllTags(headString.ToString(), Timing.GetTimestamp(timeval),
                                             Timing.GetUsec(timeval), S.error, S.error_hint, (int)S.monitor, (int)S.mode, (int)S.doaction,
                                             everyString.ToString(), centerString.ToString());
            B.Append(serviceXmlBuilder.GetResult());
        }
Example #20
0
 public static bool HasServiceStatus(Service_T S)
 {
     return(S.monitor == MonitMonitorStateType.Monitor_Yes &&
            !Event.IsEventSet(S.error, MonitEventType.Event_Nonexist) &&
            !Event.IsEventSet(S.error, MonitEventType.Event_Data));
 }
        /*
         * Add a service object to the servicelist
         */

        public static void AddService(Service_T s)
        {
            // Test sanity check
            switch (s.type)
            {
            case MonitServiceType.Service_Host:
                //// Verify that a remote service has a port or an icmp list
                //if (!s.portlist && !s.icmplist)
                //{
                //    Logger.Log.ErrorFormat("'check host' statement is incomplete: Please specify a port number to test\n or an icmp test at the remote host: '{0}'", s.name);
                //    cfg_errflag++;
                //}
                break;

            case MonitServiceType.Service_Program:
                //// Verify that a program test has a status test
                //if (!s.statuslist)
                //{
                //    Logger.Log.ErrorFormat("'check program {0}' is incomplete: Please add an 'if status != n' test", s.name);
                //    cfg_errflag++;
                //}
                //// Create the Command object
                //s.program.C = Command_new(s.path, NULL);
                //// Append any arguments
                //for (int i = 1; i < s.program.args.length; i++)
                //    Command_appendArgument(s.program.C, s.program.args.arg[i]);
                //if (s.program.args.has_uid)
                //    Command_setUid(s.program.C, s.program.args.uid);
                //if (s.program.args.has_gid)
                //    Command_setGid(s.program.C, s.program.args.gid);
                break;

            case MonitServiceType.Service_Net:
                //if (!s.linkstatuslist)
                //{
                //    // Add link status test if not defined
                //    addeventaction(&(linkstatusset).action, Action_Alert, Action_Alert);
                //    addlinkstatus(s, &linkstatusset);
                //}
                break;

            case MonitServiceType.Service_Filesystem:
                if (s.fsflaglist == null)
                {
                    // Add filesystem flags change test if not defined
                    s.fsflaglist = new List <EventAction_T>();
                    s.fsflaglist.Add(GetEventAction(MonitActionType.Action_Alert, MonitActionType.Action_Ignored));
                }
                break;

            case MonitServiceType.Service_Directory:
            case MonitServiceType.Service_Fifo:
            case MonitServiceType.Service_File:
            case MonitServiceType.Service_Process:
                if (s.nonexistlist == null)
                {
                    // Add existence test if not defined
                    s.nonexistlist = new List <EventAction_T>();
                    s.nonexistlist.Insert(0,
                                          GetEventAction(MonitActionType.Action_Restart, MonitActionType.Action_Alert));
                }
                break;

            default:
                break;
            }

            MonitWindowsAgent.servicelist.Add(s);
            MonitWindowsAgent.servicelist_conf.Add(s);
        }
        //public void CheckServicesRunning() {
        //    var serviceList = InitServiceList();
        //    var dependingServices = new List<string>();

        //    // check each service its running
        //    foreach(var s in serviceList) {
        //        switch(s.Status) {
        //            case ServiceControllerStatus.Running:
        //                if(MonitoredServices[s.ServiceName] <= 0) {
        //                    //when service has stopped and is running now, send mail
        //                    Logger.Log.Info("Service running again: " + "[" + s.ServiceName + "]");
        //                    MonitoredServices[s.ServiceName] = 1;
        //                    // SendEMail(s.Key.ServiceName, false, false);
        //                }
        //                break;
        //            case ServiceControllerStatus.Stopped:
        //                if(MonitoredServices[s.ServiceName] >= 0) {
        //                    Logger.Log.Warn("Service stopped running: " + "[" + s.ServiceName + "]");
        //                    MonitoredServices[s.ServiceName] = 0;
        //                } else if(MonitoredServices[s.ServiceName] <= -ConfigMgr.Config.FailedStarts) {
        //                    if(MonitoredServices[s.ServiceName] == -ConfigMgr.Config.FailedStarts) {
        //                        Logger.Log.Error("Service is stuck in Status Stopped: " + "[" + s.ServiceName + "]");
        //                        MonitoredServices[s.ServiceName]--;
        //                        // SendEMail(s.Key.ServiceName, true, true);
        //                    }
        //                    continue;
        //                }

        //                //get depending services to stop them later
        //                dependingServices.AddRange(s.DependentServices.Select(sc => s.ServiceName));

        //                try {
        //                    s.Start();
        //                    MonitoredServices[s.ServiceName]--;
        //                } catch(Exception e) {
        //                    Logger.Log.Error("Exception occured while trying to start service: " + "[" + s.ServiceName + "]\n" + e);
        //                }
        //                break;
        //            default:
        //                if(MonitoredServices[s.ServiceName] != 0) {
        //                    Logger.Log.Warn("Service is in an unknown state: " + "[" + s.ServiceName + "]");
        //                    MonitoredServices[s.ServiceName] = 0;
        //                    // SendEMail(s.Key.ServiceName, true, false);
        //                }
        //                break;
        //        }
        //    }

        //    //if gateserver stopped, but not the corresponding worldserver, stop this worldserver for reconnection!
        //    foreach(var s in serviceList) {
        //        if(dependingServices.Contains(s.ServiceName)) {
        //            if(s.Status == ServiceControllerStatus.Running)
        //                s.Stop();
        //        }
        //    }
        //}

        /*
         * Create a new service object and add any current objects to the
         * service list.
         */

        public static Service_T CreateService(ServiceConfig sc, string name, string command = null)
        {
            var current = new Service_T();
            var type    = MonitServiceType.Service_System;
            var value   = "";
            Func <Service_T, bool> check = null;

            if (sc == null)
            {
                check         = Validate.CheckSystem;
                type          = MonitServiceType.Service_System;
                current.every = new CycleEvery_T {
                    type = MonitEveryType.Every_Cycle, number = 0
                };
            }
            else
            {
                if (sc is ProcessConfig)
                {
                    check = Validate.CheckProcess;
                    type  = MonitServiceType.Service_Process;
                    current.resourcelist = new List <Resource_T>();
                    var processConf = sc as ProcessConfig;
                    if (processConf.Resources != null && processConf.Resources.Count > 0)
                    {
                        foreach (var resource in processConf.Resources)
                        {
                            AddResource(current,
                                        new Resource_T
                            {
                                resource_id  = (MonitResourceType)resource.Type,
                                compOperator = resource.ComparisonOperator,
                                limit        = resource.Limit,
                                action       =
                                    GetEventAction((MonitActionType)resource.ActionType,
                                                   MonitActionType.Action_Ignored)
                            });
                        }
                    }
                    else
                    {
                        Logger.Log.ErrorFormat("error: No Resources defined for Process: {0}", sc.Name);
                    }
                }
                else if (sc is FilesystemConfig)
                {
                    check = Validate.CheckFilesystem;
                    type  = MonitServiceType.Service_Filesystem;
                    current.filesystemlist = new List <Filesystem_T>();
                    var filesystemConf = sc as FilesystemConfig;
                    if (filesystemConf.Filesystems != null && filesystemConf.Filesystems.Count > 0)
                    {
                        foreach (var filesystem in filesystemConf.Filesystems)
                        {
                            AddFilesystem(current,
                                          new Filesystem_T
                            {
                                resource       = (MonitResourceType)filesystem.Type,
                                compOperator   = filesystem.ComparisonOperator,
                                limit_absolute = filesystem.LimitAbsolute,
                                limit_percent  = filesystem.LimitPercent,
                                action         =
                                    GetEventAction((MonitActionType)filesystem.ActionType,
                                                   MonitActionType.Action_Ignored)
                            });
                        }
                    }
                    else
                    {
                        Logger.Log.ErrorFormat("error: No Filesystems defined for Drive: {0}", sc.Name);
                    }
                }
                else
                {
                    return(null);
                }

                current.mode = (MonitMonitorModeType)sc.MonitoringMode;

                if (sc.ActionRate != null)
                {
                    AddActionRate(current,
                                  new ActionRate_T
                    {
                        count  = sc.ActionRate.Count,
                        cycle  = sc.ActionRate.Cycle,
                        action =
                            GetEventAction((MonitActionType)sc.ActionRate.ActionType, MonitActionType.Action_Alert)
                    });
                }
                else
                {
                    Logger.Log.ErrorFormat("warning: No ActionRate defined for Service: {0}", sc.Name);
                }

                if (sc.Every != null)
                {
                    current.every = new CycleEvery_T
                    {
                        type   = (MonitEveryType)sc.Every.Type,
                        number = sc.Every.CycleNumber
                    };
                }
                else
                {
                    current.every = new CycleEvery_T {
                        type = MonitEveryType.Every_Cycle, number = 0
                    };
                }
            }

            if (Util.ExistService(name))
            {
                Logger.Log.ErrorFormat("Service name conflict, {0} already defined", name);
                return(null);
            }

            current.type = type;

            switch (type)
            {
            case MonitServiceType.Service_Filesystem:
                current.inf = new FileSystemInfo_T();
                break;

            case MonitServiceType.Service_File:
                current.inf = new FileInfo_T();
                break;

            case MonitServiceType.Service_Directory:
                current.inf = new DirectoryInfo_T();
                break;

            case MonitServiceType.Service_Fifo:
                current.inf = new FiFoInfo_T();
                break;

            case MonitServiceType.Service_Process:
                current.inf = new ProcessInfo_T();
                break;

            case MonitServiceType.Service_Net:
                current.inf = new NetInfo_T();
                break;

            default:
                break;
            }
            Util.ResetInfo(current);

            if (type == MonitServiceType.Service_Program)
            {
                current.program         = new Program_T();
                current.program.args    = command;
                current.program.timeout = 5 * 60;
            }

            /* Set default values */
            current.monitor = MonitMonitorStateType.Monitor_Init;
            current.mode    = MonitMonitorModeType.Monitor_Active;
            current.name    = name;
            current.check   = check;
            current.path    = value;

            /* Initialize general event handlers */
            current.action_DATA    = GetEventAction(MonitActionType.Action_Alert, MonitActionType.Action_Alert);
            current.action_EXEC    = GetEventAction(MonitActionType.Action_Alert, MonitActionType.Action_Alert);
            current.action_INVALID = GetEventAction(MonitActionType.Action_Restart, MonitActionType.Action_Alert);

            current.action_MONIT_START  = GetEventAction(MonitActionType.Action_Start, MonitActionType.Action_Ignored);
            current.action_MONIT_STOP   = GetEventAction(MonitActionType.Action_Stop, MonitActionType.Action_Ignored);
            current.action_MONIT_RELOAD = GetEventAction(MonitActionType.Action_Start, MonitActionType.Action_Ignored);
            current.action_ACTION       = GetEventAction(MonitActionType.Action_Alert, MonitActionType.Action_Ignored);

            current.collected = DateTime.UtcNow;
            current.eventlist = new List <Event_T>();

            return(current);
        }
Example #23
0
        /// <summary>
        ///     Check to see if we should try to start/stop service
        /// </summary>
        /// <param name="S">A service name as stated in the config file</param>
        /// <param name="A">An action id describing the action to execute</param>
        /// <returns>false for error, otherwise true</returns>
        public static bool ControlService(string S, MonitActionType A)
        {
            Service_T s = null;

            if ((s = Util.GetService(S)) == null)
            {
                Logger.Log.ErrorFormat("Service '{0}' -- doesn't exist", S);
                return(false);
            }

            switch (A)
            {
            case MonitActionType.Action_Start:
                _doDepend(s, MonitActionType.Action_Stop, false);
                _doStart(s);
                _doDepend(s, MonitActionType.Action_Start, false);
                break;

            case MonitActionType.Action_Stop:
                _doDepend(s, MonitActionType.Action_Stop, true);
                _doStop(s, true);
                break;

            case MonitActionType.Action_Restart:
                Logger.Log.InfoFormat("'{0}' trying to restart", s.name);
                _doDepend(s, MonitActionType.Action_Stop, false);
                if (s.restart != null)
                {
                    _doRestart(s);
                    _doDepend(s, MonitActionType.Action_Start, false);
                }
                else
                {
                    if (_doStop(s, false))
                    {
                        /* Only start if stop succeeded */
                        _doStart(s);
                        _doDepend(s, MonitActionType.Action_Start, false);
                    }
                    else
                    {
                        /* enable monitoring of this service again to allow the restart retry in the next cycle up to timeout limit */
                        Util.MonitorSet(s);
                    }
                }
                break;

            case MonitActionType.Action_Monitor:
                /* We only enable monitoring of this service and all prerequisite services. Chain of services which depends on this service keep its state */
                _doMonitor(s, false);
                break;

            case MonitActionType.Action_Unmonitor:
                /* We disable monitoring of this service and all services which depends on it */
                _doDepend(s, MonitActionType.Action_Unmonitor, false);
                _doUnmonitor(s, false);
                break;

            default:
                Logger.Log.ErrorFormat("Service '{0}' -- invalid action {1}", S, A);
                return(false);
            }
            return(true);
        }
Example #24
0
        public static void Post(Service_T service, MonitEventType id, MonitStateType state, EventAction_T action,
                                string s, params object[] args)
        {
            var message = string.Format(s, args);

            Event_T E = null;

            if (service.eventlist != null)
            {
                service.eventlist.ForEach(e =>
                {
                    if (e.action == action && e.id == id)
                    {
                        e.collected   = DateTime.UtcNow;
                        e.state_map <<= 1;
                        e.state_map  |= ((state == MonitStateType.State_Succeeded ||
                                          state == MonitStateType.State_ChangedNot)
                            ? 0
                            : 1);
                        e.message = message;
                        E         = e;
                    }
                });
            }

            if (E == null)
            {
                if (state == MonitStateType.State_Succeeded || state == MonitStateType.State_ChangedNot)
                {
                    Logger.Log.DebugFormat("'{0}' {1}", service.name, message);
                    return;
                }

                E           = new Event_T();
                E.id        = id;
                E.collected = DateTime.UtcNow;
                E.source    = service.name;
                E.mode      = service.mode;
                E.type      = service.type;
                E.state     = MonitStateType.State_Init;
                E.state_map = 1;
                E.action    = action;
                E.message   = message;
                if (service.eventlist == null)
                {
                    service.eventlist = new List <Event_T>();
                }
                service.eventlist.Insert(0, E);
            }

            E.state_changed = CheckState(E, state);

            if (E.state_changed)
            {
                E.state = state;
                E.count = 1;
            }
            else
            {
                E.count++;
            }

            handleEvent(service, E);
        }
Example #25
0
        /// <summary>
        ///     Handles the event.
        /// </summary>
        /// <param name="S">The s.</param>
        /// <param name="E">The e.</param>
        private static void handleEvent(Service_T S, Event_T E)
        {
            /* We will handle only first succeeded event, recurrent succeeded events
             * or insufficient succeeded events during failed service state are
             * ignored. Failed events are handled each time. */
            if (!E.state_changed &&
                (E.state == MonitStateType.State_Succeeded || E.state == MonitStateType.State_ChangedNot ||
                 ((E.state_map & 0x1) ^ 0x1) == 1))
            {
                Logger.Log.DebugFormat("'{0}' {1}%s", S.name, E.message);
                return;
            }

            if (!string.IsNullOrEmpty(E.message))
            {
                /* In the case that the service state is initializing yet and error
                 * occured, log it and exit. Succeeded events in init state are not
                 * logged. Instance and action events are logged always with priority
                 * info. */
                if (E.state != MonitStateType.State_Init || (E.state_map & 0x1) == 1)
                {
                    if (E.state == MonitStateType.State_Succeeded || E.state == MonitStateType.State_ChangedNot ||
                        E.id == MonitEventType.Event_Instance || E.id == MonitEventType.Event_Action)
                    {
                        Logger.Log.InfoFormat("'{0}' {1}", S.name, E.message);
                    }
                    else
                    {
                        Logger.Log.ErrorFormat("'{0}' {1}", S.name, E.message);
                    }
                }
                if (E.state == MonitStateType.State_Init)
                {
                    return;
                }
            }

            if (E.state == MonitStateType.State_Failed || E.state == MonitStateType.State_Changed)
            {
                if (E.id != MonitEventType.Event_Instance && E.id != MonitEventType.Event_Action)
                {
                    // We are not interested in setting error flag for instance and action events
                    S.error |= (int)E.id;
                    /* The error hint provides second dimension for error bitmap and differentiates between failed/changed event states (failed=0, chaged=1) */
                    if (E.state == MonitStateType.State_Changed)
                    {
                        S.error_hint |= (int)E.id;
                    }
                    else
                    {
                        S.error_hint &= ~(int)E.id;
                    }
                }
                handleAction(E, E.action.failed);
            }
            else
            {
                S.error &= ~(int)E.id;
                handleAction(E, E.action.succeeded);
            }

            /* Possible event state change was handled so we will reset the flag. */
            E.state_changed = false;
        }