-
-
Save kylemclaren/3c09a4dda5991cf0bf9c to your computer and use it in GitHub Desktop.
Find and (safely) kill long running MongoDB ops
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| db.currentOp().inprog.forEach( | |
| function(op) { | |
| if(op.secs_running > 5) printjson(op); | |
| } | |
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // kills long running ops in MongoDB (taking seconds as an arg to define "long") | |
| // attempts to be a bit safer than killing all by excluding replication related operations | |
| // and only targeting queries as opposed to commands etc. | |
| killLongRunningOps = function(maxSecsRunning) { | |
| currOp = db.currentOp(); | |
| for (oper in currOp.inprog) { | |
| op = currOp.inprog[oper-0]; | |
| if (op.secs_running > maxSecsRunning && op.op == "query" && !op.ns.startsWith("local")) { | |
| print("Killing opId: " + op.opid | |
| + " running for over secs: " | |
| + op.secs_running); | |
| db.killOp(op.opid); | |
| } | |
| } | |
| }; | |
| //example: killLongRunningOps(5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi i am a devops engineer, and using mongodb percona in replicaset wondering if this is a production ready script cz i guess we should ignore system queries like .local admin cmd and configs also what about index builds operations here is my script let me know if you guys can test it for edge cases
`#!/usr/bin/env python3
import argparse
import sys
import re
from pymongo import MongoClient
from pymongo.errors import PyMongoError
def parse_args():
parser = argparse.ArgumentParser(
description="Safely kill long-running MongoDB operations (production-ready)"
)
parser.add_argument(
"--uri",
required=True,
help="MongoDB connection string (mongodb+srv://...)"
)
parser.add_argument(
"--seconds",
type=int,
required=True,
help="Kill operations running longer than this many seconds"
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Only print operations, do not kill"
)
parser.add_argument(
"--max-kills",
type=int,
default=3,
help="Maximum operations to kill per run (default: 3)"
)
return parser.parse_args()
def main():
args = parse_args()
if name == "main":
sys.exit(main())
`