Azure / azure-iot-sdk-node

A Node.js SDK for connecting devices to Microsoft Azure IoT services
https://docs.microsoft.com/en-us/azure/iot-hub/
Other
262 stars 227 forks source link

UnauthorizedError: mqtt.js returned Failure on first connection (Not authorized): connect ECONNREFUSED 172.18.0.3:8883 error #1088

Closed radeshsharma closed 2 years ago

radeshsharma commented 2 years ago

Hello Azure Iot Sdk Team, I'm beginner in the azure iot edge. Basically when I'm runing a sample module based on node.js sdk my module showing a error in logs UnauthorizedError: mqtt.js returned Failure on first connection (Not authorized): connect ECONNREFUSED 172.18.0.3:8883 error

Steps I follow :

  1. I created a iot edge device in hub.
  2. Created the virtual machine using virtualbox in windows system with ubuntu (20.04 as well as 18.04 both tested).
  3. I followed the tutorial to setup iotedge runtime in ubuntu .
  4. After the setup I go the Hub Click on module and then on + button then marketplace and added the Simulated Temperature Sensor module to test things for first time, everything going perfect till here.
  5. Now decided to follow up new tutorial to get started with custom module for iot edge in Node.js .
  6. Now by following the above tutorial created a custom module and pushed successfully and deployed it for my edge device.
  7. Now suddenly I get the error:

Logs of Custom Module which I created

/app/app.js:19
        throw err;
        ^

UnauthorizedError: mqtt.js returned Failure on first connection (Not authorized): connect ECONNREFUSED 172.18.0.3:8883 error
IoT Hub module client initialized
Receiving message status: MessageCompleted
Receiving message status: MessageCompleted
Receiving message status: MessageCompleted
Receiving message status: MessageCompleted
Receiving message status: MessageCompleted
Receiving message status: MessageCompleted
Receiving message status: MessageCompleted
Receiving message status: MessageCompleted
Receiving message status: MessageCompleted
Machine temperature 25.085859883965863 exceeds threshold 25
Sending received message status: MessageEnqueued
Receiving message status: MessageCompleted
Machine temperature 25.491465912429373 exceeds threshold 25
Sending received message status: MessageEnqueued
Receiving message status: MessageCompleted

and so on..

Logs for Simulated Temperature Sensor

01/18/2022 21:36:37> Sending message: 252, Body: [{"machine":{"temperature":105.46291468104485,"pressure":10.622357368726629},"ambient":{"temperature":20.917699348841655,"humidity":25},"timeCreated":"2022-01-18T21:36:37.8520744Z"}]
    01/18/2022 21:36:42> Sending message: 253, Body: [{"machine":{"temperature":105.38133829337609,"pressure":10.613063856207402},"ambient":{"temperature":20.82922277009544,"humidity":25},"timeCreated":"2022-01-18T21:36:42.861158Z"}]
    01/18/2022 21:36:47> Sending message: 254, Body: [{"machine":{"temperature":105.3538365246979,"pressure":10.609930743320014},"ambient":{"temperature":20.682453360493508,"humidity":26},"timeCreated":"2022-01-18T21:36:47.8816814Z"}]
    01/18/2022 21:36:52> Sending message: 255, Body: [{"machine":{"temperature":105.82241240834,"pressure":10.663312806013417},"ambient":{"temperature":21.113297815254562,"humidity":24},"timeCreated":"2022-01-18T21:36:52.8938155Z"}]
    01/18/2022 21:36:57> Sending message: 256, Body: [{"machine":{"temperature":106.23350977373009,"pressure":10.710146683083174},"ambient":{"temperature":21.25707483000917,"humidity":26},"timeCreated":"2022-01-18T21:36:57.9049516Z"}]
    01/18/2022 21:37:02> Sending message: 257, Body: [{"machine":{"temperature":105.94725339531307,"pressure":10.6775351969344},"ambient":{"temperature":21.074938539217662,"humidity":25},"timeCreated":"2022-01-18T21:37:02.91564Z"}]
    01/18/2022 21:37:07> Sending message: 258, Body: [{"machine":{"temperature":106.25028182414842,"pressure":10.71205742300425},"ambient":{"temperature":20.80197614352311,"humidity":25},"timeCreated":"2022-01-18T21:37:07.9258014Z"}]
    01/18/2022 21:37:12> Sending message: 259, Body: [{"machine":{"temperature":106.45064476199946,"pressure":10.73488358048095},"ambient":{"temperature":20.74607399070918,"humidity":26},"timeCreated":"2022-01-18T21:37:12.939921Z"}]

Logs for Edge Agent

<6> 2022-01-18 21:51:33.511 +00:00 [INF] - Received direct method call - ping
<6> 2022-01-18 21:51:33.513 +00:00 [INF] - Received request ping with payload
<6> 2022-01-18 21:51:33.513 +00:00 [INF] - Successfully handled request ping
<6> 2022-01-18 21:51:34.020 +00:00 [INF] - Received direct method call - GetModuleLogs
<6> 2022-01-18 21:51:34.021 +00:00 [INF] - Received request GetModuleLogs with payload
<6> 2022-01-18 21:51:34.021 +00:00 [INF] - Processing request to get logs for {"schemaVersion":"1.0","items":{"id":"\\bSimulatedTemperatureSensor\\b","filter":{"tail":1500,"since":"15m","until":null,"loglevel":null,"regex":""}},"encoding":1,"contentType":1}
<6> 2022-01-18 21:51:34.058 +00:00 [INF] - Initiating streaming logs for SimulatedTemperatureSensor
<6> 2022-01-18 21:51:34.175 +00:00 [INF] - Received 8428 bytes of logs for SimulatedTemperatureSensor
<6> 2022-01-18 21:51:34.176 +00:00 [INF] - Successfully handled request GetModuleLogs
<6> 2022-01-18 21:53:02.880 +00:00 [INF] - Received direct method call - ping
<6> 2022-01-18 21:53:02.882 +00:00 [INF] - Received request ping with payload
<6> 2022-01-18 21:53:02.882 +00:00 [INF] - Successfully handled request ping
<6> 2022-01-18 21:53:03.359 +00:00 [INF] - Received direct method call - GetModuleLogs
<6> 2022-01-18 21:53:03.360 +00:00 [INF] - Received request GetModuleLogs with payload
<6> 2022-01-18 21:53:03.361 +00:00 [INF] - Processing request to get logs for {"schemaVersion":"1.0","items":{"id":"\\bedgeAgent\\b","filter":{"tail":1500,"since":"15m","until":null,"loglevel":null,"regex":""}},"encoding":1,"contentType":1}

Logs for Edge Hub

<6> 2022-01-18 21:40:13.806 +00:00 [INF] - Entering periodic task to reauthenticate connected clients
<6> 2022-01-18 21:45:04.824 +00:00 [INF] - Started task to cleanup processed and stale messages for endpoint radesh_iot/Radsample/input1
<6> 2022-01-18 21:45:05.149 +00:00 [INF] - Cleaned up 353 messages from queue for endpoint radesh_iot/Radsample/input1 and 353 messages from message store.
<6> 2022-01-18 21:45:05.149 +00:00 [INF] - Started task to cleanup processed and stale messages for endpoint iothub
<6> 2022-01-18 21:45:05.403 +00:00 [INF] - Cleaned up 345 messages from queue for endpoint iothub and 345 messages from message store.
<6> 2022-01-18 21:45:13.804 +00:00 [INF] - Entering periodic task to reauthenticate connected clients
<6> 2022-01-18 21:50:13.807 +00:00 [INF] - Entering periodic task to reauthenticate connected clients

Sample Module app.js

'use strict';

var Transport = require('azure-iot-device-mqtt').Mqtt;
var Client = require('azure-iot-device').ModuleClient;
var Message = require('azure-iot-device').Message;
var temperatureThreshold = 25;

Client.fromEnvironment(Transport, function (err, client) {
  if (err) {
    throw err;
  } else {
    client.on('error', function (err) {
      throw err;
    });

    // connect to the Edge instance
    client.open(function (err) {
      if (err) {
        throw err;
      } else {
        console.log('IoT Hub module client initialized');

        // Act on input messages to the module.
        client.on('inputMessage', function (inputName, msg) {
          filterMessage(client, inputName, msg);
          });

          client.getTwin(function (err, twin) {
            if (err) {
                console.error('Error getting twin: ' + err.message);
            } else {
                twin.on('properties.desired', function(delta) {
                    if (delta.TemperatureThreshold) {
                        temperatureThreshold = delta.TemperatureThreshold;
                    }
                });
            }
        });
      }
    });
  }
});

// This function filters out messages that report temperatures below the temperature threshold.
// It also adds the MessageType property to the message with the value set to Alert.
function filterMessage(client, inputName, msg) {
  client.complete(msg, printResultFor('Receiving message'));
  if (inputName === 'input1') {
      var message = msg.getBytes().toString('utf8');
      var messageBody = JSON.parse(message);
      if (messageBody && messageBody.machine && messageBody.machine.temperature && messageBody.machine.temperature > temperatureThreshold) {
          console.log(`Machine temperature ${messageBody.machine.temperature} exceeds threshold ${temperatureThreshold}`);
          var outputMsg = new Message(message);
          outputMsg.properties.add('MessageType', 'Alert');
          client.sendOutputEvent('output1', outputMsg, printResultFor('Sending received message'));
      }
  }
}

// Helper function to print results in the console
function printResultFor(op) {
  return function printResult(err, res) {
    if (err) {
      console.log(op + ' error: ' + err.toString());
    }
    if (res) {
      console.log(op + ' status: ' + res.constructor.name);
    }
  };
}

Iot edge check Result

Configuration checks (aziot-identity-service)
---------------------------------------------
√ keyd configuration is well-formed - OK
√ certd configuration is well-formed - OK
√ tpmd configuration is well-formed - OK
√ identityd configuration is well-formed - OK
√ daemon configurations up-to-date with config.toml - OK
√ identityd config toml file specifies a valid hostname - OK
√ aziot-identity-service package is up-to-date - OK
√ host time is close to reference time - OK
√ preloaded certificates are valid - OK
√ keyd is running - OK
√ certd is running - OK
√ identityd is running - OK
√ read all preloaded certificates from the Certificates Service - OK
√ read all preloaded key pairs from the Keys Service - OK
√ ensure all preloaded certificates match preloaded private keys with the same ID - OK

Connectivity checks (aziot-identity-service)
--------------------------------------------
√ host can connect to and perform TLS handshake with iothub AMQP port - OK
√ host can connect to and perform TLS handshake with iothub HTTPS / WebSockets port - OK
√ host can connect to and perform TLS handshake with iothub MQTT port - OK

Configuration checks
--------------------
√ aziot-edged configuration is well-formed - OK
√ configuration up-to-date with config.toml - OK
√ container engine is installed and functional - OK
√ configuration has correct URIs for daemon mgmt endpoint - OK
√ aziot-edge package is up-to-date - OK
√ container time is close to host time - OK
‼ DNS server - Warning
    Container engine is not configured with DNS server setting, which may impact connectivity to IoT Hub.
    Please see https://aka.ms/iotedge-prod-checklist-dns for best practices.
    You can ignore this warning if you are setting DNS server per module in the Edge deployment.
‼ production readiness: container engine - Warning
    Device is not using a production-supported container engine (moby-engine).
    Please see https://aka.ms/iotedge-prod-checklist-moby for details.
‼ production readiness: logs policy - Warning
    Container engine is not configured to rotate module logs which may cause it run out of disk space.
    Please see https://aka.ms/iotedge-prod-checklist-logs for best practices.
    You can ignore this warning if you are setting log policy per module in the Edge deployment.
‼ production readiness: Edge Agent's storage directory is persisted on the host filesystem - Warning
    The edgeAgent module is not configured to persist its /tmp/edgeAgent directory on the host filesystem.
    Data might be lost if the module is deleted or updated.
    Please see https://aka.ms/iotedge-storage-host for best practices.
‼ production readiness: Edge Hub's storage directory is persisted on the host filesystem - Warning
    The edgeHub module is not configured to persist its /tmp/edgeHub directory on the host filesystem.
    Data might be lost if the module is deleted or updated.
    Please see https://aka.ms/iotedge-storage-host for best practices.
√ Agent image is valid and can be pulled from upstream - OK

Connectivity checks
-------------------
√ container on the default network can connect to upstream  AMQP port - OK
√ container on the default network can connect to upstream HTTPS / WebSockets port - OK
√ container on the default network can connect to upstream MQTT port - OK
√ container on the IoT Edge module network can connect to upstream AMQP port - OK
√ container on the IoT Edge module network can connect to upstream HTTPS / WebSockets port - OK
√ container on the IoT Edge module network can connect to upstream MQTT port - OK
31 check(s) succeeded.
5 check(s) raised warnings. Re-run with --verbose for more details.

I tried to find about the ip address 172.18.0.3 and I got to know that this ip address is address of edgeHub module Inside container. So, it's clear that samplemodule trying to connect with edgeHub module through mqtt and it show error for that, but still have confusion like why why error I haven't changed anything just followed the things like my team they don't have same issue.

In this sample module even I'm not trying to connect using mqtt or I'm not using mqtt still It's showing error related to mqtt. Please do help me in this to get override from this problem. Thanks in Advance.

anthonyvercolano commented 2 years ago

@radeshsharma closed as a duplicate to edge issue #6013