Uncaught exception 'MongoConnectionException' - mongodb

Fatal error: Uncaught exception 'MongoConnectionException' with message
'Failed to connect to: localhost:27017: Permission denied' in
/var/www/html/test.php:8 Stack trace: #0 /var/www/html/test.php(8):
MongoClient->__construct() #1 {main} thrown in /var/www/html/test.php
on line 8
Hi Mongo experts...
I am a developer wanting to try out MongoDB. So installed centoOS 6.5 64bit in a test machine (Dell E520 Intel Dual Core 4GB Ram), installed PHP (Apache was already present).
Then installed MongoDB (yum install mongo-10gen mongo-10gen-server), then installed "pecl install mongo" (install ok: channel://pecl.php.net/mongo-1.4.5), added extension=mongo.so to php.ini.
To install pecl, I installed few other things like C++ compiler & php-pear. php5-dev & php5-cli was not available in yum so installed php-devel & php-cli (installed versions are php-devel-5.3.3-27.el6_5.x86_64 & php-cli-5.3.3-27.el6_5.x86_64
I turned off iptables firewall. Ran mongo --host localhost:27017 from shell & connected without problems
[root#localhost ~]# mongo --host localhost:27017
MongoDB shell version: 2.4.8
connecting to: localhost:27017/test
>
These are the contents of test.php
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
// connect
$m = new MongoClient();
//$m = new MongoClient("mongodb://localhost:27017");
// select a database
$db = $m->comedy;
// select a collection (analogous to a relational database's table)
$collection = $db->cartoons;
// add a record
$document = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );
$collection->insert($document);
// add another record, with a different "shape"
$document = array( "title" => "XKCD", "online" => true );
$collection->insert($document);
// find everything in the collection
$cursor = $collection->find();
// iterate through the results
foreach ($cursor as $document) {
echo $document["title"] . "\n";
}
?>
As you can see I have tried both
$m = new MongoClient(); & $m = new MongoClient("mongodb://localhost:27017");
But I am getting the same error. Where am I going wrong?

This problem is documented at http://ca3.php.net/manual/en/mongo.installation.php#mongo.installation.fedora
Red Hat,Fedora and CentOS:
The default Apache settings on these systems do not let requests make network connections, meaning that the driver will get "Permission denied" errors when it tries to connect to the database. If you run into this, try running:
$ /usr/sbin/setsebool -P httpd_can_network_connect 1
Then restart Apache. (This issue has also occurred with SELinux.)
Thanks for all your support!
Hope this thread helps someone from going in circles!

Related

trying to connect to an azure SQL database with python / pyodbc and a raspberry pi

with following code I try to connect to an azure database :
server = 'tcp:myserver.database.windows.net'
database = 'DBFREE'
username = 'user'
password = 'password'
conn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
but getting following error :
pyodbc.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'SQL Server' : file not found (0) (SQLDriverConnect)")
I used following commands to install pyodbc :
sudo apt-get install python-pyodbc
sudo apt-get install unixodbc-dev
pip3 install pyodbc
thanx in advance
As mentioned in my comment I recently walked this path and could never get the drivers from Microsoft to work on my Rasberry PIs. I speculate it has something to do with the ARM architecture. So even though Rasberry PI OS is based on Debian and Microsoft supplies the drivers, I could never get them to work.
I ended up using FreeTDS
First, install using the following commands:
sudo apt-get install freetds-dev freetds-bin unixodbc-dev tdsodbc
sudo pip install pyodbc sqlalchemy
When that is done, open the following file in a text editor:
/etc/odbcinst.ini
Add the following:
[FreeTDS]
Description=FreeTDS Driver
Driver=/usr/lib/arm-linux-gnueabihf/odbc/libtdsodbc.so
Setup=/usr/lib/arm-linux-gnueabihf/odbc/libtdsS.so
Then in the python connection string use FreeTDS as the driver and add ;TDS_Version=8.0 to the end of the connection string:
server = 'servername.database.windows.net'
database = 'database'
username = 'user'
password = 'password'
driver = 'FreeTDS'
pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password + ';TDS_Version=8.0')
Please ref the pyodbc here: Quickstart: Use Python to query a database in Azure SQL Database or Azure SQL Managed Instance
import pyodbc
server = '<server>.database.windows.net'
database = '<database>'
username = '<username>'
password = '<password>'
driver= '{ODBC Driver 17 for SQL Server}'
with pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password) as conn:
with conn.cursor() as cursor:
cursor.execute("SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName FROM [SalesLT].[ProductCategory] pc JOIN [SalesLT].[Product] p ON pc.productcategoryid = p.productcategoryid")
row = cursor.fetchone()
while row:
print (str(row[0]) + " " + str(row[1]))
row = cursor.fetchone()
You didn't set the ODBC driver version and the server don't have prefix tcp: .

CentOS 6.7 and Windows MSSQL connection - FreeTDS and PHP

I searched for answers related to my question but not found what I'm looking for.
I have server with Linux CentOS 6.7. I need to connect to MS SQL Server 2005 on Windows Small Business Server 2003. In CentOS I installed FreeTDS and I managed to connect to SQL Server from terminal using this command:
# TDSVER=7.0 tsql -H ServerIPAdress -p 1433 -U username -P password
As far as I know this command bypass settings in freetds.conf.
Now I need to connect from PHP script. I'm using PDO extension and I tried this DSN string:
$db = new PDO("dblib:version=7.0;host=ServerIPAdress;dbname=Database;","username","password");
This leads me to first error:
Could not find driver
Ok, I understand that - my PHP 5.3.3 installation doesn't have installed PDO driver dblib.
My question: How can I install pdo_dblib driver in CentOS? Many tutorials and answers suggest to install through this command:
yum install php5-sybase
But that package doesn't exist:
No package php-sybase available.
If I check tsql configuration with command
tsql -C
I get these output:
Version: freetds v0.95
freetds.conf directory: /usr/local/etc
MS db-lib source compatibility: no
Sybase binary compatibility: no
Thread safety: yes
iconv library: yes
TDS version: 5.0
iODBC: no
unixodbc: yes
As I understand I need to configure FreeTDS:
./configure --enable-msdblib --with-pdo-dblib=/usr/local
But how can I configure FreeTDS after instalation? I tried to remove current version but I can't find way to do that. Also I tried to install another version but configuration doesn't change.
Any advice are appreciated.
When I run command # odbcinst -j I can see this output:
unixODBC 2.3.0
DRIVERS ...........: /usr/local/etc/odbcinst.ini
SYSTEM DATA SOURCES: /usr/local/etc/odbc.ini
FILE DATA SOURCES..: /usr/local/etc/ODBCDataSources
USER DATA SOURCES..: /root/.odbc.ini
SQLULEN Size.......: 8
SQLSETPOSIROW Size.: 8
Content of my freetds.conf:
# $Id: freetds.conf,v 1.12 2007/12/25 06:02:36 jklowden Exp $
#
# This file is installed by FreeTDS if no file by the same
# name is found in the installation directory.
#
# For information about the layout of this file and its settings,
# see the freetds.conf manpage "man freetds.conf".
# Global settings are overridden by those in a database
# server specific section
[global]
# TDS protocol version
tds version = 7.0
# Whether to write a TDSDUMP file for diagnostic purposes
# (setting this to /tmp is insecure on a multi-user system)
; dump file = /tmp/freetds.log
; debug flags = 0xffff
# Command and connection timeouts
; timeout = 10
; connect timeout = 10
# If you get out-of-memory errors, it may mean that your client
# is trying to allocate a huge buffer for a TEXT field.
# Try setting 'text size' to a more reasonable limit
text size = 64512
# A typical Sybase server
[egServer50]
host = symachine.domain.com
port = 5000
tds version = 7.0
# A typical Microsoft server
[MSServer]
host = 192.168.1.55
port = 1433
tds version = 7.0
odbcinst.ini:
[FreeTDS]
Description = FreeTDS v7.0
Driver = /usr/local/lib/libtdsodbc.so
UsageCount = 1
odbc.ini:
[MSSQL]
Driver = FreeTDS
Description = MSSQL Server Connection
TDS_Version = 7.0
Trace = No
Server = MSServer
Port = 1433
Database = MyDatabase
Username = DOMAIN\MyUsername
Password = MyPassword
I can make connection with isql command when I specify username and password:
# isql -v MSSQL "DOMAIN\MyUsername" MyPassword
But if I omit username and password isql generate error:
[S1000][unixODBC][FreeTDS][SQL Server]Unable to connect to data source
[01000][unixODBC][FreeTDS][SQL Server]Adaptive Server connection failed
I suspect that my username make problems because I have to use DOMAIN name followed by backslash before username when I connect to SQL Server 2005.
UPDATE:
I succesfully made connection in PHP and now I can run queries. I added this line on top of my script: putenv("FREETDSCONF=/usr/local/etc/freetds.conf")
Why is this necessary?

Unable to load Mongodb Driver

I have a Nnginx -FPM php server running on Ubuntu.
I am trying to make the MongoDB Driver for PHP work but some how it never shows in my phpinfo() and every time I run a test script i get Fatal error: Class 'Mongo' not found
The actual MongoDB server is not installed in that server given that I will be connecting to another server.
What am I missing that it doesnt work?
I followed this straight forward steps
1) pecl search mongo
Show the latest 1.4.3 (stable) verion
2) sudo pecl install mongo
3) vim /etc/php5/fpm/php.ini
and at the end of the [dba] tag i add
[Mongo]
extension=mongo.so
4)
service nginx restart
service php5-fpm restart
Check to see if you have mongodb.ini in /etc/php5/conf.d/ The contents should look something like:
extension=mongo.so
mongo.auto_reconnect = true
mongo.allow_persistent = On
mongo.max_persistent = -1
mongo.max_connections = -1
;mongo.default_host = www.example.com
mongo.default_port = 42
mongo.chunk_size = 1024
mongo.cmd = "$"

MongoDB db.serverStatus() gives error when running using tunnel that is targeted to api.cloudfoundry.com

Following is the console session...
C:\Users\xxx>vmc tunnel myMongoDB
Getting tunnel connection info: OK
Service connection info:
username : uuuu
password : pppp
name : db
url : mongodb://uuuu:pppp#172.30.xx.xx:25200/db
Starting tunnel to myMongoDB on port 10000.
1: none
2: mongo
3: mongodump
4: mongorestore
Which client would you like to start?: 2
Launching 'mongo --host localhost --port 10000 -u uuuu -p pppp db'
MongoDB shell version: 2.0.6
connecting to: localhost:10000/db
> db.serverStatus()
{ "errmsg" : "need to login", "ok" : 0 }
>
Which credentials should I use to login (assuming should use db.auth) to get rid of the error "{ "errmsg" : "need to login", "ok" : 0 }".
When I run the same in micro CF on my machine it works ok and gives me the expected output.
P.S. I'm trying this to get to know the current connections on my application, written in node.js. Trying to debug some issues with connections to the DB. If there is any other alternative that I can use please suggest that as well.
this should work! Not sure why your tunnel isn't connecting, my immediate suggestion is to try another instance of MongoDB and see if the same error occurs.
If you are trying to inspect the bound services on you node.js app you should be able to inspect them in the VCAP_SERVICES environment variable. For example;
var http = require('http');
var util = require('util');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(util.inspect(process.env.VCAP_SERVICES));
res.write("\n\n************\n\n");
res.end(util.inspect(req.headers));
}).listen(3000);
This code is currently running at http://node-headers.cloudfoundry.com/ to serve as an example. However, mongodb connections for node.js applications should automatically configure to the bound service. If this does not work for you, then please do let me know.

I've installed MongoDB on a server. What now?

I'm interesting in playing around with NoSQL and particularly MongoDB. To this end, I've installed MongoDB on an external Linux box by SSHing into the server and running the following command:
sudo pecl install mongo
Mongo seems to have installed correctly and there's now a 'Mongo' section if I run phpinfo().
But what now? I seem to be having trouble going from here to using it in production. The problem being, I don't think the MongoDB service is running, and I haven't configured any MongoDB users because I'm not sure how to. As a result, the following test script fails:
<?php
// connect
$m = new Mongo();
// select a database
$db = $m->comedy;
// select a collection (analogous to a relational database's table)
$collection = $db->cartoons;
// add a record
$obj = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );
$collection->insert($obj);
// add another record, with a different "shape"
$obj = array( "title" => "XKCD", "online" => true );
$collection->insert($obj);
// find everything in the collection
$cursor = $collection->find();
// iterate through the results
foreach ($cursor as $obj) {
echo $obj["title"] . "\n";
}
?>
As I get the following error message:
Fatal error: Uncaught exception 'MongoConnectionException' with message 'connecting to failed: Transport endpoint is not connected' in /home/[username]/public_html/mongodbtest/index.php:4 Stack trace: #0 /home/[username]/public_html/mongodbtest/index.php(4): Mongo->__construct() #1 {main} thrown in /home/woohoobi/public_html/mongodbtest/index.php on line 4
How can I get from here to using MongoDB?
You never actually installed MongoDB, but rather the PHP extension that lets you connect to a MongoDB instance. Install MongoDB by downloading it and installing it on your server, and then connect to it from your PHP script.