https://wiki.uniformserver.com/index.php?title=MongoDB_Plugin_Design:_Support_Functions&feed=atom&action=historyMongoDB Plugin Design: Support Functions - Revision history2024-03-29T02:29:15ZRevision history for this page on the wikiMediaWiki 1.41.0https://wiki.uniformserver.com/index.php?title=MongoDB_Plugin_Design:_Support_Functions&diff=4313&oldid=prevRic: New page: {{Nav MongoDB Plugin Design}} '''''Support Functions''''' Currently we have all our main functions in place allowing server to be started, stopped and administered using the client. Star...2010-08-01T12:54:36Z<p>New page: {{Nav MongoDB Plugin Design}} '''''Support Functions''''' Currently we have all our main functions in place allowing server to be started, stopped and administered using the client. Star...</p>
<p><b>New page</b></p><div>{{Nav MongoDB Plugin Design}}<br />
'''''Support Functions'''''<br />
<br />
Currently we have all our main functions in place allowing server to be started, stopped and administered using the client.<br />
<br />
Starting and stopping MongoDB takes a finite time a method is required to determine when either action is complete. Similarly we need to know if a client is already running.<br />
<br />
With server running Admin requires an easy way to create new users and update exciting user passwords.<br />
<br />
This page covers support functions that address the above.<br />
<br />
== Is MongoDB running? ==<br />
Uniform Server has a small utility '''''pskill.exe''''' returning true if a named process is running.<br />
<br />
This utility is command-line driven making it ideal for scripting.<br />
<br />
We require a function that returns true if MongoDB is running. <br />
<br />
=== Initial setup ===<br />
Copy UniServer\unicon\program\pskill.exe to folder UniServer\usr\local\mongo\bin<br />
<br />
Our script needs to find this file add the following constant to file UniServer\usr\local\mongo\a_test\mongo_db_inc.php<br />
<pre><br />
define("MON_PSKILL_EXE", "$mongo_base_f/usr/local/mongo_tutorial/bin/pskill.exe");<br />
</pre><br />
<br />
=== New batch file ===<br />
Create a new batch file '''''z_mongo_running.bat''''' in folder a_test with the following content<br />
{|<br />
|-<br />
|<br />
<pre><br />
TITLE UNIFORM SERVER - Mongo Running<br />
COLOR B0<br />
@echo off<br />
cls<br />
cd ..\..\php<br />
php.exe -c mongo_tutorial_cli.ini ..\mongo_tutorial\a_test\mongo_running.php<br />
pause<br />
EXIT<br />
|}<br />
<br />
=== New test script ===<br />
Create a new test script '''''mongo_running.php''''' with the following content<br />
{|<br />
|-valign="top"<br />
|<br />
<pre><br />
<?php<br />
chdir(dirname(__FILE__)); // Change wd to this files location<br />
include_once "mongo_db_inc.php";<br />
<br />
if(mongodb_running()){<br />
print "\n Mongo Running \n";<br />
}<br />
else{<br />
print "\n Mongo Not Running \n";<br />
}<br />
<br />
//=== Is MongoDB running ======================================================<br />
function mongodb_running(){<br />
$mongo_exe = "mongod.exe"; <br />
<br />
$cmd = MON_PSKILL_EXE." $mongo_exe"; // command line to be run <br />
exec($cmd,$dummy,$return); // 0=running 1=not-running <br />
<br />
if($return == 0){ // Check return value<br />
return true; // MongoDB is running<br />
}<br />
else{<br />
return false; // MongoDB not running<br />
}<br />
}<br />
//================================================= END Is MongoDB running ====<br />
?><br />
</pre><br />
|<br />
'''''Run Test'''''<br />
<br />
* Start MongoDB double click Run_mongo_no_auth.bat<br />
* Start test script double click z_mongo_running.bat <br />
<br />
* If statement runs function '''mongodb_running()'''<br />
* If returned value is true prints “Mongo Running” <br />
* Otherwise prints “Mongo Not Running”<br />
<br />
'''''Function''''' <br />
* The executable (mongod.exe) to be tested is assigned to a variable. This is not strictly required however function may be converted at a later date to be more generic by passing executable as a parameter to the function.<br />
* A command-line ($cmd) is contracted it defines path to utility pskill and passes a paramter ($mongo_exe) to it.<br />
* This command line is executed returned value from pskill is tested using an if statement.<br />
* 0 returned that executable is running hence function returns true.<br />
* 1 returned executable not running hence function returns false<br />
|}<br />
Cut and copy above function save to file '''''mongo_db_inc.php'''''<br />
<br />
'''''[[#top | Top]]'''''<br />
<br />
== Is MongoDB Client running? ==<br />
Similar to above differences are function and executable name changes.<br />
=== New batch file ===<br />
Create a new batch file '''''z_client_running.bat''''' in folder a_test with the following content<br />
{|<br />
|-<br />
|<br />
<pre><br />
TITLE UNIFORM SERVER - Mongo Client running<br />
COLOR B0<br />
@echo off<br />
cls<br />
cd ..\..\php<br />
php.exe -c mongo_tutorial_cli.ini ..\mongo_tutorial\a_test\client_running.php<br />
pause<br />
EXIT<br />
</pre><br />
|}<br />
<br />
=== New test script ===<br />
Create a new test script '''''client_running.php''''' with the following content<br />
{|<br />
|-valign="top"<br />
|<br />
<pre><br />
<?php<br />
chdir(dirname(__FILE__)); // Change wd to this files location<br />
include_once "mongo_db_inc.php";<br />
<br />
if(mongo_client_running()){<br />
print "\n Mogo Client Running \n";<br />
}<br />
else{<br />
print "\n Mogo Client Not Running \n";<br />
}<br />
<br />
//=== Is Mongo client running =================================================<br />
function mongo_client_running(){<br />
$mongo_exe = "mongo.exe"; <br />
<br />
$cmd = MON_PSKILL_EXE." $mongo_exe"; // command line to be run <br />
exec($cmd,$dummy,$return); // 0=running 1=not-running <br />
<br />
if($return == 0){ // Check return value<br />
return true; // Mongo cient is running<br />
}<br />
else{<br />
return false; // Mongo client not running<br />
}<br />
}<br />
//============================================ END Is Mongo client running ====<br />
?><br />
</pre><br />
|<br />
'''''Run Test'''''<br />
<br />
* Start MongoDB double click Run_mongo_no_auth.bat<br />
* Start MongoDB-Client double click Run_client_no_auth.bat<br />
* Start test script double click z_client_running.bat <br />
<br />
* If statement runs function '''client_running()'''<br />
* If returned value is true prints “Mongo Client Running” <br />
* Otherwise prints “Mongo Client Not Running”<br />
<br />
After testing cut and copy function, save to file '''''mongo_db_inc.php'''''<br />
<br />
'''''Note'':'''<br />
<br />
Coding is one of personal choice this is a classic example. Do you create a generic function and pass the executable as a parameter or use two separate functions. My preference is two functions; duplicated code is small and not an issue. They are slightly easier to use, you do not have to remember to pass a parameter.<br />
|}<br />
<br />
'''''[[#top | Top]]'''''<br />
<br />
== Databases and users ==<br />
Creating a database requires it to be first selected by name and some write action performed on it. A database will not be created until it is written to hence adding a useris a good way to create a database. <br />
<br />
MongoDB is essentially a command-line driven device and certain commands specific to database control are not reflected in the PHP extension these can only be run from the command-line client. We wish to run client in the background although the client supports parameter --eval it cannot run a series of commands. <br />
<br />
Solution is to run commands we require from an external file. This file is piped to Mongo it contains a list of commands and executed as if they were typed at the keyboard.<br />
<br />
=== Command-line format ===<br />
<pre><br />
mongo.exe --port 27017 --username root --password root admin < cmd.txt<br />
</pre><br />
<br />
=== cmd.txt examples ===<br />
The following selects a database and creates a new user: <br />
<pre><br />
use books - select db<br />
db.addUser('fred', 'secret123') - Create new user fred password secret123<br />
</pre><br />
The following selects a database and deletes user fred<br />
<pre><br />
use books - select db<br />
db.system.users.remove ({user: “fred”})<br />
</pre><br />
Having above commands limited to client only is logical; no user other than Admin should have the power to create or delete users.<br />
<br />
== List of client and PHP driver commands ==<br />
{|cellpadding="4" cellspacing="1" style="background:#000000;"<br />
|-valign="top" style="background:#e8e8e8;"<br />
|'''''Client'''''||'''''PHP driver'''''||'''''Comments'''''<br />
|-valign="top" style="background:#f5f5f5;"<br />
|use dbname||$db = $connection->selectDB("dbname")||Select database to use. If database does not exist prepare to create it<br />
|-valign="top" style="background:#f5f5f5;"<br />
|show dbs ||$dbs = $connection->listDBs() ||Lists all available databases<br />
|-valign="top" style="background:#f5f5f5;"<br />
|&nbsp; ||$db->drop()||Drop (delete) currently selected database<br />
|-valign="top" style="background:#f5f5f5;"<br />
|db.addUser("username", "password") ||&nbsp;||Create new user to access currently selected database<br />
|-valign="top" style="background:#f5f5f5;"<br />
|db.system.users.remove( { user: "fred123" } ) ||&nbsp;|| Remove user from currently selected database <br />
|-valign="top" style="background:#f5f5f5;"<br />
|db.system.users.find() ||&nbsp;||Show users for currently selected database <br />
|}<br />
<br />
=== listDBs() ===<br />
Create a new batch file '''''z_list_dbs.bat''''' with the following content:<br />
<pre><br />
TITLE UNIFORM SERVER - Mongo List DBS<br />
COLOR B0<br />
@echo off<br />
cls<br />
cd ..\..\php<br />
php.exe -c mongo_tutorial_cli.ini ..\mongo_tutorial\a_test\z_list_dbs.php<br />
pause<br />
EXIT<br />
</pre><br />
Create a new test script '''''z_list_dbs.php''''' with the following content:<br />
{|<br />
|-valign="top"<br />
|<br />
<pre><br />
<?php<br />
chdir(dirname(__FILE__)); // Change wd to this files location<br />
include_once "mongo_db_inc.php";<br />
<br />
$dbs_array = list_dbs_no_auth();<br />
print_r($dbs_array);<br />
<br />
//$dbs_array = list_dbs_auth();<br />
//print_r($dbs_array);<br />
<br />
//=== List DBS NO Auth ========================================================<br />
// List all DBS on server. <br />
function list_dbs_no_auth(){<br />
$port = get_mongo_port_no_auth(); // Get port from config<br />
<br />
$connection = new Mongo('mongodb://'.'localhost:'.$port); // connect<br />
<br />
$dbs = $connection->listDBs(); //get array of list of dbs<br />
$connection->close(); // disconnect<br />
//print_r($dbs); // Test code<br />
<br />
foreach ($dbs["databases"] as $property=>$value) { // Scan array<br />
$names[] = $value["name"]; // Create aray of names<br />
//print_r($names); // Test code<br />
}<br />
return $names; // Return array of dbs<br />
}<br />
//==================================================== END List DBS NO Auth ===<br />
<br />
//=== List DBS Auth ===========================================================<br />
// List all DBS on server. <br />
function list_dbs_auth(){<br />
$port = get_mongo_port_no_auth(); // Get port from config<br />
$a_pwd_array = get_name_pwd_array(); // Get Admin name and password from file<br />
$name = $a_pwd_array[0]; // Set name <br />
$password = $a_pwd_array[1]; // Set password<br />
<br />
// connect<br />
$connection = new Mongo('mongodb://'.$name.':'.$password.'@localhost:'.$port);<br />
<br />
$dbs = $connection->listDBs(); //get array of list of dbs<br />
$connection->close(); // disconnect<br />
//print_r($dbs); // Test code<br />
<br />
foreach ($dbs["databases"] as $property=>$value) { // Scan array<br />
$names[] = $value["name"]; // Create aray of names<br />
//print_r($names); // Test code<br />
}<br />
return $names; // Return array of dbs<br />
}<br />
//======================================================= END List DBS Auth ===<br />
?><br />
<br />
</pre><br />
|<br />
'''''Overview'''''<br />
<br />
There are two functions each return an array of all databases on the server.<br />
<br />
First function requires no authentication while the second does. Parameters that are changeable by a user are read directly from appropriate configuration file.<br />
<br />
Script is currently enabled to run the no authentication function.<br />
<br />
Hence the code that runs the authentication function is commented out.<br />
<br />
'''''Test 1'':'''<br />
<br />
* Run - Run_mongo_no_auth.bat<br />
* Run - z_list_dbs.bat<br />
* Run - Run_stop_mongo_no_auth.bat<br />
<br />
'''''Test 2'':'''<br />
<br />
Comment no authentication and un-Comment authentication as shown:<br />
<pre><br />
//$dbs_array = list_dbs_no_auth();<br />
//print_r($dbs_array);<br />
<br />
$dbs_array = list_dbs_auth();<br />
print_r($dbs_array);<br />
</pre><br />
<br />
* Run - Run_mongo_auth.bat<br />
* Run - z_list_dbs.bat<br />
* Run - Run_stop_mongo_auth.bat<br />
<br />
'''''Results'':'''<br />
<br />
Minimum of two databases as shown:<br />
<pre><br />
Array<br />
(<br />
[0] => admin<br />
[1] => local<br />
)<br />
Press any key to continue . . .<br />
</pre><br />
|}<br />
'''''Note'':'''<br />
<br />
Cut the two functions and paste in file '''''mongo_db_inc.php'''''<br />
<br />
=== drop() ===<br />
Drop (Delete) a currently selected database.<br />
<br />
Create a new batch file '''''z_drop_db.bat''''' with the following content:<br />
<pre><br />
TITLE UNIFORM SERVER - Mongo Drop DB<br />
COLOR B0<br />
@echo off<br />
cls<br />
cd ..\..\php<br />
php.exe -c mongo_tutorial_cli.ini ..\mongo_tutorial\a_test\z_drop_db.php<br />
<br />
pause<br />
EXIT<br />
</pre><br />
Create a new test script '''''z_drop_db.php''''' with the following content:<br />
{|<br />
|-valign="top"<br />
|<br />
<pre><br />
<?php<br />
chdir(dirname(__FILE__)); // Change wd to this files location<br />
include_once "mongo_db_inc.php";<br />
<br />
$dbs_array = drop_db_no_auth("fred1234");<br />
print_r($dbs_array);<br />
<br />
//$dbs_array = drop_db_auth("mpg456");<br />
//print_r($dbs_array);<br />
<br />
//=== DROP DB NO Auth =========================================================<br />
// Drop (delete) a db <br />
function drop_db_no_auth($db_name){<br />
$port = get_mongo_port_no_auth(); // Get port from config<br />
<br />
$connection = new Mongo('mongodb://'.'localhost:'.$port); // connect<br />
<br />
$db = $connection->selectDB($db_name); // select (create) a database<br />
$response = $db->drop(); // Delete db<br />
//print_r($response); // test code<br />
$connection->close(); // disconnect<br />
}<br />
//===================================================== END DROP DB NO Auth ===<br />
<br />
//=== DROP DB Auth ============================================================<br />
// Drop (delete) a db <br />
function drop_db_auth($db_name){<br />
$port = get_mongo_port_no_auth(); // Get port from config<br />
$a_pwd_array = get_name_pwd_array(); // Get Admin name and password from file<br />
$name = $a_pwd_array[0]; // Set name <br />
$password = $a_pwd_array[1]; // Set password<br />
<br />
$connection = new Mongo('mongodb://'.$name.':'.$password.'@localhost:'.$port); // connect<br />
<br />
$db = $connection->selectDB($db_name); // select (create) a database<br />
$response = $db->drop(); // Delete db<br />
//print_r($response); // test code<br />
$connection->close(); // disconnect<br />
}<br />
//======================================================== END DROP DB Auth ===<br />
?><br />
<br />
<br />
<br />
<br />
<br />
</pre><br />
|<br />
'''''Overview'''''<br />
<br />
There are two functions each drops (deltes) a database '''''db_name''''' passed as parameter on the server.<br />
<br />
First function requires no authentication while the second does. Parameters that are changeable by a user are read directly from appropriate configuration file.<br />
<br />
Script is currently enabled to run the no authentication function.<br />
<br />
Hence the code that runs the authentication function is commented out.<br />
<br />
'''''Test 1'':'''<br />
<br />
* Run - Run_mongo_no_auth.bat<br />
* Run - z_drop_db.bat<br />
* Run - z_list_dbs.bat<br />
* Run - Run_stop_mongo_no_auth.bat<br />
<br />
Result: Database name '''''fred1234''''' deleted from list.<br />
<br />
'''''Test 2'':'''<br />
<br />
Comment no authentication and un-Comment authentication as shown:<br />
<pre><br />
//$dbs_array = drop_db_no_auth("fred1234");<br />
//print_r($dbs_array);<br />
<br />
$dbs_array = drop_db_auth("mpg456");<br />
print_r($dbs_array);<br />
</pre><br />
<br />
* Run - Run_mongo_auth.bat<br />
* Run - z_drop_db.bat<br />
* Run - z_list_dbs.bat<br />
* Run - Run_stop_mongo_auth.bat<br />
<br />
Result: Database name '''''mpg456''''' deleted from list.<br />
|}<br />
'''''Note'':'''<br />
<br />
Cut the two functions and paste in file '''''mongo_db_inc.php'''''<br />
<br />
'''''[[#top | Top]]'''''<br />
<br />
== Summary ==<br />
That covers most of the functions required for our applications.<br />
<br />
Next page covers some additional functions that may be required to offer more advanced features.<br />
<br />
These are implemented using a [[MongoDB Plugin Design: Command pipe | '''command pipe''']].<br />
<br />
<br />
'''''[[#top | Top]]'''''<br />
<br />
----<br />
<br />
[[Category: Tutorials]]<br />
[[Category: How To]]<br />
[[Category: Uniform Server 6-Carbo]]</div>Ric