View Javadoc

1   /*******************************************************************************
2    * Copyright (c) 2007, 2014 Massimiliano Ziccardi
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   *******************************************************************************/
16  package it.jnrpe.plugin;
17  
18  import it.jnrpe.ICommandLine;
19  import it.jnrpe.Status;
20  import it.jnrpe.plugins.Metric;
21  import it.jnrpe.plugins.MetricGatheringException;
22  import it.jnrpe.plugins.PluginBase;
23  import it.jnrpe.utils.BadThresholdException;
24  import it.jnrpe.utils.thresholds.ThresholdsEvaluatorBuilder;
25  
26  import java.math.BigDecimal;
27  import java.sql.Connection;
28  import java.sql.Driver;
29  import java.sql.DriverManager;
30  import java.sql.SQLException;
31  import java.util.ArrayList;
32  import java.util.Collection;
33  import java.util.List;
34  import java.util.Properties;
35  
36  /**
37   * Tests connections to a PostgreSQL Database.
38   *
39   * @author Frederico Campos
40   */
41  public class CheckPgsql extends PluginBase {
42  
43      /*
44       * default settings
45       */
46  
47      /**
48       * Default hostname.
49       */
50      private static final String DEFAULT_HOSTNAME = "localhost";
51  
52      /**
53       * Default server port.
54       */
55      private static final String DEFAULT_PORT = "5432";
56  
57      /**
58       * Default server table.
59       */
60      private static final String DEFAULT_TABLE = "template1";
61  
62      /**
63       * Default timeout.
64       */
65      private static final String DEFAULT_TIMEOUT = "10";
66  
67      @Override
68      public void configureThresholdEvaluatorBuilder(
69              final ThresholdsEvaluatorBuilder thrb,
70              final ICommandLine cl)
71              throws BadThresholdException {
72          if (cl.hasOption("th")) {
73              super.configureThresholdEvaluatorBuilder(thrb, cl);
74          } else {
75              thrb.withLegacyThreshold("conn", null,
76                      cl.getOptionValue("warning"),
77                      cl.getOptionValue("critical"));
78          }
79      }
80  
81      @Override
82      public Collection<Metric> gatherMetrics(ICommandLine cl)
83              throws MetricGatheringException {
84  
85          List<Metric> metricList = new ArrayList<Metric>();
86  
87          Connection conn = null;
88          Long start = System.currentTimeMillis();
89  
90          try {
91              conn = getConnection(cl);
92          } catch (ClassNotFoundException e) {
93              log.error("PostgreSQL driver library not found into the classpath: "
94                      + "download and put it in the same directory of "
95                      + "this plugin");
96              throw new MetricGatheringException("Error accessing the PostgreSQL "
97                      + "server - JDBC driver not installed", Status.CRITICAL, e);
98          } catch (Exception e) {
99              log.error("Error accessing the PostgreSQL server", e);
100             throw new MetricGatheringException("Error accessing the PostgreSQL "
101                     + "server - ", Status.CRITICAL, e);
102         }
103         finally {
104             closeConnection(conn);
105         }
106 
107         Long end = System.currentTimeMillis();
108         Long elapsed = new Long((end - start) / 1000);
109 
110         metricList.add(new Metric("conn", "Connection time : " + elapsed + "s",
111                 new BigDecimal(elapsed), new BigDecimal(0), null));
112 
113         return metricList;
114     }
115 
116 
117 
118     /**
119      * Connect to the server.
120      *
121      * @param cl
122      *            The command line
123      * @return The connection
124      * @throws SQLException
125      *             -
126      * @throws InstantiationException
127      *             -
128      * @throws IllegalAccessException
129      *             -
130      * @throws ClassNotFoundException
131      *             -
132      */
133     private Connection getConnection(final ICommandLine cl)
134             throws SQLException,
135             InstantiationException, IllegalAccessException,
136             ClassNotFoundException {
137         String database = DEFAULT_TABLE;
138         if (cl.hasOption("database")) {
139             database = cl.getOptionValue("database");
140         }
141         String hostname = DEFAULT_HOSTNAME;
142         if (cl.hasOption("hostname")
143                 && !"".equals(cl.getOptionValue("hostname"))) {
144             hostname = cl.getOptionValue("hostname");
145         }
146         String port = DEFAULT_PORT;
147         if (cl.hasOption("port") && !"".equals(cl.getOptionValue("port"))) {
148             port = cl.getOptionValue("port");
149         }
150         String password = "";
151         if (cl.hasOption("password")) {
152             password = cl.getOptionValue("password");
153         }
154         String username = "";
155         if (cl.hasOption("logname")) {
156             username = cl.getOptionValue("logname");
157         }
158         String timeout = DEFAULT_TIMEOUT;
159         if (cl.getOptionValue("timeout") != null) {
160             timeout = cl.getOptionValue("timeout");
161         }
162         Properties props = new Properties();
163         props.setProperty("user", username);
164         props.setProperty("password", password);
165         props.setProperty("timeout", timeout);
166         String url =
167                 "jdbc:postgresql://" + hostname + ":" + port + "/" + database;
168         DriverManager.registerDriver((Driver) Class.forName(
169                 "org.postgresql.Driver").newInstance());
170         Connection conn = DriverManager.getConnection(url, props);
171         return conn;
172 
173     }
174 
175     /**
176      * Closes the connection.
177      *
178      * @param conn
179      *            The connectiont o be closed
180      */
181     private void closeConnection(final Connection conn) {
182         try {
183             if (conn != null) {
184                 conn.close();
185             }
186         } catch (SQLException e) {
187             e.printStackTrace();
188         }
189     }
190 
191     @Override
192     protected String getPluginName() {
193         return "CHECK_PGSQL";
194     }
195 }