Check several different TCP/IP services for availability? - node.js

Let's say I have a list of hostnames and ports, not all of which are HTTP related.
var config = {
"checks": [
{
"name": "NPM",
"hostname": "npmjs.com",
"port": 80
},
{
"name": "AWS",
"hostname": "aws.amazon.com",
"port": 443
},
{
"name": "RabbitMQ",
"hostname": "merry-butterfly.rmq.cloudamqp.com",
"port": 5671
}
]
}
What is an effective way to test that each of these services can be reached? My first thoughts were to use a typical telnet-like approach, I did this:
var telnet = require('telnet-client')
config.checks.forEach(function(check) {
var connection = new telnet()
var params = {
host: check.hostname,
port: check.port,
negotiationMandatory: false
}
connection.on('connect', function() {
connection.send('GET /', {
ors: '\r\n',
waitfor: '\n'
}, function(err, data) {
console.log(err, data);
connection.end()
})
})
connection.connect(params)
results.push(result);
});
The above seems to work, but I'm actually not sure what data to send to each individual services to get back a response that suggests the service is "reachable", I don't need to auth or do any operations with the service, just check that it can be reached. Additionally it raises an exception if the DNS is unreachable:
Error: getaddrinfo ENOTFOUND merry-butterfly.rmq.cloudamqp.com/api merry-butterfly.rmq.cloudamqp.com/api:443
What would be the appropriate way to handle the errors, and async test each of the entries in the list of "checks"?

Ping the host.
https://www.npmjs.com/package/ping
For example:
var ping = require('ping');
var hosts = ['192.168.1.1', 'google.com', 'yahoo.com'];
hosts.forEach(function(host){
ping.sys.probe(host, function(isAlive){
var msg = isAlive ? 'host ' + host + ' is alive' : 'host ' + host + ' is dead';
console.log(msg);
});
});

Related

Simple-peer WebRTC Error: Ice connection failed

I can not make the Simple-Peer NPM library to connect between two computers in two different networks in Browser. If the computers are in the same local network, the browsers connect each other, but otherwise, I can not make them connect.
Both browsers return this error:
"Error: Ice connection failed.
at Peer._onIceStateChange"
at RTCPeerConnection.Peer.self._pc.oniceconnectionstatechange
The signalling looks right for me:
{ type: 'offer',
sdp: 'v=0\r\no=- 2275520429720515716 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE data\r\na=msid-semantic: WMS\r\nm=application 49523 DTLS/SCTP 5000\r\nc=IN IP4 5.12.206.160\r\na=candidate:2020300070 1 udp 2113937151 192.168.2.8 49523 typ host generation 0 network-cost 50\r\na=candidate:842163049 1 udp 1677729535 5.12.206.160 49523 typ srflx raddr 192.168.2.8 rport 49523 generation 0 network-cost 50\r\na=ice-ufrag:Ph/x\r\na=ice-pwd:csnTbzHs+dxzakEKPY8LfvBg\r\na=fingerprint:sha-256 B9:C0:9D:91:46:1B:E8:5C:83:B1:11:A7:C5:D7:64:97:A6:63:D9:12:11:0F:9A:05:8F:46:83:BC:90:38:86:9E\r\na=setup:actpass\r\na=mid:data\r\na=sctpmap:5000 webrtc-datachannel 1024\r\n' } }
{ type: 'answer',
sdp: 'v=0\r\no=- 1356997482353729498 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE data\r\na=msid-semantic: WMS\r\nm=application 56005 DTLS/SCTP 5000\r\nc=IN IP4 86.126.104.54\r\nb=AS:30\r\na=candidate:2702239670 1 udp 2113937151 192.168.1.103 56003 typ host generation 0 network-cost 50\r\na=candidate:842163049 1 udp 1677729535 86.126.104.54 56005 typ srflx raddr 192.168.1.103 rport 56003 generation 0 network-cost 50\r\na=ice-ufrag:W6zA\r\na=ice-pwd:1NhU5D47rSz83ANxlY+Tz/XI\r\na=ice-options:trickle\r\na=fingerprint:sha-256 2C:0B:78:49:F5:F0:44:6C:86:DD:27:BC:B6:7D:77:B9:B1:07:F4:2F:37:F5:24:D9:A3:54:7D:B3:A0:3C:57:C0\r\na=setup:active\r\na=mid:data\r\na=sctpmap:5000 webrtc-datachannel 1024\r\n' } }
but when the library wants to establish the connection, both browsers return the above-mentioned error.
This my code
//TUTORIAL BASED ON
// https://github.com/feross/simple-peer
var initiator = (location.hash||'') === '#1';
console.log("inititator",location.hash , initiator);
var Peer = require('simple-peer');
params = {
initiator: initiator,
trickle: false,
reconnectTimer: 100,
iceTransportPolicy: 'relay',
config: {
iceServers: [
{
urls: "stun:numb.viagenie.ca",
username: "pasaseh#ether123.net",
credential: "12345678"
},
{
urls: "turn:numb.viagenie.ca",
username: "pasaseh#ether123.net",
credential: "12345678"
}
]
}
};
if (typeof window === "undefined"){
var wrtc = require('wrtc');
params.wrtc= wrtc;
}
var p = new Peer(params);
p.on('error', function (err) { console.log('error', err) })
p.on('signal', function (data) {
console.log('SIGNAL', JSON.stringify(data));
document.querySelector('#outgoing').textContent = JSON.stringify(data)
});
document.querySelector('form').addEventListener('submit', function (ev) {
ev.preventDefault();
console.log("am apasat pe button");
p.signal(JSON.parse(document.querySelector('#incoming').value))
});
let index = Math.floor(Math.random()*100);
p.on('connect', function (data) {
console.log('CONNECT', data, p);
setInterval(function() {
if ((typeof p !== 'undefined')&& ( p !== null)) {
console.log(p);
p.send('whatever' + index + " ___ " + Math.random())
}
}, 500);
p.on("hello", function(data){
alert(data);
});
p.emit("hello",55);
})
p.on('data', function (data) {
console.log('data: ' + data)
});
module.exports = function(){
console.log("Hello World Server");
};
webrtc-internals
Any solution to this problem? Thanks
The screenshot from chrome://webrtc-internals shows that despite the TURN server credentials you use, no icecandidate with type relay is gathered. See this blog post for details.
You can check the credentials using this page
i suggest using still working ice servers when listing your ice server as below
new SimplePeer({
initiator: false,
tricle: false,
config: {
iceServers: [
{
urls: "turn:numb.viagenie.ca",
credential: "muazkh",
username: "webrtc#live.com",
},
],
},
})

StrongLoop ACL table doesn't exist

I succeed to generate all my models from my database. Then, I run the api by executing, 'node .'
I'm able to see all my web services but when I try to try out a service, there is an 500 error saying to me that There is no ACL table.
So, I open model-config.json and I saw that there were 4 models I didn't created before (User, AccessToken, ACL, RoleMapping and Role).
I would like to know if all these models has to exist in my database. And Do you know which properties I have to put in each table?
Thanks you in advance.
Error:
{
"error": {
"name": "Error",
"status": 500,
"message": "ER_NO_SUCH_TABLE: Table 'sed.ACL' doesn't exist",
"code": "ER_NO_SUCH_TABLE",
"errno": 1146,
"sqlState": "42S02",
"index": 0,
"stack": "Error: ER_NO_SUCH_TABLE: Table 'sed.ACL' doesn't exist\n [...]"
}
}
You will need to automigrate these tables yourself. See:
https://groups.google.com/forum/#!searchin/loopbackjs/automigrate$20default$20tables/loopbackjs/IiapgVVf-NQ/32yeCnNxBmIJ
https://github.com/strongloop/loopback/issues/591.
You need to migrate them yourself
Follow the basic procedure in Attaching models to data sources to change from the in-memory data source to the database you want to use.
Create server/create-lb-tables.js file with the following:
var server = require('./server');
var ds = server.dataSources.db;
var lbTables = ['User', 'AccessToken', 'ACL', 'RoleMapping', 'Role'];
ds.automigrate(lbTables, function(er) {
if (er) throw er;
console.log('Loopback tables [' - lbTables - '] created in ', ds.adapter.name);
ds.disconnect();
});
Run the script manually:
$ cd server
$ node create-lb-tables.js
For further details see loopback Documentation
var server = require('./server');
var ds = server.dataSources.db;
var lbTables = ['User', 'AccessToken', 'ACL', 'RoleMapping', 'Role'];
ds.automigrate(lbTables, function(er) {
if (er) throw er;
console.log('Loopback tables [' - lbTables - '] created in ', ds.adapter.name);
ds.disconnect();
});
Here
var ds = server.dataSources.db;
db would be your database name, which you are using in datasource.json .
database connection string:
{
"db": {
"name": "db",
"connector": "memory"
},
"inventory": {
"host": "localhost",
"port": 3306,
"url": "",
"database": "inventory",
"password": "root",
"name": "inventory",
"user": "root",
"connector": "mysql"
}
}
Here is my db name:
"database": "inventory"
Upadated code is
var server = require('./server');
var ds = server.dataSources.inventory;
var lbTables = ['User', 'AccessToken', 'ACL', 'RoleMapping', 'Role'];
ds.automigrate(lbTables, function(er) {
if (er) throw er;
console.log('Loopback tables [' - lbTables - '] created in ', ds.adapter.name);
ds.disconnect();
});
shoot this code with independent saved file in directory with node filename.js
And it works.

peerjs connection opens, but no data is received

Here's my setup
Server
var webrtcServer = new PeerServer({
port: 9000,
path: "/wrtc"
});
Peer 1 (running inside a node-webkit application)
var peer = new Peer( 'masterName', {
host: 'localhost',
port: 9000,
path: '/wrtc'
});
peer.on( 'connection', function(conn) {
conn.on( 'open', function() {
console.log( "peer connected" ); // This fires as expected
conn.send( "helo" );
});
});
Peer 2 (running inside a browser)
conn = peer.connect('masterName');
conn.on('open', function(){
console.log( "WebRTC connection open" ); // This fires as expected
});
conn.on('data', function(data) {
debugger;
console.log("data"); // This never hits
});
If I set breakpoints in peer.js, no data is being received. Nothing changes if I set the connection to reliable. Is there anything else I can try?
I ran into a similar problem and adding a STUN server solved it for me. Also have a look this discussion in the peerjs Google group
peer = new Peer(
{
host: 'localhost',
port: 9000,
debug: true,
config: { 'iceServers': [
{ 'url': 'stun:stun.l.google.com:19302' }
] }
});

Docker Websocket Attaching in NodejS

I want to connect to Docker API with Websockets, however, in any container it just gives me 403 Forbidden Error. I do not know what I am doing wrong, there is not enough documentation about it, but here is my code:
var docker = require('docker.io')({
socketPath: false,
host: "http://127.0.0.1",
port: "4500"
});
var WebSocket = require('ws');
var opts = {
"AttachStdin": true,
"AttachStdout": true,
"AttachStderr": true,
"Tty": true,
"OpenStdin": true,
"Cmd": [
"/bin/bash"
],
"Image": "ubuntu"
};
docker.containers.create(opts, function(err, result) {
if (!err) {
var containerId = result.Id;
console.log("Container", containerId, "created");
docker.containers.start(containerId, function(err, result) {
console.log(result);
var ws = new WebSocket('ws://127.0.0.1:4500/v1.7/containers/' + containerId + '/attach/ws?logs=1&stderr=1&stdout=1');
ws.on("open", function() {
console.log("ok, open");
});
ws.on("message", function(msg) {
console.log("msg", msg);
});
ws.on("error", function(msg) {
console.log("error", msg);
});
});
} else {
console.log(err);
}
});
The output it produces is:
Container ceeef5eb34acf06dad7d6fea01dd71d9b0283c63b14bc52d49585aa379ec4922 created
error [Error: unexpected server response (403)]
But I see the Docker daemon output as follows:
Local (127.0.0.1) DNS resolver found in resolv.conf and containers can't use it. Using default external servers : [8.8.8.8 8.8.4.4]
[/var/lib/docker|f99d0d11] -job create() = OK (0)
2014/04/16 23:04:09 POST http://127.0.0.1:4500/v1.7/containers/ceeef5eb34acf06dad7d6fea01dd71d9b0283c63b14bc52d49585aa379ec4922/start
[error] common.go:41 Error parsing media type: error: mime: no media type
[/var/lib/docker|f99d0d11] +job start(ceeef5eb34acf06dad7d6fea01dd71d9b0283c63b14bc52d49585aa379ec4922)
[/var/lib/docker|f99d0d11] +job allocate_interface(ceeef5eb34acf06dad7d6fea01dd71d9b0283c63b14bc52d49585aa379ec4922)
[/var/lib/docker|f99d0d11] -job allocate_interface(ceeef5eb34acf06dad7d6fea01dd71d9b0283c63b14bc52d49585aa379ec4922) = OK (0)
[/var/lib/docker|f99d0d11] -job start(ceeef5eb34acf06dad7d6fea01dd71d9b0283c63b14bc52d49585aa379ec4922) = OK (0)
2014/04/16 23:04:09 GET /v1.7/containers/ceeef5eb34acf06dad7d6fea01dd71d9b0283c63b14bc52d49585aa379ec4922/attach/ws
[/var/lib/docker|f99d0d11] +job inspect(ceeef5eb34acf06dad7d6fea01dd71d9b0283c63b14bc52d49585aa379ec4922, container)
[/var/lib/docker|f99d0d11] -job inspect(ceeef5eb34acf06dad7d6fea01dd71d9b0283c63b14bc52d49585aa379ec4922, container) = OK (0)
As it can be seen requests comes to Daemon but there is no indication why it gives a 403 Forbidden error.
It seems that I needed to change 127.0.0.1 to localhost and it magically worked.

How to get the exact IP address of the Restify server on listen?

Consider the following code for rest API node server.
var restify = require('restify');
var server = restify.createServer();
server.get('/echo/:name', function (req, res, next) {
res.send({name: req.params.name});
next();
});
server.listen(8080, function () {
console.log('%s listening at %s', server.name, server.url);
});
Running up that server with node:
$ node echo.js
restify listening at http://0.0.0.0:8080
It shows 0.0.0.0 which is wrong.
Can anyone the me how to console log the exact IP of the server when its turned on?
Thanks
Update:
On executing the following code I am getting the below mentioned output, which is again makes difficult, which IP to pick?
rest_server.listen(config.appPort, function () {
var adrs = require('os').networkInterfaces();
console.log(adrs);
console.log('%s listening at %s', rest_server.name, rest_server.url);
});
Output:
{ 'Local Area Connection': [ { address: '192.168.3.60', family: 'IPv4', internal
: false } ],
'Loopback Pseudo-Interface 1':
[ { address: '::1', family: 'IPv6', internal: true },
{ address: '127.0.0.1', family: 'IPv4', internal: true } ],
'isatap.TEST.ORG':
[ { address: 'fe80::5efe:c0a8:33c',
family: 'IPv6',
internal: false } ] }
restify listening at http://0.0.0.0:8080
You can set the real address to the listen method, see
http://mcavage.github.io/node-restify/#Server-API and http://nodejs.org/docs/latest/api/net.html#net_server_listen_path_callback
server.address() may return the address the server was bound to:
http://nodejs.org/docs/latest/api/net.html#net_server_address
Had the Same issue and figured out the problem, basically you can pass another parameter to the .listen() function and that should be your server IP address
server.listen(port, [host], [backlog], [callback])
server.listen(port, YOUR IP ADDRESS, function(){ });
for you to get your server ip address just do "traceroute www.WEBSITE_URL.com" in the terminal.
let me know if you still have an issue.
thanks
Mahdi
Got some solution, which is as follows.
Any improvements on the same is always welcomed.
var osDetails = require('os');
function getDynamicIP(calbck) {
var ip;
try {
var adrs = osDetails.networkInterfaces();
for (key in adrs) {
if (adrs.hasOwnProperty(key)) {
if (adrs[key][0].internal === false && adrs[key][0].family === 'IPv4') {
ip = adrs[key][0].address;
break;
}
}
}
}
catch (e) {
return calbck(e, null);
}
return calbck(null, ip);
}

Resources