Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 632f1f295c
Fetching contributors…

Cannot retrieve contributors at this time

file 193 lines (150 sloc) 6.061 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
from __future__ import with_statement

import ConfigParser
import os
import pymongo

from flask import flash, Flask, g, render_template, request, session, redirect,\
    url_for, abort

app = Flask(__name__)
config = ConfigParser.ConfigParser()
config.readfp(open("madmin.ini"))

###############################
## Before Request
###############################

@app.before_request
def connect_mongo():
    servers = {}
    sections = config.sections()
    for section in sections:
        if "server" in section:
            host = config.get(section, "host", "127.0.0.1")
            port = config.getint(section, "port")
            name = config.get(section, "name", None)
            server_info = dict(name=name, host=host, port=port)
            servers.update({section: server_info})
    
    ## if nothing was configured, setup the basic defaults
    if not servers:
        server = dict(name="Default", host="127.0.0.1", port=27017)
        servers.update({"server_1": server})
        
    ## If the default option is not set choose the first one.
    if not config.has_option("madmin", "default"):
        first = servers.keys()[0]
        server = servers.get(first)
    else:
        default = config.get("madmin", "default")
        server = servers.get(default)
    
    if request.path and "server" in request.path:
        use_server = request.path.split("/")[1]
        server = servers.get(use_server)
        
    ## connect up to the initial mongo server.
    try:
        g.mongo = pymongo.Connection(server.get("host"), server.get("port"))
        g.servers = servers
    except pymongo.errors.ConnectionFailure, e:
        return "Unable to connect to MongoDB instance."
         

##############################
# Database Management
##############################

@app.route("/<server>")
@app.route("/")
def databases(server=None):
    
    databases = []
    
    for database in g.mongo.database_names():
        total_indexes = 0
        total_size = 0
        total_index_size = 0
        
        # don't want people removing these as I believe they are important
        if database in ["test", "local"]:
                continue

        for coll in g.mongo[database].collection_names():
            
            try:
                idx_info = g.mongo[database].command("collstats", coll, safe=True)
            except pymongo.OperationalError, e:
                print e
                
            total_indexes += idx_info.get("nindexes")
            total_size += idx_info.get("storageSize")
            total_index_size += idx_info.get("totalIndexSize")
        
        db = dict(
            name=database,
            size=total_size,
            indexes=total_indexes,
            collections=len(g.mongo[database].collection_names()),
            index_size=total_index_size,
        )
        databases.append(db)
    
    return render_template("index.html", databases=databases, servers=g.servers)
    
    
@app.route("/database/clone", methods=["POST",])
def clone_database():
    if request.method == "POST":
        if "from" in request.form and "to" in request.form:
            from_db = request.form.get("from")
            to_db = request.form.get("to")
            
            try:
                g.mongo.copy_database(from_db, to_db)
                flash("%s has been cloned to %s." % (from_db, to_db))
            except pymongo.errors.InvalidName:
                return "Originating database does not exist."
            except TypeError:
                return "From & To must be strings."
            except pymongo.errors.OperationError, e:
                print e
                return "Unable to clone database."
            finally:
                return ""
            
    
@app.route("/database/repair/<database>")
def repair_database(database):
    try:
        g.mongo[database].command("repairDatabase", safe=True)
    except pymongo.errors.OperationError, e:
        return "Unable to repair database."
        
    flash("%s has been repaired." % (database))
    return redirect(url_for("databases"))

    
@app.route("/database/drop/<database>")
def drop_database(database):
    try:
        g.mongo.drop_database(database)
        flash("%s has been dropped." % database)
    except Exception ,e:
        flash("Unable to drop %s. (%s)" % (database, e))
        
    return redirect(url_for("databases"))
        
        
##############################
# Collection Management
##############################

@app.route("/<database>/collections")
def list_collections(database):
    
    collections = []
    for coll in g.mongo[database].collection_names():
        if coll in ["system.indexes",]:
            continue
            
        total_indexes = total_size = total_index_size = 0
        try:
            idx_info = g.mongo[database].command("collstats", coll, safe=True)
        except pymongo.OperationalError, e:
            print e
            
        total_indexes += idx_info.get("nindexes")
        total_size += idx_info.get("storageSize")
        total_index_size += idx_info.get("totalIndexSize")
    
        collection = dict(
            name=coll,
            size=total_size,
            indexes=total_indexes,
            index_size=total_index_size,
            documents=idx_info.get("count")
        )
        collections.append(collection)
    return render_template("collections.html", collections=collections)
        
        
##############################
# Filters
##############################
def pretty_size(size):
    kb = float(size) / float(1024)
    mb = kb / float(1024)
    gb = mb / float(1024)
    
    if gb > 1:
        return "%s GB" % (round(gb, 2))
    
    if mb > 1:
        return "%s MB" % (round(mb,2))
        
    return "%s KB" % (round(kb,2))
    
app.jinja_env.filters["pretty_size"] = pretty_size

if __name__ == "__main__":
    app.secret_key = "kTNpaQRVgJzwwTxcavixEpQqTwQezSVJLkALaUiJDj0fBc1Cfd"
    app.run(host=config.get("madmin", "host"), port=int(config.getint("madmin", "port")), debug=True)
Something went wrong with that request. Please try again.