#!/bin/sh
# - mongodb_cpu_node_bind
# - mongodb_mem_node_bind
# - nr_processes

. "$LKP_SRC/lib/reproduce-log.sh"
. "$LKP_SRC/lib/numactl.sh"
. "$LKP_SRC/lib/unit.sh"

bg_pids=""
mongodb_server="$BENCHMARK_ROOT/mongodb/bin/mongod"

if [ -n "$mount_points" ]; then
	MONGODB_DIR="${mount_points%% *}"
else
	echo "Can not get the mount points, exit!" 1>&2
	exit 1
fi

# it's used for controling how much memory one mongodb comsumes
# https://docs.mongodb.com/manual/reference/configuration-options/#storage.wiredTiger.engineConfig.cacheSizeGB
# by default:
#    Starting in MongoDB 3.4, the default WiredTiger internal cache size is the larger of either:
#    50% of (RAM - 1 GB), or 256 MB.
setup_cache_size()
{
	local memory_byte=$(to_byte $memory)
	local nr_node=${nr_node:-1}

	[ "$mongodb_mem_node_bind" ] && {
		memory_byte=$((memory_byte / nr_node)) # memory per node
	}

	cache_size_gb=$((memory_byte / 2)) # 50% memory
	cache_size_gb=$((cache_size_gb / nr_processes)) # memory per mongodb instance
	cache_size_gb=$(to_gb $cache_size_gb)
	[ $cache_size_gb -eq 0 ] && cache_size_gb=1
}

setup_cache_size

for i in $(seq 1 "$nr_processes")
do
        mkdir -p "$MONGODB_DIR/mongodb/dbdir_$i"
        port=$((27016 + i))
        cat > "$TMP_RESULT_ROOT/mongod.conf.$i" <<EOF
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
 dbPath: $MONGODB_DIR/mongodb/dbdir_$i
 journal:
  enabled: true
#  engine:
#  mmapv1:
 wiredTiger:
   engineConfig:
     cacheSizeGB: $cache_size_gb

# where to write logging data.
systemLog:
 destination: file
 logAppend: true
 path: $MONGODB_DIR/mongodb/dbdir_$i/mongod.log

# network interfaces
net:
 port: $port
#  bindIp: 127.0.0.1
EOF
done

parse_numa_node_binding "$mongodb_cpu_node_bind" "$mongodb_mem_node_bind"

# start mongodb server
for i in $(seq 1 "$nr_processes")
do
	port=$((27016+i))
	numa_bind=$(numa_node_binding "$i")
	log_eval "$numa_bind $mongodb_server --port $port --dbpath=${MONGODB_DIR}/mongodb/dbdir_$i/ --config ${TMP_RESULT_ROOT}/mongod.conf.$i &"
	bg_pids="$bg_pids $!"
done

cat > "$TMP_RESULT_ROOT/post-run.mongodb" <<EOF
/bin/kill -15 $bg_pids
EOF
