venerdì 14 ottobre 2011

MongoDB and Java - Checking cluster status

Java Example for monitoring MongoDB Cluster.

package freedbtoMongoDb;

import com.mongodb.DB;
import com.mongodb.Mongo;
import java.util.ArrayList;
import java.util.List;

public class CheckCluster {

    static String host = "192.168.0.72";
    static int[] ports = {
        //replica1
        20001, 20002, 20003, 20005,
        //replica11
        20011, 20012, 20013,
        //configsvr1
        20050,
        //configsvr2
        20060,
        //configdb1
        20100,
        //configdb2
        20101
    };

    public static void main(String[] args) {

        try {

            while (true) {
                Thread.sleep(10000);

                for (int port : ports) {

                    try {
                        Mongo m = new Mongo(host, port);
                        List add_l = m.getAllAddress();
                        System.out.println("address:" + add_l);
                        System.out.println("Version: " + m.getVersion());

                        if (m.getReplicaSetStatus() != null) {
                            System.out.println("Replica Name: " + m.getReplicaSetStatus().getName());
                        }

                        ArrayList db_ll = (ArrayList) m.getDatabaseNames();
                        System.out.println("db_list:" + db_ll);
                        for (String db_name : db_ll) {
                            DB d = m.getDB(db_name);
                            System.out.println(db_name + ": " + d.getStats().get("ok") + " - fileSize: " + Double.parseDouble(d.getStats().get("fileSize").toString()) / 1024 + "MB");
                        }

                        m.close();

                        System.out.println();
                    } catch (Exception e) {
                        System.out.println("Problemi sul db: " + port + "\n" + e.getMessage());
                        //send Mail
                    }
                }

            }
        } catch (Throwable t) {
                   //send Mail
        }
    }
}

[download source]

Nessun commento: