21
Sat, Dec
3 New Articles

TechTip: Monit, the UNIX System Service Watch Dog

Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times
Manage, monitor, and automatically repair services, processes, and many other resources with the free open-source tool Monit.

 

Many of you have heard me and fellow author Barry L. Kline mention the Nagios utility in the past. While I implement Nagios on my networks to diligently monitor everything from host devices to services, it's not necessarily always easy and convenient to implement event handlers to act on problems; Nagios has a very steep learning curve. So if you just want a simple utility designed specifically to restart services and act on behalf of conditions you have set forth, consider Monit instead. Monit can provide automated recovery of services and processes on a Linux system in very simple fashion.

What Can Monit Do for You?

My IT department maintains a Linux host running OpenVPN to provide us 24x7 access to inside our network at the office. This means we can work from home or, more importantly, get inside to repair a problem when we're out of town. OpenVPN runs on a CentOS/Red Hat installation and therefore runs as any RHEL service normally does. What happens when OpenVPN locks up or dies when we're hours away from the office? Either one of us would be stuck finding another member of the department to physically get to the host in the building, or worse yet, we would lose access until we return home. Monit, however, can correct this issue for us so we don't have to worry.

 

Using this OpenVPN example, Monit's job would be to check OpenVPN constantly to ensure the service is in fact running. If it detects that it has stopped, it will attempt to restart the service with whatever parameters you have set up. You can have it send you an email or a page stating that it restarted the service or, if you don't care about the event, have it alert you only if it can't successfully revive OpenVPN. This is only one small example of what Monit is capable of, and you can use it in many more advanced ways.

 

Already you can see the crisis aversion that it can provide for you. Monit not only provides this feature, but also allows you to configure a Web-based page on each host if you would like to restart services from the Web page. The Web page provides some useful reporting output as well, such as uptime of services and the amount of CPU and memory utilization for services that you have configured. Although very useful, the Web feature is not a mandatory part of Monit.

Obtaining Monit

Monit is available either in source form or in many pre-packaged forms, depending on what Linux OS you are most familiar with. You can obtain the packages from the downloads section of the Web site. As usual, my favorite Linux flavor is CentOS/RHEL, so my installation was done across RPM packages using yum and third-party repositories. My commands are a reflection of that. Choose your installation based upon your needs, and once you have Monit installed, you can start on configurations.

Configuring Monit

I encourage you to read the Monit documentation (it's a fairly short read), but if you're like me, you'd rather jump right into configurations. Monit's configuration file is just a simple text file that can be edited at /etc/monit.conf. You can either specify all your configurations in this one file or add a location to split out configurations. Open up /etc/monit.conf and ensure the following line is uncommented.

 

# vim /etc/monit.conf include /etc/monit.d/*

 

Once you save the file, you'll need to create the directory to hold the includes. Also, if you're using a RHEL or CentOS installation, you'll need to turn the service on to start at boot time.

 

# mkdir /etc/monit.d # chkconfig monit on

 

There are only a few items located in the configuration file that you have to make sure are set up before you can start specifying resources watch. The first is how frequently you want the daemon to check your services. This is specified in seconds.

 

set daemon 120

 

Second, set the logging facility you want to use. The default is fine, unless you use other logging services.

 

set logfile syslog facility log_daemon

 

Next, configure the mail server you want alerts sent to. You can also specify a backup in case connections to the primary server fail, as well as a fail-safe to localhost.

 

set mailserver mail.yourserver.com,                mail.your2ndserver.com,                localhost

 

Last, set the recipient email address alerts should be sent to. You have two options: send all alerts or send only service-timeout alerts. All alerts can be verbose, meaning you'll get messages for everything, including every time you change the configuration file and restart Monit. You can override this setting within each service or condition you set up later on, so I only set mine to alert me on a timeout.

 

set alert This email address is being protected from spambots. You need JavaScript enabled to view it. only on { timeout }

Optional Monit Configurations

Although useful, a few settings in the configuration file are optional (they're documented within the file). The first is the event queue setting. This setting can be configured to use a directory, like a spool file, to store messages should a mail server be unavailable.

 

The next item is an editable template used to generate the messages. If you would like to overwrite the default, you can do so here. A section on alert message layouts can be found in the Monit documentation.

 

The last optional piece of Monit is the embedded Web server, which I mentioned earlier. You can configure it so that anyone can connect, you can restrict connections with a user name and password, or you can specify hostnames and IP addresses. Combinations of both are allowed as well. For a liberal setting, use the following:

 

set httpd port 2812 and

     allow admin:monit

 

Once you've completed all the options, go ahead and start Monit.

 

# service monit start

 

Starting process monitor (monit): Starting monit daemon with http interface at [*:2812]

 

If you've configured the embedded Web server portion, you should be able to browse to your instance and check out the Web page. Since you have only the Monit service running, the only item visible will be the Monit service itself. Once you've configured other services, you can revisit the page to inspect, start, stop, and disable monitoring from this location. The Web page will look like Figure 1 below.

 

010408Hetrick_monit_web.png
Figure 1: This is the Monit service manager Web page. (Click image to enlarge.)

Setting Up Service Checks

Let's go back to the OpenVPN server I mentioned at the beginning. Again, my example is running OpenVPN on CentOS installation, so your usage will vary. Create the following file and enter the paths for the start and stop commands.

 

# vim /etc/monit.d/openvpn.conf

check process openvpn with pidfile /var/run/openvpn/server.pid

   start program = "/etc/init.d/openvpn start"

   stop program = "/etc/init.d/openvpn stop"

   if 5 restarts within 5 cycles then timeout

 

This definition will attempt to restart the service five times within five cycles of two minutes apiece if Monit notices OpenVPN is not running. If it fails after the 10-minute attempt, it will time out and alert you. Save the file and then restart monit.

 

# service monit restart

 

If a service times out because it cannot start back up normally within the cycle specified, Monit puts a timeout lock on the service so it doesn't loop itself forever. Once you've been alerted and resolved the issue, enable the service checks again and stop the timeout lock.

 

# monit monitor openvpn

 

If you configured the Web interface, you can see the new service appear in a list detailing CPU and memory usage. You can also click on the service to view more details, as well as start and stop the service.

The Many Uses of Monit

The OpenVPN example is only the tip of the iceberg on what this utility is able to do. Within the main configuration file and at the Monit examples section of the Web site, many more elaborate definitions can be found and put to use. For example, you can use Monit to watch system load, memory, and CPU usage to verify checksums, permissions, and existence of files and directories on UNIX systems. By being able to check and actively respond to situations, you'll never have to worry about your Linux servers and workstations again.

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: