MongoDB Plugin Design: Start

 

UniServer 6-Carbo
MongoDB plugin design.

Starting MongoDB

Starting MongoDB is very easy this page covers two methods from a batch file and a PHP CLI script. Our main application requires Mongo be run either with or without authentication and hidden in the background.

Manually stopping MongoDB

For testing we will manually stop MongoDB using the mongo-client. Create a new batch file Run_client.bat with the following ontents:

:mode con:cols=65 lines=20
TITLE UNIFORM SERVER - Run Mongo Client
COLOR B0
@echo off
cls
cd ..\bin
mongo.exe
pause
EXIT
  • Changes directory to folder bin
  • Run mongo-client mongo.exe

To stop MongoDB type the following into client:

  • use admin
  • db.shutdownServer()
  • exit

Top

Starting MongoDB from a batch file

To start MongoDB from a batch file

Create a new batch file Run_mongo_no_auth.bat with the following ontents:

:mode con:cols=65 lines=20
TITLE UNIFORM SERVER - Run Mongo Client
COLOR B0
@echo off
cls
cd ..\bin
mongod.exe -f config_no_auth.ini
pause
EXIT
  • Changes directory to folder bin
  • Run mongo-server mongod.exe
  • With following configuration file -f config_no_auth.ini

Top

Test

Running the above batch files is equivalent to running commands from a command prompt.

Start MongoDb

  • Double click Run_mongo_no_auth.bat

Result shown on right. For clarity some details have been removed.

What is important is the last line “listening on port 28017” this confirms server is running.

Accessing: local for the first time
query local.system.namespaces ntoreturn:0 reslen:36 nreturned:0 15ms
enter repairDatabases
    uniform_server
Accessing: uniform_server for the first time
done repairDatabases
db version v1.4.5-pre-, pdfile version 4.5
git version: f07303e44fbfaab5d9eb014aaaec8cb3b64a4c48
waiting for connections on port 27017
web admin interface listening on port 28017

Start Mongo-client

  • Double click Run_client.bat

Result shown on right.

What is important you will see a flashing cursor “>|” this confirms mongo-client has connected to the server and is ready to receive commands.

MongoDB shell version: 1.4.5-pre-
url: test
connecting to: test
type "exit" to exit
type "help" for help
>

We have both server and client running next test cleanly shuts down the sever.

From client close server

Enter the following command:

  • use admin
  • db.shutdownServer()
  • exit

You will notice several error message these I believe are irrelevant!

Ignoring the errors what is important is the “bye” message.

This indicates the command-line client has not fallen over. It received the exit command and terminated with no errors.

MongoDB shell version: 1.4.5-pre-
url: test
connecting to: test
type "exit" to exit
type "help" for help
> use admin
switched to db admin
> db.shutdownServer()
query failed : admin.$cmd { shutdown: 1.0 } to: 127.0.0.1
server should be down...
trying reconnect to 127.0.0.1
reconnect 127.0.0.1 failed couldn't connect to server 127.0.0.1
   127.0.0.1:27017
MessagingPort say send() errno:0 No error 127.0.0.1:27017
JS Error: Error: error doing query: unknown (anon):1284
> exit
bye
Press any key to continue . . .

Server Response

Of real importance is the server’s response to command db.shutdownServer()

It has received this command and initiated a clean server shutdown.

Up to line dbexit: really exiting now there are no errors this confirms server was cleanly shutdown.


What about those errors!

I think it’s a cause of overzealous error reporting. Client has sent a shutdown command, which is dully executed by the server and shuts down. The client is still expecting a response from a killed server!

Probably needs sorting by Mongo’s development team.

From a users point of view it’s not a issue data integrity is maintained.

flushing mmap took 0ms
flushing mmap took 0ms
flushing mmap took 0ms

flushing mmap took 0ms
run command admin.$cmd { shutdown: 1.0 }
Accessing: admin for the first time
terminating, shutdown command received
  dbexit:
      shutdown: going to close listening sockets...
      going to close listening socket: 1876
      going to close listening socket: 1884
 Listener: accept() returns -1 errno:0 No error
      shutdown: going to flush oplog...
 MiniWebServer: accept() returns -1 errno:0 No error
      shutdown: going to close sockets...
      shutdown: waiting for fs preallocator...
      shutdown: closing all files...
      closeAllFiles() finished
  dbexit: really exiting now
ERROR: Client::~Client _context should be NULL: conn
Press any key to continue . . .

Top

Starting MongoDB from a batch file hidden

We want to run MongoDB hidden in the background easiest way to to this is to use Uniform Server’s utility uniserv.exe.

Modify batch file Run_mongo_no_auth.bat as shown below:

:mode con:cols=65 lines=20
TITLE UNIFORM SERVER - Run Mongo Client
COLOR B0
@echo off
cls
cd ..\bin
start uniserv.exe "mongod.exe -f config_no_auth.ini"
pause
EXIT
  • start uniserv.exe - Runs Uniform Server’s utility
  • This runs mongod.exe
  • Because we are passing parameters to mongod.exe separated by spaces it needs to be enclosed in quotes

Top

Test

Start MongoDB

  • Doube click on Run_mongo_no_auth.bat
Nothing to see running in background

Start Mongo-client

  • Double click Run_client.bat

Enter the following command:

  • use admin
  • db.shutdownServer()
  • exit

Confirms MongoDB was running and client can be closed.

MongoDB shell version: 1.4.5-pre-
url: test
connecting to: test
type "exit" to exit
type "help" for help
> use admin
switched to db admin
> db.shutdownServer()
query failed : admin.$cmd { shutdown: 1.0 } to: 127.0.0.1
server should be down...
trying reconnect to 127.0.0.1
reconnect 127.0.0.1 failed couldn't connect to server 127.0.0.1
 127.0.0.1:27017
MessagingPort say send() errno:0 No error 127.0.0.1:27017
JS Error: Error: error doing query: unknown (anon):1284
> exit
bye
Press any key to continue . . .

Restart Mongo-client

  • Double click Run_client.bat

Cannot connect confirms MongoDB was shutdown.

MongoDB shell version: 1.4.5-pre-
url: test
connecting to: test
JS Error: Error: couldn't connect: couldn't connect
to server 127.0.0.1 127.0.0.1:27017 (anon):952
User Exception 12513:connect failed
exception: connect failed
Press any key to continue . . .

Top

Starting MongoDB from a PHP CLI script

Above test has proven we can start MongoDB hidden. We can converts the batch file to a PHP CLI script.

First step is to add a back slash to all quotes as shown

start uniserv.exe \"mongod.exe -f config_no_auth.ini\"

Slit line into smaller manageable parts:

start uniserv.exe \"
mongod.exe
-f config_no_auth.ini\"

Our include file contains a constant to config_no_auth.ini

define("CONFIG_NO_AUTH_F",   "$mongo_base_f/usr/local/mongo_tutorial/bin/config_no_auth.ini"); 

We need to define a constant for uniserv.exe as follows:

define("UNISERV_EXE",   "$mongo_base_f/usr/local/mongo_tutorial/bin/uniserv.exe"); 

Add the above to mongo_db_inc.php

Add the two constants to above and rebuild the command line string as follows:

$cmd1 = "start ".UNISERV_EXE." \"";
$cmd2 = "mongod.exe ";
$cmd3 = "-f ".CONFIG_NO_AUTH_F."\"";
$cmd=$cmd1.$cmd2.$cmd3;

Top

Update batch file

Update batch file Run_mongo_no_auth.bat to have the following content

TITLE UNIFORM SERVER - Run cmd
COLOR B0
@echo off
cls

cd ..\..\php
php.exe -c mongo_tutorial_cli.ini ..\mongo_tutorial\a_test\mongo_no_auth.php

pause

EXIT

New Script

Create a new script mongo_no_auth.php with the following content:

<?php
chdir(dirname(__FILE__)); // Change wd to this files location
include_once "mongo_db_inc.php";

start_mongo_no_auth();

//=== Start Mongo No Auth =====================================================
// Start mongo server. Uses uniserv.exe to detatch hidden process

function start_mongo_no_auth(){
  $return_wd = getcwd();                    // Save current wd 
  chdir(MONGO_BIN);                         // Change wd to Mongo Bin
 
  // Build command line
  $cmd1 = "start ".UNISERV_EXE." \"";
  $cmd2 = "mongod.exe ";
  $cmd3 = "-f ".CONFIG_NO_AUTH_F."\"";
  $cmd=$cmd1.$cmd2.$cmd3;
  //print $cmd; // Test code

  exec($cmd,$dummy,$return);    // Run command 
  chdir($return_wd);           // Restore original wd
}
//================================================= END Start Mongo No Auth ===
?>
  • First operation of the function is to switch working directory to “bin” folder
  • The command line is assembled as explained.
  • This command is executed as a detached process
  • Finally original working directory is restored.

Top

Testing

  • Run test script by double clicking on Run_mongo_no_auth.bat
  • Run Run_client.bat check server can be stopped

After confirming server can be run and closed copy the function to include file.

In our test script modify the function to run server with authentication as shown below:

//=== Start Mongo Auth =======================================================
// Start mongo server. Uses uniserv.exe to detatch hidden process

function start_mongo_auth(){
  $return_wd = getcwd();                    // Save current wd 
  chdir(MONGO_BIN);                         // Change wd to Mongo Bin
 
  // Build command line
  $cmd1 = "start ".UNISERV_EXE." \"";
  $cmd2 = "mongod.exe ";
  $cmd3 = "-f ".CONFIG_AUTH_F."\"";
  $cmd=$cmd1.$cmd2.$cmd3;
  //print $cmd; // Test code

  exec($cmd,$dummy,$return);    // Run command 
  chdir($return_wd);            // Restore original wd
}
//==================================================== END Start Mongo Auth ===

Change line start_mongo_no_auth(); to start_mongo_auth();

Test

  • Run test script by double clicking on Run_mongo_no_auth.bat
  • Run Run_client.bat check server can be stopped

After confirming server can be run and closed copy the function to include file.

Note:

We have not set an admin account hence there is nothing to authenticate the client can connect and close the server.

Top

Final test scripts and batch files

Before moving on ensure you have the following four files with content as shown. They are used throughout the remainder of this tutorial.

Run_mongo_no_auth.bat

TITLE UNIFORM SERVER - Mongo No Auth
COLOR B0
@echo off
cls
cd ..\..\php
php.exe -c mongo_tutorial_cli.ini ..\mongo_tutorial\a_test\mongo_no_auth.php
pause
EXIT

mongo_no_auth.php

<?php
chdir(dirname(__FILE__)); // Change wd to this files location
include_once "mongo_db_inc.php";
start_mongo_no_auth();
?>

Run_mongo_auth.bat

TITLE UNIFORM SERVER - Mongo Auth
COLOR B0
@echo off
cls
cd ..\..\php
php.exe -c mongo_tutorial_cli.ini ..\mongo_tutorial\a_test\mongo_auth.php
pause
EXIT

mongo_auth.php

<?php
chdir(dirname(__FILE__)); // Change wd to this files location
include_once "mongo_db_inc.php";
start_mongo_auth();
?>

Top


Summary

Our basic components (functions) are slowly increasing we now have support for starting Mongo server with or without authentication.

For testing we had to stop the server manually next page covers stopping the server using a PHP CLI script.

Top