Here is a sample code to cleanup MongoDB tasks.
#!/usr/bin/env bash
function do_cleanup() {
mongo 127.0.0.1:27017/admin \
--username 'my-username' \
--password 'my-password' --eval '
db.currentOp().inprog.forEach(
function(op) {
if(op.secs_running > 10 &&
op.client != null &&
op.client.startsWith("127.0.0.1:") ) {
db.killOp(op.opid)
}
}
)
'
}
while sleep 8
do
echo "do cleanup"$(date)
do_cleanup
done;
What Am I Doing Here?
- I will run “do_cleanup” every 8 seconds
- I will login to 127.0.0.1:27017, check my current operation
- I will filter each operation, kill the operations request from 127.0.0.1 and run more than 10 seconds
What Does The “db.currentOp()” Seems Like?
local:PRIMARY> db.currentOp()
{
"inprog" : [
{
"desc" : "conn1379280",
"threadId" : "139962306003704",
"connectionId" : 1379280,
"client" : "127.0.0.1:12345",
"active" : true,
"opid" : 1070507339,
"secs_running" : 0,
"microsecs_running" : NumberLong(11),
"op" : "command",
"ns" : "admin.$cmd",
"query" : {
"currentOp" : 1
},
"numYields" : 0,
"locks" : {
},
"waitingForLock" : false,
"lockStats" : {
"Global" : {
"acquireCount" : {
"r" : NumberLong(20),
"w" : NumberLong(3),
"R" : NumberLong(1),
"W" : NumberLong(2)
}
},
"Database" : {
"acquireCount" : {
"r" : NumberLong(7),
"w" : NumberLong(2),
"W" : NumberLong(1)
}
},
"Collection" : {
"acquireCount" : {
"r" : NumberLong(6)
}
},
"Metadata" : {
"acquireCount" : {
"w" : NumberLong(1)
}
},
"oplog" : {
"acquireCount" : {
"r" : NumberLong(1),
"w" : NumberLong(2)
}
}
}
}
]
}
We just need to read secs_running in each object listed in inprog, and kill them by id, which is appeared as opid in each object.
2 Comments
xqiushi · August 8, 2017 at 21:27
8秒一次,CPU受得了吗?
yu · August 9, 2017 at 03:32
@xqiushi 列出任务并删除的执行速度是 ms 级别.
因此只要花费千分之一的时间来处理它