Connect from IBM Cloud Functions to MySQL on local host - mysql

I want to connect to my MySQL database on a local host which is not in IBM Cloud using IBM Cloud Functions. I am unable to do that.
I have written Node.js code in IBM Cloud Function.
var mysql = require('mysql');
//,cn="server=localhost;port=3306;database=chatbot;uid=root;password=oracle1#;";
var connection = mysql.createConnection({
server: 'localhost',
user: 'root',
port:3306,
password: 'my_password'
});
function main(params) {
try {
//var connection=mysql.createConnection(cn);
connection.connect();
//var s = JSON.stringify(params['user_input']);
//var v = s.substring(1,11);
//var check= conn.querySync("select count(distinct PHONE_NUMBER) where PHONE_NUMBER='"+v+"'");
var rows = connection.query(
"select * from chatbot.customer_data");
//console.log(rows);
connection.end();
return{message:"TRUE:"+rows[0]['PHONE']};
}
catch (e) {
return { message:"error" };
//return{message:"FALSE"};
}
}
Expected result:
TRUE:RESULTSET
Actual Result:
error

This is a pure network issue. The Cloud function running in IBM Cloud does not have a network route that directs to your local host. If you did want that connectivity then you would need to expose the address of your local host using something like a secure gateway service.

var sql = require('mysql');
var connection = sql.createConnection({
host: 'host name',
user: 'user name',
password: 'passwprd',
database: 'database_name'
});
function main(params) {
try {
connection.connect();
var sql="select * from table _name";
connection.query(sql,function(err,result){
return{message:result};
})
//console.log(rows);
connection.end();
}
catch (e) {
return { message:"error" };
//return{message:"FALSE"};
}
}

Related

CloudFunction access to MySQL hosted on Computer Engine Virtual Machine

My CloudFunction needs to access a MariaDB server hosted on a virtual machine from Computer Engine.
Accessing MariaDB by the public IP is working. But I want to access it from the private IP with VPC serverless connector. I don't want my database open on internet.
My VPC is configured with 10.10.0.0/28 adress range.
Screenshot1
My VM have 2 network interfaces :
nic0 on default network : 10.132.0.12 and an external IP (34.XX.XX.XX)
nic1 on vpc-subnet : 10.10.0.7
Screenshot2
CloudFunction is configured with the VPC connector.
Screenshot3
My CloudFunction code :
const mysql = require('mysql');
const ping = require('ping');
const config = require('./config.json');
exports.test = async function(event, context){
//Decode data if is from pubsub call
if(typeof event.data == "string"){
var buff = new Buffer(event.data, 'base64');
var data = JSON.parse(buff.toString('ascii'));
}else{
var data = event.data;
}
const db = mysql.createConnection({
host: data.host,
user: config.db.username,
password: config.db.password,
database: config.db.database
});
ping.sys.probe(data.host, function(isAlive){
var msg = isAlive ? 'host ' + data.host + ' is alive' : 'host ' + data.host + ' is dead';
console.log(msg);
});
db.connect(function(err) {
if (err) throw err;
console.log("Connected to MySQL");
db.query("Select * from Sites limit 1", function (err, result) {
if (err) throw err;
console.log(result);
});
});
}
I tested 10.10.0.7 but I doesn't work.

non-Google MySQL database connection with firebase cloud function

When i try to connect to my MySQL, server sends me an error Error: connect ETIMEDOUT
Here is sample code
const mysql = require('mysql');
const mysqlConfig = {
connectionLimit: 1,
host: "remote_host_ip",
user: "server_user",
password: "server_pass",
database: "server_db",
port: 3306
};
mysql.createConnection(mysqlConfig).connect(function (err) {
if (!err) {
console.log("Database is connected");
} else {
console.log("Database is not connected " + err);
}
});
I am on firebase blaze(pay as you go) plan.
I know the question title already states it, but you are not using GCP Cloud SQL, right?
In that case, there's a great possibility of your MySQL server is not reachable from Cloud Functions. Are you sure network connectivity is OK?
Besides, even in Cloud Functions, it's a good idea to use connection pools. Consider using it, it will be something like that:
var config = {
user: 'root',
password: 'akdaskdasdaE',
database: 'database1'
}
config.connectionLimit = 10
config.multipleStatements = true
// needed in GCP Cloud SQL, but it seems it's not your case
// config.socketPath = `/cloudsql/__INSTANCE_CONNECTION_NAME__`
var connectionPool = mysql.createPool(config)
connectionPool.on('connection', () => {
console.log(`[connectionPool] new connection opened`)
})
// then you use connectionPool.getConnection(..)

AWS Lambda and RDS working example (need it to work with Sequelize)

Here's a working example of AWS Lambda and MySQL, but I'd like it to work with Sequelize. How do I initialize Sequelize to work with AWS Lambda? I have the authenticated IAM role working too.
https://dzone.com/articles/passwordless-database-authentication-for-aws-lambd
'use strict';
const mysql = require('mysql2');
const AWS = require('aws-sdk');
// TODO use the details of your database connection
const region = 'eu-west-1';
const dbPort = 3306;
const dbUsername = 'lambda'; // the name of the database user you created in step 2
const dbName = 'lambda_test'; // the name of the database your database user is granted access to
const dbEndpoint = 'lambdatest-cluster-1.cluster-c8o7oze6xoxs.eu-west-1.rds.amazonaws.com';
module.exports.handler = (event, context, cb) => {
var signer = new AWS.RDS.Signer();
signer.getAuthToken({ // uses the IAM role access keys to create an authentication token
region: region,
hostname: dbEndpoint,
port: dbPort,
username: dbUsername
}, function(err, token) {
if (err) {
console.log(`could not get auth token: ${err}`);
cb(err);
} else {
var connection = mysql.createConnection({
host: dbEndpoint,
port: dbPort,
user: dbUsername,
password: token,
database: dbName,
ssl: 'Amazon RDS',
authSwitchHandler: function (data, cb) { // modifies the authentication handler
if (data.pluginName === 'mysql_clear_password') { // authentication token is sent in clear text but connection uses SSL encryption
cb(null, Buffer.from(token + '\0'));
}
}
});
connection.connect();
// TODO replace with your SQL query
connection.query('SELECT * FROM lambda_test.test', function (err, results, fields) {
connection.end();
if (err) {
console.log(`could not execute query: ${err}`);
cb(err);
} else {
cb(undefined, results);
}
});
}
});
};
Instead of using mysql.createConnection() and use your RDS Signer token:
var sequelize = require('sequelize')
const Sequelize = new sequelize(
process.env.database_name,
process.env.databse_user,
token,
{
dialect: 'mysql',
dialectOptions: {
ssl: 'Amazon RDS',
authPlugins: { // authSwitchHandler is deprecated
mysql_clear_password: () => () => {
return token
}
}
},
host: process.env.db_proxy_endpoint,
port: process.env.db_port,
pool: {
min: 0, //default
max: 5, // default
idle: 3600000
},
define: {
charset: 'utf8mb4'
}
}
// then return your models (defined in separate files usually)
await Sequelize.authenticate() // this just does a SELECT 1+1 as result;
await Sequelize.sync() // DO NOT use this in production, this tries to create tables defined by your models. Consider using sequelize migrations instead of using sync()
Also it's a good idea to keep your database connection parameters in a config file so no one can see them. (process.env)
We are working with Sequelize and Lambda, but you will need to reserve more resources, in our case we need at least 1GB to run a lambda with Sequelize. Without it, just with mysql2 it runs just with 128MB.
But if you really wanna use Sequelize just replace your createConnection for something like what you will find in sequelize doc
Probably you will use the context.callbackWaitsForEmptyEventLoop=true because you may have some issues when you call the callback function and you get nothing because your Event Loop probably will never be empty.

Error connecting to MySQL from Node-JS server

I am learning to develop server on node-js and have developed a basic get function which retrieves data from MySQL DB hosted on a ubuntu server at digitalocean.
Here's my code:
const express = require('express')
const app = express()
const mysql = require('mysql')
const Client = require('ssh2').Client;
const ssh = new Client();
const db = new Promise(function(resolve, reject){
ssh.on('ready', function() {
ssh.forwardOut(
// source address, this can usually be any valid address
'localhost',
// source port, this can be any valid port number
3333,
// destination address (localhost here refers to the SSH server)
'xxx.xxx.xxx.xxx',
// destination port
22,
function (err, stream) {
if (err) throw err; // SSH error: can also send error in promise ex.
reject(err)
// use `sql` connection as usual
connection = mysql.createConnection({
host : '127.0.0.1',
user : 'user',
password : 'pass',
database: 'mysql',
stream: stream
});
// send connection back in variable depending on success or not
connection.connect(function(err){
if (!err) {
resolve(connection)
} else {
reject(err)
}
});
});
}).connect({
host: 'xxx.xxx.xxx.xxx', //IP address where DB is hosted
port: 22, //Port refering to the IP
username: 'user', //username to loginto the host
password: 'pass' //password to log into host
});
});
//Retrieve route
app.get('/users', (req, res) => {
//console.log("Fetching user with id: " + req.params.id)
const queryString = "SELECT * FROM user"
connection.query(queryString, (err, rows, fields) => {
if(err){
console.log("Failed to query " + err)
res.sendStatus(500)
return
}
console.log("Fetch Succesful")
res.json(rows)
})
})
app.listen(3000, () => {
console.log("Server is up and listerning on port 3000")
})
When I run this code on my local machine it is able to connect to external DB and fetch the data. I have created another server at digitalocean and hosted the same code. However upon running it I get error at connection stating: UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:3306
I tried various solutions available on the platform but could not suceed.
I have written the code accoring to the documentation but still clueless what's causing the error.
Thank You.

Cannot connect to mysql using Node js

I am trying to connect to mysql but I am getting the following error :
"Error: ER_ACCESS_DENIED_ERROR: Access denied for user ' root'#'localhost' (using password: YES)"
But when I connect using mysql command line client I am able to connect to mysql.
Here is my config.js file where I have defined the connectivity settings :
//config.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
port : '3306',
user : ' root',
password : 'root',
database : 'world'
});
module.exports = connection;
I am trying to connect to the db in this file :
// userController.js
var jwt = require('jwt-simple');
var connection = require("../config.js");
var auth = {
getAll: function(req, res) {
console.log("in user comtroller");
console.log(connection);
connection.connect(function(err) {
// connected! (unless `err` is set)
if(err){
console.log("Failed to connect to mysql. Error : "+err);
}
else{
console.log("connection Successful..!!");
}
});
res.send("going good");
}
}
module.exports = auth;