Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES_NEXT_RELEASE
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
IOTA

- Fix: Improve error reporting for HTTP commands when delivery fails or the endpoint returns an unexpected response. The IoT Agent still returns HTTP 400. (#1016)
- Add: unify iotagent-node-lib code into this codebase, under the iotagent-node-lib/ folder. The library is no longer consumed as an external dependency and from now on it shares version with iotagent-json (#922)
- Fix: MQTT binding scheduled a reconnection after being stopped (#928)
- Fix: health check state from a previous activation was reported until the first new check finished (#928)
Expand Down
40 changes: 29 additions & 11 deletions docs/usermanual.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,9 @@ the NGSI entity. E.g.:
```

The attribute names in the payload can be mapped to different attribute names in the entity, by using alias in the
device provisioning (see the [Provisioning API](https://github.com/telefonicaid/iotagent-json/blob/master/iotagent-node-lib/doc/api.md#api-routes) for
details).
device provisioning (see the
[Provisioning API](https://github.com/telefonicaid/iotagent-json/blob/master/iotagent-node-lib/doc/api.md#api-routes)
for details).

A device can report new measures to the IoT Platform using an HTTP POST request to the `/iot/json` path with the
following query parameters:
Expand Down Expand Up @@ -119,7 +120,8 @@ It is possible to report as a measure a NGSI-v2 or NGSI-LD payload when related
attributes.

Note that the entity ID and type in the measure are also include as attributes `measure_id` and `measure_type` as
described [here](https://github.com/telefonicaid/iotagent-json/blob/master/iotagent-node-lib/doc/api.md#special-measures-and-attributes-names)
described
[here](https://github.com/telefonicaid/iotagent-json/blob/master/iotagent-node-lib/doc/api.md#special-measures-and-attributes-names)
(both using attribute type `Text`). The ID and type of the entity updated at Context Broker is taken from device/group
configuration or provision,

Expand Down Expand Up @@ -462,8 +464,8 @@ MQTT devices commands are always push. For HTTP Devices commands to be push they
commands. Otherwise the command will be poll. When using the HTTP transport, the command handling have two flavours:

- **Push commands**: The request payload format will be a plain JSON, as described in the "Payload" section. The
device will reply with a 200OK response containing the result of the command in the JSON result format. Example of
the HTTP request sent by IOTA in the case of push command:
device endpoint should reply with HTTP `200 OK` or `201 Created` and a JSON command result. Example of the HTTP
request sent by IOTA in the case of push command:

```
POST http://[DEVICE_IP]:[PORT]
Expand All @@ -484,6 +486,15 @@ commands. Otherwise the command will be poll. When using the HTTP transport, the
}
```

If the request fails or the endpoint returns an unexpected status or invalid JSON, the IoT Agent returns HTTP
`400 Bad Request` with `HTTP_COMMAND_RESPONSE_ERROR`. The error description includes the command name, the device
ID, the endpoint's HTTP status (if a response was received), and the reason for the failure. For example, an
endpoint that returns HTTP `200 OK` with plain text instead of JSON produces this description:

```text
Command [ping] failed for device [test125]: endpoint returned HTTP 200; invalid JSON response
```

- **Polling commands**: These commands are meant to be used on those cases where the device can't be online the whole
time waiting for commands. In this case, the IoTAgents must store the received commands, offering a way for the
device to retrieve the pending commands upon connection. Whenever the device is ready, it itself retrieves the
Expand Down Expand Up @@ -1025,7 +1036,8 @@ module.exports = {

The customsubstr transformation can then be used inside JEXL expressions.

In the case of error in some tranformation, it is logged in traces, but IOTA JSON starts and works as expected. For instance:
In the case of error in some tranformation, it is logged in traces, but IOTA JSON starts and works as expected. For
instance:

```
extraJexlTransformations = {
Expand All @@ -1035,19 +1047,25 @@ extraJexlTransformations = {
badTransform3: null,
badTransform4: [],
badTransform5: "function (a,b) { return a }"

};

module.exports = extraJexlTransformations;
```

will procude this log at startup

> time=2026-02-03T09:14:27.302Z | lvl=WARN| corr=6350789e-522f-4886-a80b-b402fd0711b3 | trans=6350789e-522f-4886-a80b-b402fd0711b3 | op=IoTAgentNGSI.JEXL | from=n/a | srv=n/a | subsrv=n/a | msg=badTransform1,badTransform2,badTransform3,badTransform4,badTransform5 must be a function | comp=IoTAgent
> time=2026-02-03T09:14:27.302Z | lvl=WARN| corr=6350789e-522f-4886-a80b-b402fd0711b3 |
> trans=6350789e-522f-4886-a80b-b402fd0711b3 | op=IoTAgentNGSI.JEXL | from=n/a | srv=n/a | subsrv=n/a |
> msg=badTransform1,badTransform2,badTransform3,badTransform4,badTransform5 must be a function | comp=IoTAgent

In the case of severe error with the file (i.e. a syntax error in the JavaScript code or not a JavaScript file at all) it is also logged in traces, but IOTA JSON starts and works as expected. For instance:
In the case of severe error with the file (i.e. a syntax error in the JavaScript code or not a JavaScript file at all)
it is also logged in traces, but IOTA JSON starts and works as expected. For instance:

> time=2026-02-03T09:45:55.515Z | lvl=ERROR | corr=bfbd22cb-637a-4825-9eba-81a658101b42 | trans=bfbd22cb-637a-4825-9eba-81a658101b42 | op=IoTAgentNGSI.NGSIService | from=n/a | srv=n/a | subsrv=n/a | msg=/opt/iotagent-json/customJexl.java - Failed to load extra JEXL transformations: Unexpected token '(' | comp=IoTAgent
> time=2026-02-03T09:45:55.515Z | lvl=ERROR | corr=bfbd22cb-637a-4825-9eba-81a658101b42 |
> trans=bfbd22cb-637a-4825-9eba-81a658101b42 | op=IoTAgentNGSI.NGSIService | from=n/a | srv=n/a | subsrv=n/a |
> msg=/opt/iotagent-json/customJexl.java - Failed to load extra JEXL transformations: Unexpected token '(' |
> comp=IoTAgent

## Development documentation

Expand Down
2 changes: 1 addition & 1 deletion iotagent-node-lib/lib/request-shim.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ function request(options, callback) {
})
.catch((error) => {
logger.debug(context, 'Error: %s', JSON.stringify(util.inspect(error), null, 4));
return callback(error);
return callback(error, error.response, error.response?.body);
});
}

Expand Down
93 changes: 93 additions & 0 deletions iotagent-node-lib/test/unit/general/request-shim_test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* Copyright 2016 Telefonica Investigación y Desarrollo, S.A.U
*
* This file is part of fiware-iotagent-lib
*
* fiware-iotagent-lib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* fiware-iotagent-lib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with fiware-iotagent-lib.
* If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License
* please contact with::[contacto@tid.es]
*
*
*
*/

const nock = require('nock');

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

License header missing?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done a89307a

const should = require('should');
const request = require('../../../lib/request-shim');

describe('HTTP request adapter responses', function () {
const options = {
url: 'https://command.example.test/nada',
method: 'POST',
body: '{"ping":"RRRR"}',
headers: { 'content-type': 'application/json' }
};

afterEach(function () {
nock.cleanAll();
});

[200, 201].forEach(function (status) {
it('should preserve the HTTP ' + status + ' response when JSON parsing fails', function (done) {
const endpoint = nock('https://command.example.test')
.post('/nada', { ping: 'RRRR' })
.reply(status, 'Hey ya! Greetings!', { 'Content-Type': 'text/plain' });

request(options, function (error, response, body) {
should.exist(error);
error.code.should.equal('ERR_BODY_PARSE_FAILURE');
should.exist(response);
response.should.equal(error.response);
response.statusCode.should.equal(status);
response.headers['content-type'].should.equal('text/plain');
body.should.equal('Hey ya! Greetings!');
body.should.equal(response.body);
endpoint.isDone().should.equal(true);
done();
});
});
});

it('should not invent a response when the connection fails', function (done) {
const endpoint = nock('https://command.example.test')
.post('/nada', { ping: 'RRRR' })
.replyWithError({ code: 'ECONNREFUSED', message: 'Connection refused' });

request(options, function (error, response, body) {
should.exist(error);
error.code.should.equal('ECONNREFUSED');
should(response).equal(undefined);
should(body).equal(undefined);
endpoint.isDone().should.equal(true);
done();
});
});

it('should continue returning parsed JSON for a valid response', function (done) {
const endpoint = nock('https://command.example.test')
.post('/nada', { ping: 'RRRR' })
.reply(200, { ping: 'OK' });

request(options, function (error, response, body) {
should.not.exist(error);
response.statusCode.should.equal(200);
body.should.deepEqual({ ping: 'OK' });
body.should.equal(response.body);
endpoint.isDone().should.equal(true);
done();
});
});
});
3 changes: 2 additions & 1 deletion lib/bindings/HTTPBinding.js
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,8 @@ function executeCommand(apiKey, group, device, cmdName, serializedPayload, extra
);
request(options, function (error, response, body) {
if (error || !response || (response.statusCode !== 200 && response.statusCode !== 201)) {
callback(new errors.HTTPCommandResponseError(response ? response.statusCode : 400, error));
const commandResponse = response || error?.response;
callback(new errors.HTTPCommandResponseError(commandResponse?.statusCode, error, cmdName, device.id));
} else if (apiKey) {
config
.getLogger()
Expand Down
13 changes: 10 additions & 3 deletions lib/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,17 @@ class ConfigurationError {
}
}
class HTTPCommandResponseError {
constructor(code, error) {
constructor(code, error, command, deviceId) {
this.name = 'HTTP_COMMAND_RESPONSE_ERROR';
this.message =
'There was an error in the response of a device to a command [' + code + ' ]:' + JSON.stringify(error);
this.message = 'Command [' + command + '] failed for device [' + deviceId + ']: ';
this.message += code ? 'endpoint returned HTTP ' + code : 'no HTTP response received from endpoint';
if (error?.code === 'ERR_BODY_PARSE_FAILURE') {
this.message += '; invalid JSON response';
} else if (error) {
this.message += '; ' + (error.message || error.code || error.name || 'request failed');
} else {
this.message += '; expected HTTP 200 or 201 with a JSON response';
}
this.code = 400;
}
}
Expand Down
132 changes: 132 additions & 0 deletions test/unit/ngsiv2/HTTP_command_errors_test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/*
* Copyright 2016 Telefonica Investigación y Desarrollo, S.A.U
*
* This file is part of iotagent-json
*
* iotagent-json is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* iotagent-json is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with iotagent-json.
* If not, seehttp://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License
* please contact with::[contacto@tid.es]
*
*
*/

const nock = require('nock');
const should = require('should');
const proxyquire = require('proxyquire');
const binding = proxyquire('../../../lib/bindings/HTTPBinding', {
'../configService': {
getConfig: () => ({ http: {}, iota: {} })
}
});

describe('HTTP command execution responses', function () {
const device = {
id: 'device1',
type: 'Thing',
service: 'smartcity',
subservice: '/',
endpoint: 'http://localhost:9876/command'
};

afterEach(function () {
nock.cleanAll();
});

it('should report HTTP 200 with a plain-text response as a command error', function (done) {
const commandDevice = {
...device,
id: 'test125',
endpoint: 'https://command.example.test/nada'
};
const endpoint = nock('https://command.example.test', {
reqheaders: {
'fiware-service': 'smartcity',
'fiware-servicepath': '/',
'content-type': 'application/json'
}
})
.post('/nada', { ping: 'RRRR' })
.reply(200, 'Hey ya! Greetings!', { 'Content-Type': 'text/plain' });

binding.executeCommand(
null,
null,
commandDevice,
'ping',
'{"ping":"RRRR"}',
null,
'application/json',
function (error) {
should.exist(error);
error.code.should.equal(400);
error.name.should.equal('HTTP_COMMAND_RESPONSE_ERROR');
error.message.should.equal(
'Command [ping] failed for device [test125]: endpoint returned HTTP 200; invalid JSON response'
);
endpoint.isDone().should.equal(true);
done();
}
);
});

[
{ status: 200, body: 'Hey ya!', reason: 'invalid JSON' },
{ status: 500, body: { error: 'Command failed' }, reason: 'HTTP 500' },
{ status: 503, body: 'Unavailable', reason: 'HTTP 503' },
{ status: 204, reason: 'HTTP 204' },
{ error: { code: 'ECONNREFUSED', message: 'Connection refused' }, reason: 'Connection refused' }
].forEach(function (testCase) {
it('should describe command failure for ' + testCase.reason, function (done) {
const endpoint = nock('http://localhost:9876').post('/command', { ping: 'MMMM' });
if (testCase.error) {
endpoint.replyWithError(testCase.error);
} else {
endpoint.reply(testCase.status, testCase.body);
}

binding.executeCommand(null, null, device, 'ping', '{"ping":"MMMM"}', null, 'application/json', function (
error
) {
should.exist(error);
error.code.should.equal(400);
error.name.should.equal('HTTP_COMMAND_RESPONSE_ERROR');
error.message.should.containEql('ping');
error.message.should.containEql('device1');
error.message.should.containEql(testCase.reason);
if (testCase.status) {
error.message.should.containEql('HTTP ' + testCase.status);
} else {
error.message.should.not.containEql('HTTP 400');
}
should(nock.isDone()).equal(true);
done();
});
});
});

[200, 201].forEach(function (status) {
it('should continue accepting HTTP ' + status + ' with JSON', function (done) {
nock('http://localhost:9876').post('/command').reply(status, { ping: 'OK' });
binding.executeCommand(null, null, device, 'ping', '{"ping":"MMMM"}', null, 'application/json', function (
error
) {
should.not.exist(error);
should(nock.isDone()).equal(true);
done();
});
});
});
});
Loading