Remove node.d.plugin and relevant files (#12769)
* Remove node.d.plugin and relevant files * fix build packages * remove node.d related words/phrases from docs and tests
Suraj Neupane committed
May 3, 2022 at 09:16 UTC
22863c42b9ccf59d340f39c7719b6ef19b455a16
44 files changed
+24
-7207
.codacy.yml
-1
@@ -4,7 +4,6 @@ exclude_paths:
4
- collectors/python.d.plugin/python_modules/pyyaml3/**
5
- collectors/python.d.plugin/python_modules/urllib3/**
6
- collectors/python.d.plugin/python_modules/third_party/**
7
- - collectors/node.d.plugin/node_modules/**
7
- contrib/**
8
- packaging/makeself/**
9
- web/gui/css/**
.codeclimate.yml
-5
@@ -91,8 +91,3 @@ exclude_patterns:
91
- "collectors/python.d.plugin/python_modules/pyyaml2/"
92
- "collectors/python.d.plugin/python_modules/pyyaml3/"
93
- "collectors/python.d.plugin/python_modules/urllib3/"
94
- - "collectors/node.d.plugin/node_modules/lib/"
95
- - "collectors/node.d.plugin/node_modules/asn1-ber.js"
96
- - "collectors/node.d.plugin/node_modules/extend.js"
97
- - "collectors/node.d.plugin/node_modules/pixl-xml.js"
98
- - "collectors/node.d.plugin/node_modules/net-snmp.js"
.github/CODEOWNERS
-2
@@ -15,8 +15,6 @@ collectors/ebpf.plugin/ @thiagoftsm @vlvkobal
15
collectors/charts.d.plugin/ @ilyam8 @surajnpn @Ferroin
16
collectors/freebsd.plugin/ @vlvkobal @thiagoftsm @surajnpn
17
collectors/macos.plugin/ @vlvkobal @thiagoftsm @surajnpn
18
-collectors/node.d.plugin/ @jacekkolasa
19
-collectors/node.d.plugin/snmp/ @jacekkolasa
18
collectors/python.d.plugin/ @ilyam8
19
collectors/cups.plugin/ @simonnagl @vlvkobal @thiagoftsm
20
exporting/ @vlvkobal @thiagoftsm
.github/labeler.yml
-4
@@ -116,10 +116,6 @@ collectors/nfacct:
116
- collectors/nfacct.plugin/*
117
- collectors/nfacct.plugin/**/*
118
119
-collectors/node.d:
120
- - collectors/node.d.plugin/*
121
- - collectors/node.d.plugin/**/*
122
-
119
collectors/perf:
120
- collectors/perf.plugin/*
121
- collectors/perf.plugin/**/*
.gitignore
-1
@@ -136,7 +136,6 @@ health/notifications/alarm-notify.sh
136
claim/netdata-claim.sh
137
collectors/tc.plugin/tc-qos-helper.sh
138
collectors/charts.d.plugin/charts.d.plugin
139
-collectors/node.d.plugin/node.d.plugin
139
collectors/python.d.plugin/python.d.plugin
140
collectors/fping.plugin/fping.plugin
141
collectors/ioping.plugin/ioping.plugin
.lgtm.yml
-5
@@ -12,11 +12,6 @@ path_classifiers:
12
- collectors/python.d.plugin/python_modules/urllib3/
13
- collectors/python.d.plugin/python_modules/pyyaml2/
14
- collectors/python.d.plugin/python_modules/pyyaml3/
15
- - collectors/node.d.plugin/node_modules/lib/
16
- - collectors/node.d.plugin/node_modules/asn1-ber.js
17
- - collectors/node.d.plugin/node_modules/extend.js
18
- - collectors/node.d.plugin/node_modules/net-snmp.js
19
- - collectors/node.d.plugin/node_modules/pixl-xml.js
15
- ml/kmeans/dlib/
16
- ml/json/
17
- web/gui/lib/
build_external/scenarios/aclk-testing/agent_netdata.conf
-5
@@ -96,7 +96,6 @@
96
# check for new plugins every = 60
97
# slabinfo = no
98
# go.d = yes
99
- # node.d = yes
99
# apps = yes
100
# charts.d = yes
101
# fping = yes
@@ -265,10 +264,6 @@
264
# update every = 1
265
# command options =
266
268
-[plugin:node.d]
269
- # update every = 1
270
- # command options =
271
-
267
[plugin:apps]
268
# update every = 1
269
# command options =
build_external/scenarios/gaps_lo/mostly_off.conf
-1
@@ -28,7 +28,6 @@ errors flood protection period = 0
28
fping = no
29
python.d = no
30
charts.d = no
31
- node.d = no
31
nfacct = no
32
cups = no
33
freeipmi = no
collectors/COLLECTORS.md
+10
-9
@@ -250,13 +250,15 @@ configure any of these collectors according to your setup and infrastructure.
250
251
- [AM2320](/collectors/python.d.plugin/am2320/README.md): Monitor sensor temperature and humidity.
252
- [Access point](/collectors/charts.d.plugin/ap/README.md): Monitor client, traffic and signal metrics using the `aw`
253
- tool.
253
+ tool.
254
- [APC UPS](/collectors/charts.d.plugin/apcupsd/README.md): Capture status information using the `apcaccess` tool.
255
-- [Energi Core](https://learn.netdata.cloud/docs/agent/collectors/go.d.plugin/modules/energid): Monitor
256
- blockchain indexes, memory usage, network usage, and transactions of wallet instances.
255
+- [Energi Core (Go)](https://learn.netdata.cloud/docs/agent/collectors/go.d.plugin/modules/energid): Monitor
256
+ blockchain indexes, memory usage, network usage, and transactions of wallet instances.
257
+- [Energi Core (Python)](/collectors/python.d.plugin/energid/README.md): Monitor blockchain, memory, network, and
258
+ unspent transactions statistics.
259
- [UPS/PDU](/collectors/charts.d.plugin/nut/README.md): Read the status of UPS/PDU devices using the `upsc` tool.
258
-- [SNMP devices](/collectors/node.d.plugin/snmp/README.md): Gather data using the SNMP protocol.
259
-- [1-Wire sensors](/collectors/python.d.plugin/w1sensor/README.md): Monitor sensor temperature.
260
+- [SNMP devices](https://learn.netdata.cloud/docs/agent/collectors/go.d.plugin/modules/snmp): Gather data using the SNMP protocol.
261
+- [1-Wire sensors](/collectors/python.d.plugin/w1sensor/README.md): Monitor sensor temperature.
262
263
### Search
264
@@ -481,10 +483,9 @@ Plugin orchestrators organize and run many of the above collectors.
483
If you're interested in developing a new collector that you'd like to contribute to Netdata, we highly recommend using
484
the `go.d.plugin`.
485
484
-- [go.d.plugin](https://github.com/netdata/go.d.plugin): An orchestrator for data collection modules written in `go`.
485
-- [python.d.plugin](python.d.plugin/README.md): An orchestrator for data collection modules written in `python` v2/v3.
486
-- [charts.d.plugin](charts.d.plugin/README.md): An orchestrator for data collection modules written in `bash` v4+.
487
-- [node.d.plugin](node.d.plugin/README.md): An orchestrator for data collection modules written in `node.js`.
486
+- [go.d.plugin](https://github.com/netdata/go.d.plugin): An orchestrator for data collection modules written in `go`.
487
+- [python.d.plugin](python.d.plugin/README.md): An orchestrator for data collection modules written in `python` v2/v3.
488
+- [charts.d.plugin](charts.d.plugin/README.md): An orchestrator for data collection modules written in `bash` v4+.
489
490
## Third-party collectors
491
collectors/Makefile.am
-1
@@ -20,7 +20,6 @@ SUBDIRS = \
20
nfacct.plugin \
21
xenstat.plugin \
22
perf.plugin \
23
- node.d.plugin \
23
proc.plugin \
24
python.d.plugin \
25
slabinfo.plugin \
collectors/REFERENCE.md
-4
@@ -67,9 +67,6 @@ field contains `go.d`, that collector uses the Go orchestrator.
67
# Python orchestrator (python.d.plugin)
68
./python.d.plugin <MODULE_NAME> debug trace
69
70
-# Node orchestrator (node.d.plugin)
71
-./node.d.plugin debug 1 <MODULE_NAME>
72
-
70
# Bash orchestrator (bash.d.plugin)
71
./charts.d.plugin debug 1 <MODULE_NAME>
72
```
@@ -100,7 +97,6 @@ This section features a list of Netdata's plugins, with a boolean setting to ena
97
# slabinfo = no
98
# fping = yes
99
# ioping = yes
103
- # node.d = yes
100
# python.d = yes
101
# go.d = yes
102
# apps = yes
collectors/apps.plugin/apps_groups.conf
-1
@@ -82,7 +82,6 @@ cups.plugin: cups.plugin
82
xenstat.plugin: xenstat.plugin
83
perf.plugin: perf.plugin
84
charts.d.plugin: *charts.d.plugin*
85
-node.d.plugin: *node.d.plugin*
85
python.d.plugin: *python.d.plugin*
86
tc-qos-helper: *tc-qos-helper.sh*
87
fping: fping
collectors/node.d.plugin/Makefile.am
deleted
-57
@@ -1,57 +0,0 @@
1
-# SPDX-License-Identifier: GPL-3.0-or-later
2
-
3
-MAINTAINERCLEANFILES = $(srcdir)/Makefile.in
4
-CLEANFILES = \
5
- node.d.plugin \
6
- $(NULL)
7
-
8
-include $(top_srcdir)/build/subst.inc
9
-SUFFIXES = .in
10
-
11
-dist_libconfig_DATA = \
12
- node.d.conf \
13
- $(NULL)
14
-
15
-dist_plugins_SCRIPTS = \
16
- node.d.plugin \
17
- $(NULL)
18
-
19
-dist_noinst_DATA = \
20
- node.d.plugin.in \
21
- README.md \
22
- $(NULL)
23
-
24
-usernodeconfigdir=$(configdir)/node.d
25
-dist_usernodeconfig_DATA = \
26
- $(NULL)
27
-
28
-# Explicitly install directories to avoid permission issues due to umask
29
-install-exec-local:
30
- $(INSTALL) -d $(DESTDIR)$(usernodeconfigdir)
31
-
32
-nodeconfigdir=$(libconfigdir)/node.d
33
-dist_nodeconfig_DATA = \
34
- $(NULL)
35
-
36
-dist_node_DATA = \
37
- $(NULL)
38
-
39
-include snmp/Makefile.inc
40
-
41
-nodemodulesdir=$(nodedir)/node_modules
42
-dist_nodemodules_DATA = \
43
- node_modules/netdata.js \
44
- node_modules/extend.js \
45
- node_modules/pixl-xml.js \
46
- node_modules/net-snmp.js \
47
- node_modules/asn1-ber.js \
48
- $(NULL)
49
-
50
-nodemoduleslibberdir=$(nodedir)/node_modules/lib/ber
51
-dist_nodemoduleslibber_DATA = \
52
- node_modules/lib/ber/index.js \
53
- node_modules/lib/ber/errors.js \
54
- node_modules/lib/ber/reader.js \
55
- node_modules/lib/ber/types.js \
56
- node_modules/lib/ber/writer.js \
57
- $(NULL)
collectors/node.d.plugin/README.md
deleted
-236
@@ -1,236 +0,0 @@
1
-<!--
2
-title: "node.d.plugin"
3
-custom_edit_url: https://github.com/netdata/netdata/edit/master/collectors/node.d.plugin/README.md
4
--->
5
-
6
-# node.d.plugin
7
-
8
-`node.d.plugin` is a Netdata external plugin. It is an **orchestrator** for data collection modules written in `node.js`.
9
-
10
-1. It runs as an independent process `ps fax` shows it
11
-2. It is started and stopped automatically by Netdata
12
-3. It communicates with Netdata via a unidirectional pipe (sending data to the `netdata` daemon)
13
-4. Supports any number of data collection **modules**
14
-5. Allows each **module** to have one or more data collection **jobs**
15
-6. Each **job** is collecting one or more metrics from a single data source
16
-
17
-## Pull Request Checklist for Node.js Plugins
18
-
19
-This is a generic checklist for submitting a new Node.js plugin for Netdata. It is by no means comprehensive.
20
-
21
-At minimum, to be buildable and testable, the PR needs to include:
22
-
23
-- The module itself, following proper naming conventions: `node.d/<module_dir>/<module_name>.node.js`
24
-- A README.md file for the plugin.
25
-- The configuration file for the module
26
-- A basic configuration for the plugin in the appropriate global config file: `conf.d/node.d.conf`, which is also in JSON format. If the module should be enabled by default, add a section for it in the `modules` dictionary.
27
-- A line for the plugin in the appropriate `Makefile.am` file: `node.d/Makefile.am` under `dist_node_DATA`.
28
-- A line for the plugin configuration file in `conf.d/Makefile.am`: under `dist_nodeconfig_DATA`
29
-- Optionally, chart information in `web/dashboard_info.js`. This generally involves specifying a name and icon for the section, and may include descriptions for the section or individual charts.
30
-
31
-## Motivation
32
-
33
-Node.js is perfect for asynchronous operations. It is very fast and quite common (actually the whole web is based on it).
34
-Since data collection is not a CPU intensive task, node.js is an ideal solution for it.
35
-
36
-`node.d.plugin` is a Netdata plugin that provides an abstraction layer to allow easy and quick development of data
37
-collectors in node.js. It also manages all its data collectors (placed in `/usr/libexec/netdata/node.d`) using a single
38
-instance of node, thus lowering the memory footprint of data collection.
39
-
40
-Of course, there can be independent plugins written in node.js (placed in `/usr/libexec/netdata/plugins`).
41
-These will have to be developed using the guidelines of **[External Plugins](/collectors/plugins.d/README.md)**.
42
-
43
-To run `node.js` plugins you need to have `node` installed in your system.
44
-
45
-In some older systems, the package named `node` is not node.js. It is a terminal emulation program called `ax25-node`.
46
-In this case the node.js package may be referred as `nodejs`. Once you install `nodejs`, we suggest to link
47
-`/usr/bin/nodejs` to `/usr/bin/node`, so that typing `node` in your terminal, opens node.js.
48
-
49
-## configuring `node.d.plugin`
50
-
51
-`node.d.plugin` can work even without any configuration. Its default configuration file is
52
-`node.d.conf`. To edit it on your system, run `/etc/netdata/edit-config node.d.conf`.
53
-
54
-## configuring `node.d.plugin` modules
55
-
56
-`node.d.plugin` modules accept configuration in `JSON` format.
57
-
58
-Unfortunately, `JSON` files do not accept comments. So, the best way to describe them is to have markdown text files
59
-with instructions.
60
-
61
-`JSON` has a very strict formatting. If you get errors from Netdata at `/var/log/netdata/error.log` that a certain
62
-configuration file cannot be loaded, we suggest to verify it at <http://jsonlint.com/>.
63
-
64
-The files in this directory, provide usable examples for configuring each `node.d.plugin` module.
65
-
66
-## debugging modules written for node.d.plugin
67
-
68
-To test `node.d.plugin` modules, which are placed in `/usr/libexec/netdata/node.d`, you can run `node.d.plugin` by hand,
69
-like this:
70
-
71
-```sh
72
-# become user netdata
73
-sudo su -s /bin/sh netdata
74
-
75
-# run the plugin in debug mode
76
-/usr/libexec/netdata/plugins.d/node.d.plugin debug 1 X Y Z
77
-```
78
-
79
-`node.d.plugin` will run in `debug` mode (lots of debug info), with an update frequency of `1` second, evaluating only
80
-the collector scripts `X` (i.e. `/usr/libexec/netdata/node.d/X.node.js`), `Y` and `Z`.
81
-You can define zero or more modules. If none is defined, `node.d.plugin` will evaluate all modules available.
82
-
83
-Keep in mind that if your configs are not in `/etc/netdata`, you should do the following before running `node.d.plugin`:
84
-
85
-```sh
86
-export NETDATA_USER_CONFIG_DIR="/path/to/etc/netdata"
87
-```
88
-
89
----
90
-
91
-## developing `node.d.plugin` modules
92
-
93
-Your data collection module should be split in 3 parts:
94
-
95
-- a function to fetch the data from its source. `node.d.plugin` already can fetch data from web sources,
96
- so you don't need to do anything about it for http.
97
-
98
-- a function to process the fetched/manipulate the data fetched. This function will make a number of calls
99
- to create charts and dimensions and pass the collected values to Netdata.
100
- This is the only function you need to write for collecting http JSON data.
101
-
102
-- a `configure` and an `update` function, which take care of your module configuration and data refresh
103
- respectively. You can use the supplied ones.
104
-
105
-Your module will automatically be able to process any number of servers, with different settings (even different
106
-data collection frequencies). You will write just the work needed for one and `node.d.plugin` will do the rest.
107
-For each server you are going to fetch data from, you will have to create a `service` (more later).
108
-
109
-### writing the data collection module
110
-
111
-To provide a module called `mymodule`, you have create the file `/usr/libexec/netdata/node.d/mymodule.node.js`, with this structure:
112
-
113
-```js
114
-// the processor is needed only
115
-// if you need a custom processor
116
-// other than http
117
-netdata.processors.myprocessor = {
118
- name: 'myprocessor',
119
-
120
- process: function(service, callback) {
121
-
122
- /* do data collection here */
123
-
124
- callback(data);
125
- }
126
-};
127
-
128
-// this is the mymodule definition
129
-var mymodule = {
130
- processResponse: function(service, data) {
131
-
132
- /* send information to the Netdata server here */
133
-
134
- },
135
-
136
- configure: function(config) {
137
- var eligible_services = 0;
138
-
139
- if(typeof(config.servers) === 'undefined' || config.servers.length === 0) {
140
-
141
- /*
142
- * create a service using internal defaults;
143
- * this is used for auto-detecting the settings
144
- * if possible
145
- */
146
-
147
- netdata.service({
148
- name: 'a name for this service',
149
- update_every: this.update_every,
150
- module: this,
151
- processor: netdata.processors.myprocessor,
152
- // any other information your processor needs
153
- }).execute(this.processResponse);
154
-
155
- eligible_services++;
156
- }
157
- else {
158
-
159
- /*
160
- * create a service for each server in the
161
- * configuration file
162
- */
163
-
164
- var len = config.servers.length;
165
- while(len--) {
166
- var server = config.servers[len];
167
-
168
- netdata.service({
169
- name: server.name,
170
- update_every: server.update_every,
171
- module: this,
172
- processor: netdata.processors.myprocessor,
173
- // any other information your processor needs
174
- }).execute(this.processResponse);
175
-
176
- eligible_services++;
177
- }
178
- }
179
-
180
- return eligible_services;
181
- },
182
-
183
- update: function(service, callback) {
184
-
185
- /*
186
- * this function is called when each service
187
- * created by the configure function, needs to
188
- * collect updated values.
189
- *
190
- * You normally will not need to change it.
191
- */
192
-
193
- service.execute(function(service, data) {
194
- mymodule.processResponse(service, data);
195
- callback();
196
- });
197
- },
198
-};
199
-
200
-module.exports = mymodule;
201
-```
202
-
203
-#### configure(config)
204
-
205
-`configure(config)` is called just once, when `node.d.plugin` starts.
206
-The config file will contain the contents of `/etc/netdata/node.d/mymodule.conf`.
207
-This file should have the following format:
208
-
209
-```js
210
-{
211
- "enable_autodetect": false,
212
- "update_every": 5,
213
- "servers": [ { /* server 1 */ }, { /* server 2 */ } ]
214
-}
215
-```
216
-
217
-If the config file `/etc/netdata/node.d/mymodule.conf` does not give a `enable_autodetect` or `update_every`, these
218
-will be added by `node.d.plugin`. So you module will always have them.
219
-
220
-The configuration file `/etc/netdata/node.d/mymodule.conf` may contain whatever else is needed for `mymodule`.
221
-
222
-#### processResponse(data)
223
-
224
-`data` may be `null` or whatever the processor specified in the `service` returned.
225
-
226
-The `service` object defines a set of functions to allow you send information to the Netdata core about:
227
-
228
-1. Charts and dimension definitions
229
-2. Updated values, from the collected values
230
-
231
----
232
-
233
-_FIXME: document an operational node.d.plugin data collector - the best example is the
234
-[snmp collector](https://raw.githubusercontent.com/netdata/netdata/master/collectors/node.d.plugin/snmp/snmp.node.js)_
235
-
236
-
collectors/node.d.plugin/node.d.conf
deleted
-33
@@ -1,33 +0,0 @@
1
-{
2
- "___help_1": "Default options for node.d.plugin - this is a JSON file.",
3
- "___help_2": "Use http://jsonlint.com/ to verify it is valid JSON.",
4
- "___help_3": "------------------------------------------------------------",
5
-
6
- "___help_update_every": "Minimum data collection frequency for all node.d/*.node.js modules. Set it to 0 to inherit it from netdata.",
7
- "update_every": 0,
8
-
9
- "___help_modules_enable_autodetect": "Enable/disable auto-detection for node.d/*.node.js modules that support it.",
10
- "modules_enable_autodetect": true,
11
-
12
- "___help_modules_enable_all": "Enable all node.d/*.node.js modules by default.",
13
- "modules_enable_all": true,
14
-
15
- "___help_modules": "Enable/disable the following modules. Give only XXX for node.d/XXX.node.js",
16
- "modules": {
17
- "snmp": {
18
- "enabled": true
19
- }
20
- },
21
-
22
- "___help_paths": "Paths that control the operation of node.d.plugin",
23
- "paths": {
24
- "___help_plugins": "The full path to the modules javascript node.d/ directory",
25
- "plugins": null,
26
-
27
- "___help_config": "The full path to the modules configs node.d/ directory",
28
- "config": null,
29
-
30
- "___help_modules": "Array of paths to add to node.js when searching for node_modules",
31
- "modules": []
32
- }
33
-}
collectors/node.d.plugin/node.d.plugin.in
deleted
-303
@@ -1,303 +0,0 @@
1
-#!/usr/bin/env bash
2
-':' //; exec "$(command -v nodejs || command -v node || echo "ERROR node IS NOT AVAILABLE IN THIS SYSTEM")" "$0" "$@"
3
-
4
-// shebang hack from:
5
-// http://unix.stackexchange.com/questions/65235/universal-node-js-shebang
6
-
7
-// Initially this is run as a shell script.
8
-// Then, the second line, finds nodejs or node or js in the system path
9
-// and executes it with the shell parameters.
10
-
11
-// netdata
12
-// real-time performance and health monitoring, done right!
13
-// (C) 2017 Costa Tsaousis <costa@tsaousis.gr>
14
-// SPDX-License-Identifier: GPL-3.0-or-later
15
-
16
-// --------------------------------------------------------------------------------------------------------------------
17
-
18
-'use strict';
19
-
20
-// --------------------------------------------------------------------------------------------------------------------
21
-// get NETDATA environment variables
22
-
23
-var NETDATA_PLUGINS_DIR = process.env.NETDATA_PLUGINS_DIR || __dirname;
24
-var NETDATA_USER_CONFIG_DIR = process.env.NETDATA_USER_CONFIG_DIR || '@configdir_POST@';
25
-var NETDATA_STOCK_CONFIG_DIR = process.env.NETDATA_STOCK_CONFIG_DIR || '@libconfigdir_POST@';
26
-var NETDATA_UPDATE_EVERY = process.env.NETDATA_UPDATE_EVERY || 1;
27
-var NODE_D_DIR = NETDATA_PLUGINS_DIR + '/../node.d';
28
-
29
-// make sure the modules are found
30
-process.mainModule.paths.unshift(NODE_D_DIR + '/node_modules');
31
-process.mainModule.paths.unshift(NODE_D_DIR);
32
-
33
-
34
-// --------------------------------------------------------------------------------------------------------------------
35
-// load required modules
36
-
37
-var fs = require('fs');
38
-var url = require('url');
39
-var util = require('util');
40
-var http = require('http');
41
-var path = require('path');
42
-var extend = require('extend');
43
-var netdata = require('netdata');
44
-
45
-
46
-// --------------------------------------------------------------------------------------------------------------------
47
-// configuration
48
-
49
-function netdata_read_json_config_file(module_filename) {
50
- var f = path.basename(module_filename);
51
-
52
- var ufilename, sfilename;
53
-
54
- var m = f.match('.plugin' + '$');
55
- if(m !== null) {
56
- ufilename = netdata.options.paths.config + '/' + f.substring(0, m.index) + '.conf';
57
- sfilename = netdata.options.paths.stock_config + '/' + f.substring(0, m.index) + '.conf';
58
- }
59
-
60
- m = f.match('.node.js' + '$');
61
- if(m !== null) {
62
- ufilename = netdata.options.paths.config + '/node.d/' + f.substring(0, m.index) + '.conf';
63
- sfilename = netdata.options.paths.stock_config + '/node.d/' + f.substring(0, m.index) + '.conf';
64
- }
65
-
66
- try {
67
- netdata.debug('loading module\'s ' + module_filename + ' user-config ' + ufilename);
68
- return JSON.parse(fs.readFileSync(ufilename, 'utf8'));
69
- }
70
- catch(e) {
71
- netdata.error('Cannot read user-configuration file ' + ufilename + ': ' + e.message + '.');
72
- dumpError(e);
73
- }
74
-
75
- try {
76
- netdata.debug('loading module\'s ' + module_filename + ' stock-config ' + sfilename);
77
- return JSON.parse(fs.readFileSync(sfilename, 'utf8'));
78
- }
79
- catch(e) {
80
- netdata.error('Cannot read stock-configuration file ' + sfilename + ': ' + e.message + ', using internal defaults.');
81
- dumpError(e);
82
- }
83
-
84
- return {};
85
-}
86
-
87
-// internal defaults
88
-extend(true, netdata.options, {
89
- filename: path.basename(__filename),
90
-
91
- update_every: NETDATA_UPDATE_EVERY,
92
-
93
- paths: {
94
- plugins: NETDATA_PLUGINS_DIR,
95
- config: NETDATA_USER_CONFIG_DIR,
96
- stock_config: NETDATA_STOCK_CONFIG_DIR,
97
- modules: []
98
- },
99
-
100
- modules_enable_autodetect: true,
101
- modules_enable_all: true,
102
- modules: {}
103
-});
104
-
105
-// load configuration file
106
-netdata.options_loaded = netdata_read_json_config_file(__filename);
107
-extend(true, netdata.options, netdata.options_loaded);
108
-
109
-if(!netdata.options.paths.plugins)
110
- netdata.options.paths.plugins = NETDATA_PLUGINS_DIR;
111
-
112
-if(!netdata.options.paths.config)
113
- netdata.options.paths.config = NETDATA_USER_CONFIG_DIR;
114
-
115
-if(!netdata.options.paths.stock_config)
116
- netdata.options.paths.stock_config = NETDATA_STOCK_CONFIG_DIR;
117
-
118
-// console.error('merged netdata object:');
119
-// console.error(util.inspect(netdata, {depth: 10}));
120
-
121
-
122
-// apply module paths to node.js process
123
-function applyModulePaths() {
124
- var len = netdata.options.paths.modules.length;
125
- while(len--)
126
- process.mainModule.paths.unshift(netdata.options.paths.modules[len]);
127
-}
128
-applyModulePaths();
129
-
130
-
131
-// --------------------------------------------------------------------------------------------------------------------
132
-// tracing
133
-
134
-function dumpError(err) {
135
- if (typeof err === 'object') {
136
- if (err.stack) {
137
- netdata.debug(err.stack);
138
- }
139
- }
140
-}
141
-
142
-// --------------------------------------------------------------------------------------------------------------------
143
-// get command line arguments
144
-{
145
- var found_myself = false;
146
- var found_number = false;
147
- var found_modules = false;
148
- process.argv.forEach(function (val, index, array) {
149
- netdata.debug('PARAM: ' + val);
150
-
151
- if(!found_myself) {
152
- if(val === __filename)
153
- found_myself = true;
154
- }
155
- else {
156
- switch(val) {
157
- case 'debug':
158
- netdata.options.DEBUG = true;
159
- netdata.debug('DEBUG enabled');
160
- break;
161
-
162
- default:
163
- if(found_number === true) {
164
- if(found_modules === false) {
165
- for(var i in netdata.options.modules)
166
- netdata.options.modules[i].enabled = false;
167
- }
168
-
169
- if(typeof netdata.options.modules[val] === 'undefined')
170
- netdata.options.modules[val] = {};
171
-
172
- netdata.options.modules[val].enabled = true;
173
- netdata.options.modules_enable_all = false;
174
- netdata.debug('enabled module ' + val);
175
- }
176
- else {
177
- try {
178
- var x = parseInt(val);
179
- if(x > 0) {
180
- netdata.options.update_every = x;
181
- if(netdata.options.update_every < NETDATA_UPDATE_EVERY) {
182
- netdata.options.update_every = NETDATA_UPDATE_EVERY;
183
- netdata.debug('Update frequency ' + x + 's is too low');
184
- }
185
-
186
- found_number = true;
187
- netdata.debug('Update frequency set to ' + netdata.options.update_every + ' seconds');
188
- }
189
- else netdata.error('Ignoring parameter: ' + val);
190
- }
191
- catch(e) {
192
- netdata.error('Cannot get value of parameter: ' + val);
193
- dumpError(e);
194
- }
195
- }
196
- break;
197
- }
198
- }
199
- });
200
-}
201
-
202
-if(netdata.options.update_every < 1) {
203
- netdata.debug('Adjusting update frequency to 1 second');
204
- netdata.options.update_every = 1;
205
-}
206
-
207
-// --------------------------------------------------------------------------------------------------------------------
208
-// find modules
209
-
210
-function findModules() {
211
- var found = 0;
212
-
213
- var files = fs.readdirSync(NODE_D_DIR);
214
- var len = files.length;
215
- while(len--) {
216
- var m = files[len].match('.node.js' + '$');
217
- if(m !== null) {
218
- var n = files[len].substring(0, m.index);
219
-
220
- if(typeof(netdata.options.modules[n]) === 'undefined')
221
- netdata.options.modules[n] = { name: n, enabled: netdata.options.modules_enable_all };
222
-
223
- if(netdata.options.modules[n].enabled === true) {
224
- netdata.options.modules[n].name = n;
225
- netdata.options.modules[n].filename = NODE_D_DIR + '/' + files[len];
226
- netdata.options.modules[n].loaded = false;
227
-
228
- // load the module
229
- try {
230
- netdata.debug('loading module ' + netdata.options.modules[n].filename);
231
- netdata.options.modules[n].module = require(netdata.options.modules[n].filename);
232
- netdata.options.modules[n].module.name = n;
233
- netdata.debug('loaded module ' + netdata.options.modules[n].name + ' from ' + netdata.options.modules[n].filename);
234
- }
235
- catch(e) {
236
- netdata.options.modules[n].enabled = false;
237
- netdata.error('Cannot load module: ' + netdata.options.modules[n].filename + ' exception: ' + e);
238
- dumpError(e);
239
- continue;
240
- }
241
-
242
- // load its configuration
243
- var c = {
244
- enable_autodetect: netdata.options.modules_enable_autodetect,
245
- update_every: netdata.options.update_every
246
- };
247
-
248
- var c2 = netdata_read_json_config_file(files[len]);
249
- extend(true, c, c2);
250
-
251
- // call module auto-detection / configuration
252
- try {
253
- netdata.modules_configuring++;
254
- netdata.debug('Configuring module ' + netdata.options.modules[n].name);
255
- var serv = netdata.configure(netdata.options.modules[n].module, c, function() {
256
- netdata.debug('Configured module ' + netdata.options.modules[n].name);
257
- netdata.modules_configuring--;
258
- });
259
-
260
- netdata.debug('Configuring module ' + netdata.options.modules[n].name + ' reports ' + serv + ' eligible services.');
261
- }
262
- catch(e) {
263
- netdata.modules_configuring--;
264
- netdata.options.modules[n].enabled = false;
265
- netdata.error('Failed module auto-detection: ' + netdata.options.modules[n].name + ' exception: ' + e + ', disabling module.');
266
- dumpError(e);
267
- continue;
268
- }
269
-
270
- netdata.options.modules[n].loaded = true;
271
- found++;
272
- }
273
- }
274
- }
275
-
276
- // netdata.debug(netdata.options.modules);
277
- return found;
278
-}
279
-
280
-if(findModules() === 0) {
281
- netdata.error('Cannot load any .node.js module from: ' + NODE_D_DIR);
282
- netdata.disableNodePlugin();
283
- process.exit(1);
284
-}
285
-
286
-
287
-// --------------------------------------------------------------------------------------------------------------------
288
-// start
289
-
290
-function start_when_configuring_ends() {
291
- if(netdata.modules_configuring > 0) {
292
- netdata.debug('Waiting modules configuration, still running ' + netdata.modules_configuring);
293
- setTimeout(start_when_configuring_ends, 500);
294
- return;
295
- }
296
-
297
- netdata.modules_configuring = 0;
298
- netdata.start();
299
-}
300
-start_when_configuring_ends();
301
-
302
-//netdata.debug('netdata object:')
303
-//netdata.debug(netdata);
collectors/node.d.plugin/node_modules/asn1-ber.js
deleted
-7
@@ -1,7 +0,0 @@
1
-// SPDX-License-Identifier: MIT
2
-
3
-var Ber = require('./lib/ber/index')
4
-
5
-exports.Ber = Ber
6
-exports.BerReader = Ber.Reader
7
-exports.BerWriter = Ber.Writer
collectors/node.d.plugin/node_modules/extend.js
deleted
-88
@@ -1,88 +0,0 @@
1
-// https://github.com/justmoon/node-extend
2
-// SPDX-License-Identifier: MIT
3
-
4
-'use strict';
5
-
6
-var hasOwn = Object.prototype.hasOwnProperty;
7
-var toStr = Object.prototype.toString;
8
-
9
-var isArray = function isArray(arr) {
10
- if (typeof Array.isArray === 'function') {
11
- return Array.isArray(arr);
12
- }
13
-
14
- return toStr.call(arr) === '[object Array]';
15
-};
16
-
17
-var isPlainObject = function isPlainObject(obj) {
18
- if (!obj || toStr.call(obj) !== '[object Object]') {
19
- return false;
20
- }
21
-
22
- var hasOwnConstructor = hasOwn.call(obj, 'constructor');
23
- var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
24
- // Not own constructor property must be Object
25
- if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
26
- return false;
27
- }
28
-
29
- // Own properties are enumerated firstly, so to speed up,
30
- // if last one is own, then all properties are own.
31
- var key;
32
- for (key in obj) { /**/ }
33
-
34
- return typeof key === 'undefined' || hasOwn.call(obj, key);
35
-};
36
-
37
-module.exports = function extend() {
38
- var options, name, src, copy, copyIsArray, clone;
39
- var target = arguments[0];
40
- var i = 1;
41
- var length = arguments.length;
42
- var deep = false;
43
-
44
- // Handle a deep copy situation
45
- if (typeof target === 'boolean') {
46
- deep = target;
47
- target = arguments[1] || {};
48
- // skip the boolean and the target
49
- i = 2;
50
- } else if ((typeof target !== 'object' && typeof target !== 'function') || target == null) {
51
- target = {};
52
- }
53
-
54
- for (; i < length; ++i) {
55
- options = arguments[i];
56
- // Only deal with non-null/undefined values
57
- if (options != null) {
58
- // Extend the base object
59
- for (name in options) {
60
- src = target[name];
61
- copy = options[name];
62
-
63
- // Prevent never-ending loop
64
- if (target !== copy) {
65
- // Recurse if we're merging plain objects or arrays
66
- if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
67
- if (copyIsArray) {
68
- copyIsArray = false;
69
- clone = src && isArray(src) ? src : [];
70
- } else {
71
- clone = src && isPlainObject(src) ? src : {};
72
- }
73
-
74
- // Never move original objects, clone them
75
- target[name] = extend(deep, clone, copy);
76
-
77
- // Don't bring in undefined values
78
- } else if (typeof copy !== 'undefined') {
79
- target[name] = copy;
80
- }
81
- }
82
- }
83
- }
84
- }
85
-
86
- // Return the modified object
87
- return target;
88
-};
collectors/node.d.plugin/node_modules/lib/ber/errors.js
deleted
-10
@@ -1,10 +0,0 @@
1
-// SPDX-License-Identifier: MIT
2
-
3
-module.exports = {
4
- InvalidAsn1Error: function(msg) {
5
- var e = new Error()
6
- e.name = 'InvalidAsn1Error'
7
- e.message = msg || ''
8
- return e
9
- }
10
-}
collectors/node.d.plugin/node_modules/lib/ber/index.js
deleted
-18
@@ -1,18 +0,0 @@
1
-// SPDX-License-Identifier: MIT
2
-
3
-var errors = require('./errors')
4
-var types = require('./types')
5
-
6
-var Reader = require('./reader')
7
-var Writer = require('./writer')
8
-
9
-for (var t in types)
10
- if (types.hasOwnProperty(t))
11
- exports[t] = types[t]
12
-
13
-for (var e in errors)
14
- if (errors.hasOwnProperty(e))
15
- exports[e] = errors[e]
16
-
17
-exports.Reader = Reader
18
-exports.Writer = Writer
collectors/node.d.plugin/node_modules/lib/ber/reader.js
deleted
-270
@@ -1,270 +0,0 @@
1
-// SPDX-License-Identifier: MIT
2
-
3
-var assert = require('assert');
4
-
5
-var ASN1 = require('./types');
6
-var errors = require('./errors');
7
-
8
-
9
-///--- Globals
10
-
11
-var InvalidAsn1Error = errors.InvalidAsn1Error;
12
-
13
-
14
-
15
-///--- API
16
-
17
-function Reader(data) {
18
- if (!data || !Buffer.isBuffer(data))
19
- throw new TypeError('data must be a node Buffer');
20
-
21
- this._buf = data;
22
- this._size = data.length;
23
-
24
- // These hold the "current" state
25
- this._len = 0;
26
- this._offset = 0;
27
-}
28
-
29
-Object.defineProperty(Reader.prototype, 'length', {
30
- enumerable: true,
31
- get: function () { return (this._len); }
32
-});
33
-
34
-Object.defineProperty(Reader.prototype, 'offset', {
35
- enumerable: true,
36
- get: function () { return (this._offset); }
37
-});
38
-
39
-Object.defineProperty(Reader.prototype, 'remain', {
40
- get: function () { return (this._size - this._offset); }
41
-});
42
-
43
-Object.defineProperty(Reader.prototype, 'buffer', {
44
- get: function () { return (this._buf.slice(this._offset)); }
45
-});
46
-
47
-
48
-/**
49
- * Reads a single byte and advances offset; you can pass in `true` to make this
50
- * a "peek" operation (i.e., get the byte, but don't advance the offset).
51
- *
52
- * @param {Boolean} peek true means don't move offset.
53
- * @return {Number} the next byte, null if not enough data.
54
- */
55
-Reader.prototype.readByte = function(peek) {
56
- if (this._size - this._offset < 1)
57
- return null;
58
-
59
- var b = this._buf[this._offset] & 0xff;
60
-
61
- if (!peek)
62
- this._offset += 1;
63
-
64
- return b;
65
-};
66
-
67
-
68
-Reader.prototype.peek = function() {
69
- return this.readByte(true);
70
-};
71
-
72
-
73
-/**
74
- * Reads a (potentially) variable length off the BER buffer. This call is
75
- * not really meant to be called directly, as callers have to manipulate
76
- * the internal buffer afterwards.
77
- *
78
- * As a result of this call, you can call `Reader.length`, until the
79
- * next thing called that does a readLength.
80
- *
81
- * @return {Number} the amount of offset to advance the buffer.
82
- * @throws {InvalidAsn1Error} on bad ASN.1
83
- */
84
-Reader.prototype.readLength = function(offset) {
85
- if (offset === undefined)
86
- offset = this._offset;
87
-
88
- if (offset >= this._size)
89
- return null;
90
-
91
- var lenB = this._buf[offset++] & 0xff;
92
- if (lenB === null)
93
- return null;
94
-
95
- if ((lenB & 0x80) == 0x80) {
96
- lenB &= 0x7f;
97
-
98
- if (lenB == 0)
99
- throw InvalidAsn1Error('Indefinite length not supported');
100
-
101
- if (lenB > 4)
102
- throw InvalidAsn1Error('encoding too long');
103
-
104
- if (this._size - offset < lenB)
105
- return null;
106
-
107
- this._len = 0;
108
- for (var i = 0; i < lenB; i++)
109
- this._len = (this._len << 8) + (this._buf[offset++] & 0xff);
110
-
111
- } else {
112
- // Wasn't a variable length
113
- this._len = lenB;
114
- }
115
-
116
- return offset;
117
-};
118
-
119
-
120
-/**
121
- * Parses the next sequence in this BER buffer.
122
- *
123
- * To get the length of the sequence, call `Reader.length`.
124
- *
125
- * @return {Number} the sequence's tag.
126
- */
127
-Reader.prototype.readSequence = function(tag) {
128
- var seq = this.peek();
129
- if (seq === null)
130
- return null;
131
- if (tag !== undefined && tag !== seq)
132
- throw InvalidAsn1Error('Expected 0x' + tag.toString(16) +
133
- ': got 0x' + seq.toString(16));
134
-
135
- var o = this.readLength(this._offset + 1); // stored in `length`
136
- if (o === null)
137
- return null;
138
-
139
- this._offset = o;
140
- return seq;
141
-};
142
-
143
-
144
-Reader.prototype.readInt = function(tag) {
145
- if (typeof(tag) !== 'number')
146
- tag = ASN1.Integer;
147
-
148
- return this._readTag(ASN1.Integer);
149
-};
150
-
151
-
152
-Reader.prototype.readBoolean = function(tag) {
153
- if (typeof(tag) !== 'number')
154
- tag = ASN1.Boolean;
155
-
156
- return (this._readTag(tag) === 0 ? false : true);
157
-};
158
-
159
-
160
-Reader.prototype.readEnumeration = function(tag) {
161
- if (typeof(tag) !== 'number')
162
- tag = ASN1.Enumeration;
163
-
164
- return this._readTag(ASN1.Enumeration);
165
-};
166
-
167
-
168
-Reader.prototype.readString = function(tag, retbuf) {
169
- if (!tag)
170
- tag = ASN1.OctetString;
171
-
172
- var b = this.peek();
173
- if (b === null)
174
- return null;
175
-
176
- if (b !== tag)
177
- throw InvalidAsn1Error('Expected 0x' + tag.toString(16) +
178
- ': got 0x' + b.toString(16));
179
-
180
- var o = this.readLength(this._offset + 1); // stored in `length`
181
-
182
- if (o === null)
183
- return null;
184
-
185
- if (this.length > this._size - o)
186
- return null;
187
-
188
- this._offset = o;
189
-
190
- if (this.length === 0)
191
- return retbuf ? new Buffer(0) : '';
192
-
193
- var str = this._buf.slice(this._offset, this._offset + this.length);
194
- this._offset += this.length;
195
-
196
- return retbuf ? str : str.toString('utf8');
197
-};
198
-
199
-Reader.prototype.readOID = function(tag) {
200
- if (!tag)
201
- tag = ASN1.OID;
202
-
203
- var b = this.readString(tag, true);
204
- if (b === null)
205
- return null;
206
-
207
- var values = [];
208
- var value = 0;
209
-
210
- for (var i = 0; i < b.length; i++) {
211
- var byte = b[i] & 0xff;
212
-
213
- value <<= 7;
214
- value += byte & 0x7f;
215
- if ((byte & 0x80) == 0) {
216
- values.push(value >>> 0);
217
- value = 0;
218
- }
219
- }
220
-
221
- value = values.shift();
222
- values.unshift(value % 40);
223
- values.unshift((value / 40) >> 0);
224
-
225
- return values.join('.');
226
-};
227
-
228
-
229
-Reader.prototype._readTag = function(tag) {
230
- assert.ok(tag !== undefined);
231
-
232
- var b = this.peek();
233
-
234
- if (b === null)
235
- return null;
236
-
237
- if (b !== tag)
238
- throw InvalidAsn1Error('Expected 0x' + tag.toString(16) +
239
- ': got 0x' + b.toString(16));
240
-
241
- var o = this.readLength(this._offset + 1); // stored in `length`
242
- if (o === null)
243
- return null;
244
-
245
- if (this.length > 4)
246
- throw InvalidAsn1Error('Integer too long: ' + this.length);
247
-
248
- if (this.length > this._size - o)
249
- return null;
250
- this._offset = o;
251
-
252
- var fb = this._buf[this._offset];
253
- var value = 0;
254
-
255
- for (var i = 0; i < this.length; i++) {
256
- value <<= 8;
257
- value |= (this._buf[this._offset++] & 0xff);
258
- }
259
-
260
- if ((fb & 0x80) == 0x80 && i !== 4)
261
- value -= (1 << (i * 8));
262
-
263
- return value >> 0;
264
-};
265
-
266
-
267
-
268
-///--- Exported API
269
-
270
-module.exports = Reader;
collectors/node.d.plugin/node_modules/lib/ber/types.js
deleted
-35
@@ -1,35 +0,0 @@
1
-// SPDX-License-Identifier: MIT
2
-
3
-module.exports = {
4
- EOC: 0,
5
- Boolean: 1,
6
- Integer: 2,
7
- BitString: 3,
8
- OctetString: 4,
9
- Null: 5,
10
- OID: 6,
11
- ObjectDescriptor: 7,
12
- External: 8,
13
- Real: 9,
14
- Enumeration: 10,
15
- PDV: 11,
16
- Utf8String: 12,
17
- RelativeOID: 13,
18
- Sequence: 16,
19
- Set: 17,
20
- NumericString: 18,
21
- PrintableString: 19,
22
- T61String: 20,
23
- VideotexString: 21,
24
- IA5String: 22,
25
- UTCTime: 23,
26
- GeneralizedTime: 24,
27
- GraphicString: 25,
28
- VisibleString: 26,
29
- GeneralString: 28,
30
- UniversalString: 29,
31
- CharacterString: 30,
32
- BMPString: 31,
33
- Constructor: 32,
34
- Context: 128
35
-}
collectors/node.d.plugin/node_modules/lib/ber/writer.js
deleted
-318
@@ -1,318 +0,0 @@
1
-// SPDX-License-Identifier: MIT
2
-
3
-var assert = require('assert');
4
-var ASN1 = require('./types');
5
-var errors = require('./errors');
6
-
7
-
8
-///--- Globals
9
-
10
-var InvalidAsn1Error = errors.InvalidAsn1Error;
11
-
12
-var DEFAULT_OPTS = {
13
- size: 1024,
14
- growthFactor: 8
15
-};
16
-
17
-
18
-///--- Helpers
19
-
20
-function merge(from, to) {
21
- assert.ok(from);
22
- assert.equal(typeof(from), 'object');
23
- assert.ok(to);
24
- assert.equal(typeof(to), 'object');
25
-
26
- var keys = Object.getOwnPropertyNames(from);
27
- keys.forEach(function(key) {
28
- if (to[key])
29
- return;
30
-
31
- var value = Object.getOwnPropertyDescriptor(from, key);
32
- Object.defineProperty(to, key, value);
33
- });
34
-
35
- return to;
36
-}
37
-
38
-
39
-
40
-///--- API
41
-
42
-function Writer(options) {
43
- options = merge(DEFAULT_OPTS, options || {});
44
-
45
- this._buf = new Buffer(options.size || 1024);
46
- this._size = this._buf.length;
47
- this._offset = 0;
48
- this._options = options;
49
-
50
- // A list of offsets in the buffer where we need to insert
51
- // sequence tag/len pairs.
52
- this._seq = [];
53
-}
54
-
55
-Object.defineProperty(Writer.prototype, 'buffer', {
56
- get: function () {
57
- if (this._seq.length)
58
- throw new InvalidAsn1Error(this._seq.length + ' unended sequence(s)');
59
-
60
- return (this._buf.slice(0, this._offset));
61
- }
62
-});
63
-
64
-Writer.prototype.writeByte = function(b) {
65
- if (typeof(b) !== 'number')
66
- throw new TypeError('argument must be a Number');
67
-
68
- this._ensure(1);
69
- this._buf[this._offset++] = b;
70
-};
71
-
72
-
73
-Writer.prototype.writeInt = function(i, tag) {
74
- if (typeof(i) !== 'number')
75
- throw new TypeError('argument must be a Number');
76
- if (typeof(tag) !== 'number')
77
- tag = ASN1.Integer;
78
-
79
- var sz = 4;
80
-
81
- while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) &&
82
- (sz > 1)) {
83
- sz--;
84
- i <<= 8;
85
- }
86
-
87
- if (sz > 4)
88
- throw new InvalidAsn1Error('BER ints cannot be > 0xffffffff');
89
-
90
- this._ensure(2 + sz);
91
- this._buf[this._offset++] = tag;
92
- this._buf[this._offset++] = sz;
93
-
94
- while (sz-- > 0) {
95
- this._buf[this._offset++] = ((i & 0xff000000) >>> 24);
96
- i <<= 8;
97
- }
98
-
99
-};
100
-
101
-
102
-Writer.prototype.writeNull = function() {
103
- this.writeByte(ASN1.Null);
104
- this.writeByte(0x00);
105
-};
106
-
107
-
108
-Writer.prototype.writeEnumeration = function(i, tag) {
109
- if (typeof(i) !== 'number')
110
- throw new TypeError('argument must be a Number');
111
- if (typeof(tag) !== 'number')
112
- tag = ASN1.Enumeration;
113
-
114
- return this.writeInt(i, tag);
115
-};
116
-
117
-
118
-Writer.prototype.writeBoolean = function(b, tag) {
119
- if (typeof(b) !== 'boolean')
120
- throw new TypeError('argument must be a Boolean');
121
- if (typeof(tag) !== 'number')
122
- tag = ASN1.Boolean;
123
-
124
- this._ensure(3);
125
- this._buf[this._offset++] = tag;
126
- this._buf[this._offset++] = 0x01;
127
- this._buf[this._offset++] = b ? 0xff : 0x00;
128
-};
129
-
130
-
131
-Writer.prototype.writeString = function(s, tag) {
132
- if (typeof(s) !== 'string')
133
- throw new TypeError('argument must be a string (was: ' + typeof(s) + ')');
134
- if (typeof(tag) !== 'number')
135
- tag = ASN1.OctetString;
136
-
137
- var len = Buffer.byteLength(s);
138
- this.writeByte(tag);
139
- this.writeLength(len);
140
- if (len) {
141
- this._ensure(len);
142
- this._buf.write(s, this._offset);
143
- this._offset += len;
144
- }
145
-};
146
-
147
-
148
-Writer.prototype.writeBuffer = function(buf, tag) {
149
- if (!Buffer.isBuffer(buf))
150
- throw new TypeError('argument must be a buffer');
151
-
152
- // If no tag is specified we will assume `buf` already contains tag and length
153
- if (typeof(tag) === 'number') {
154
- this.writeByte(tag);
155
- this.writeLength(buf.length);
156
- }
157
-
158
- this._ensure(buf.length);
159
- buf.copy(this._buf, this._offset, 0, buf.length);
160
- this._offset += buf.length;
161
-};
162
-
163
-
164
-Writer.prototype.writeStringArray = function(strings, tag) {
165
- if (! (strings instanceof Array))
166
- throw new TypeError('argument must be an Array[String]');
167
-
168
- var self = this;
169
- strings.forEach(function(s) {
170
- self.writeString(s, tag);
171
- });
172
-};
173
-
174
-// This is really to solve DER cases, but whatever for now
175
-Writer.prototype.writeOID = function(s, tag) {
176
- if (typeof(s) !== 'string')
177
- throw new TypeError('argument must be a string');
178
- if (typeof(tag) !== 'number')
179
- tag = ASN1.OID;
180
-
181
- if (!/^([0-9]+\.){3,}[0-9]+$/.test(s))
182
- throw new Error('argument is not a valid OID string');
183
-
184
- function encodeOctet(bytes, octet) {
185
- if (octet < 128) {
186
- bytes.push(octet);
187
- } else if (octet < 16384) {
188
- bytes.push((octet >>> 7) | 0x80);
189
- bytes.push(octet & 0x7F);
190
- } else if (octet < 2097152) {
191
- bytes.push((octet >>> 14) | 0x80);
192
- bytes.push(((octet >>> 7) | 0x80) & 0xFF);
193
- bytes.push(octet & 0x7F);
194
- } else if (octet < 268435456) {
195
- bytes.push((octet >>> 21) | 0x80);
196
- bytes.push(((octet >>> 14) | 0x80) & 0xFF);
197
- bytes.push(((octet >>> 7) | 0x80) & 0xFF);
198
- bytes.push(octet & 0x7F);
199
- } else {
200
- bytes.push(((octet >>> 28) | 0x80) & 0xFF);
201
- bytes.push(((octet >>> 21) | 0x80) & 0xFF);
202
- bytes.push(((octet >>> 14) | 0x80) & 0xFF);
203
- bytes.push(((octet >>> 7) | 0x80) & 0xFF);
204
- bytes.push(octet & 0x7F);
205
- }
206
- }
207
-
208
- var tmp = s.split('.');
209
- var bytes = [];
210
- bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10));
211
- tmp.slice(2).forEach(function(b) {
212
- encodeOctet(bytes, parseInt(b, 10));
213
- });
214
-
215
- var self = this;
216
- this._ensure(2 + bytes.length);
217
- this.writeByte(tag);
218
- this.writeLength(bytes.length);
219
- bytes.forEach(function(b) {
220
- self.writeByte(b);
221
- });
222
-};
223
-
224
-
225
-Writer.prototype.writeLength = function(len) {
226
- if (typeof(len) !== 'number')
227
- throw new TypeError('argument must be a Number');
228
-
229
- this._ensure(4);
230
-
231
- if (len <= 0x7f) {
232
- this._buf[this._offset++] = len;
233
- } else if (len <= 0xff) {
234
- this._buf[this._offset++] = 0x81;
235
- this._buf[this._offset++] = len;
236
- } else if (len <= 0xffff) {
237
- this._buf[this._offset++] = 0x82;
238
- this._buf[this._offset++] = len >> 8;
239
- this._buf[this._offset++] = len;
240
- } else if (len <= 0xffffff) {
241
- this._buf[this._offset++] = 0x83;
242
- this._buf[this._offset++] = len >> 16;
243
- this._buf[this._offset++] = len >> 8;
244
- this._buf[this._offset++] = len;
245
- } else {
246
- throw new InvalidAsn1Error('Length too long (> 4 bytes)');
247
- }
248
-};
249
-
250
-Writer.prototype.startSequence = function(tag) {
251
- if (typeof(tag) !== 'number')
252
- tag = ASN1.Sequence | ASN1.Constructor;
253
-
254
- this.writeByte(tag);
255
- this._seq.push(this._offset);
256
- this._ensure(3);
257
- this._offset += 3;
258
-};
259
-
260
-
261
-Writer.prototype.endSequence = function() {
262
- var seq = this._seq.pop();
263
- var start = seq + 3;
264
- var len = this._offset - start;
265
-
266
- if (len <= 0x7f) {
267
- this._shift(start, len, -2);
268
- this._buf[seq] = len;
269
- } else if (len <= 0xff) {
270
- this._shift(start, len, -1);
271
- this._buf[seq] = 0x81;
272
- this._buf[seq + 1] = len;
273
- } else if (len <= 0xffff) {
274
- this._buf[seq] = 0x82;
275
- this._buf[seq + 1] = len >> 8;
276
- this._buf[seq + 2] = len;
277
- } else if (len <= 0xffffff) {
278
- this._shift(start, len, 1);
279
- this._buf[seq] = 0x83;
280
- this._buf[seq + 1] = len >> 16;
281
- this._buf[seq + 2] = len >> 8;
282
- this._buf[seq + 3] = len;
283
- } else {
284
- throw new InvalidAsn1Error('Sequence too long');
285
- }
286
-};
287
-
288
-
289
-Writer.prototype._shift = function(start, len, shift) {
290
- assert.ok(start !== undefined);
291
- assert.ok(len !== undefined);
292
- assert.ok(shift);
293
-
294
- this._buf.copy(this._buf, start + shift, start, start + len);
295
- this._offset += shift;
296
-};
297
-
298
-Writer.prototype._ensure = function(len) {
299
- assert.ok(len);
300
-
301
- if (this._size - this._offset < len) {
302
- var sz = this._size * this._options.growthFactor;
303
- if (sz - this._offset < len)
304
- sz += len;
305
-
306
- var buf = new Buffer(sz);
307
-
308
- this._buf.copy(buf, 0, 0, this._offset);
309
- this._buf = buf;
310
- this._size = sz;
311
- }
312
-};
313
-
314
-
315
-
316
-///--- Exported API
317
-
318
-module.exports = Writer;
collectors/node.d.plugin/node_modules/net-snmp.js
deleted
-3452
@@ -1,3452 +0,0 @@
1
-// Copyright 2013 Stephen Vickers <stephen.vickers.sv@gmail.com>
2
-// SPDX-License-Identifier: MIT
3
-
4
-var ber = require("asn1-ber").Ber;
5
-var dgram = require("dgram");
6
-var events = require("events");
7
-var util = require("util");
8
-var crypto = require("crypto");
9
-
10
-var DEBUG = false;
11
-
12
-var MAX_INT32 = 2147483647;
13
-
14
-function debug(line) {
15
- if (DEBUG) {
16
- console.debug(line);
17
- }
18
-}
19
-
20
-/*****************************************************************************
21
- ** Constants
22
- **/
23
-
24
-
25
-function _expandConstantObject(object) {
26
- var keys = [];
27
- for (var key in object)
28
- keys.push(key);
29
- for (var i = 0; i < keys.length; i++)
30
- object[object[keys[i]]] = parseInt(keys[i]);
31
-}
32
-
33
-var ErrorStatus = {
34
- 0: "NoError",
35
- 1: "TooBig",
36
- 2: "NoSuchName",
37
- 3: "BadValue",
38
- 4: "ReadOnly",
39
- 5: "GeneralError",
40
- 6: "NoAccess",
41
- 7: "WrongType",
42
- 8: "WrongLength",
43
- 9: "WrongEncoding",
44
- 10: "WrongValue",
45
- 11: "NoCreation",
46
- 12: "InconsistentValue",
47
- 13: "ResourceUnavailable",
48
- 14: "CommitFailed",
49
- 15: "UndoFailed",
50
- 16: "AuthorizationError",
51
- 17: "NotWritable",
52
- 18: "InconsistentName"
53
-};
54
-
55
-_expandConstantObject(ErrorStatus);
56
-
57
-var ObjectType = {
58
- 1: "Boolean",
59
- 2: "Integer",
60
- 4: "OctetString",
61
- 5: "Null",
62
- 6: "OID",
63
- 64: "IpAddress",
64
- 65: "Counter",
65
- 66: "Gauge",
66
- 67: "TimeTicks",
67
- 68: "Opaque",
68
- 70: "Counter64",
69
- 128: "NoSuchObject",
70
- 129: "NoSuchInstance",
71
- 130: "EndOfMibView"
72
-};
73
-
74
-_expandConstantObject(ObjectType);
75
-
76
-ObjectType.Integer32 = ObjectType.Integer;
77
-ObjectType.Counter32 = ObjectType.Counter;
78
-ObjectType.Gauge32 = ObjectType.Gauge;
79
-ObjectType.Unsigned32 = ObjectType.Gauge32;
80
-
81
-var PduType = {
82
- 160: "GetRequest",
83
- 161: "GetNextRequest",
84
- 162: "GetResponse",
85
- 163: "SetRequest",
86
- 164: "Trap",
87
- 165: "GetBulkRequest",
88
- 166: "InformRequest",
89
- 167: "TrapV2",
90
- 168: "Report"
91
-};
92
-
93
-_expandConstantObject(PduType);
94
-
95
-var TrapType = {
96
- 0: "ColdStart",
97
- 1: "WarmStart",
98
- 2: "LinkDown",
99
- 3: "LinkUp",
100
- 4: "AuthenticationFailure",
101
- 5: "EgpNeighborLoss",
102
- 6: "EnterpriseSpecific"
103
-};
104
-
105
-_expandConstantObject(TrapType);
106
-
107
-var SecurityLevel = {
108
- 1: "noAuthNoPriv",
109
- 2: "authNoPriv",
110
- 3: "authPriv"
111
-};
112
-
113
-_expandConstantObject(SecurityLevel);
114
-
115
-var AuthProtocols = {
116
- "1": "none",
117
- "2": "md5",
118
- "3": "sha"
119
-};
120
-
121
-_expandConstantObject(AuthProtocols);
122
-
123
-var PrivProtocols = {
124
- "1": "none",
125
- "2": "des"
126
-};
127
-
128
-_expandConstantObject(PrivProtocols);
129
-
130
-var MibProviderType = {
131
- "1": "Scalar",
132
- "2": "Table"
133
-};
134
-
135
-_expandConstantObject(MibProviderType);
136
-
137
-var Version1 = 0;
138
-var Version2c = 1;
139
-var Version3 = 3;
140
-
141
-var Version = {
142
- "1": Version1,
143
- "2c": Version2c,
144
- "3": Version3
145
-};
146
-
147
-/*****************************************************************************
148
- ** Exception class definitions
149
- **/
150
-
151
-function ResponseInvalidError(message) {
152
- this.name = "ResponseInvalidError";
153
- this.message = message;
154
- Error.captureStackTrace(this, ResponseInvalidError);
155
-}
156
-
157
-util.inherits(ResponseInvalidError, Error);
158
-
159
-function RequestInvalidError(message) {
160
- this.name = "RequestInvalidError";
161
- this.message = message;
162
- Error.captureStackTrace(this, RequestInvalidError);
163
-}
164
-
165
-util.inherits(RequestInvalidError, Error);
166
-
167
-function RequestFailedError(message, status) {
168
- this.name = "RequestFailedError";
169
- this.message = message;
170
- this.status = status;
171
- Error.captureStackTrace(this, RequestFailedError);
172
-}
173
-
174
-util.inherits(RequestFailedError, Error);
175
-
176
-function RequestTimedOutError(message) {
177
- this.name = "RequestTimedOutError";
178
- this.message = message;
179
- Error.captureStackTrace(this, RequestTimedOutError);
180
-}
181
-
182
-util.inherits(RequestTimedOutError, Error);
183
-
184
-/*****************************************************************************
185
- ** OID and varbind helper functions
186
- **/
187
-
188
-function isVarbindError(varbind) {
189
- return !!(varbind.type == ObjectType.NoSuchObject
190
- || varbind.type == ObjectType.NoSuchInstance
191
- || varbind.type == ObjectType.EndOfMibView);
192
-}
193
-
194
-function varbindError(varbind) {
195
- return (ObjectType[varbind.type] || "NotAnError") + ": " + varbind.oid;
196
-}
197
-
198
-function oidFollowsOid(oidString, nextString) {
199
- var oid = {str: oidString, len: oidString.length, idx: 0};
200
- var next = {str: nextString, len: nextString.length, idx: 0};
201
- var dotCharCode = ".".charCodeAt(0);
202
-
203
- function getNumber(item) {
204
- var n = 0;
205
- if (item.idx >= item.len)
206
- return null;
207
- while (item.idx < item.len) {
208
- var charCode = item.str.charCodeAt(item.idx++);
209
- if (charCode == dotCharCode)
210
- return n;
211
- n = (n ? (n * 10) : n) + (charCode - 48);
212
- }
213
- return n;
214
- }
215
-
216
- while (1) {
217
- var oidNumber = getNumber(oid);
218
- var nextNumber = getNumber(next);
219
-
220
- if (oidNumber !== null) {
221
- if (nextNumber !== null) {
222
- if (nextNumber > oidNumber) {
223
- return true;
224
- } else if (nextNumber < oidNumber) {
225
- return false;
226
- }
227
- } else {
228
- return true;
229
- }
230
- } else {
231
- return true;
232
- }
233
- }
234
-}
235
-
236
-function oidInSubtree(oidString, nextString) {
237
- var oid = oidString.split(".");
238
- var next = nextString.split(".");
239
-
240
- if (oid.length > next.length)
241
- return false;
242
-
243
- for (var i = 0; i < oid.length; i++) {
244
- if (next[i] != oid[i])
245
- return false;
246
- }
247
-
248
- return true;
249
-}
250
-
251
-/**
252
- ** Some SNMP agents produce integers on the wire such as 00 ff ff ff ff.
253
- ** The ASN.1 BER parser we use throws an error when parsing this, which we
254
- ** believe is correct. So, we decided not to bother the "asn1" developer(s)
255
- ** with this, instead opting to work around it here.
256
- **
257
- ** If an integer is 5 bytes in length we check if the first byte is 0, and if so
258
- ** simply drop it and parse it like it was a 4 byte integer, otherwise throw
259
- ** an error since the integer is too large.
260
- **/
261
-
262
-function readInt(buffer) {
263
- return readUint(buffer, true);
264
-}
265
-
266
-function readIpAddress(buffer) {
267
- var bytes = buffer.readString(ObjectType.IpAddress, true);
268
- if (bytes.length != 4)
269
- throw new ResponseInvalidError("Length '" + bytes.length
270
- + "' of IP address '" + bytes.toString("hex")
271
- + "' is not 4");
272
- var value = bytes[0] + "." + bytes[1] + "." + bytes[2] + "." + bytes[3];
273
- return value;
274
-}
275
-
276
-function readUint(buffer, isSigned) {
277
- buffer.readByte();
278
- var length = buffer.readByte();
279
- var value = 0;
280
- var signedBitSet = false;
281
-
282
- if (length > 5) {
283
- throw new RangeError("Integer too long '" + length + "'");
284
- } else if (length == 5) {
285
- if (buffer.readByte() !== 0)
286
- throw new RangeError("Integer too long '" + length + "'");
287
- length = 4;
288
- }
289
-
290
- for (var i = 0; i < length; i++) {
291
- value *= 256;
292
- value += buffer.readByte();
293
-
294
- if (isSigned && i <= 0) {
295
- if ((value & 0x80) == 0x80)
296
- signedBitSet = true;
297
- }
298
- }
299
-
300
- if (signedBitSet)
301
- value -= (1 << (i * 8));
302
-
303
- return value;
304
-}
305
-
306
-function readUint64(buffer) {
307
- var value = buffer.readString(ObjectType.Counter64, true);
308
-
309
- return value;
310
-}
311
-
312
-function readVarbinds(buffer, varbinds) {
313
- buffer.readSequence();
314
-
315
- while (1) {
316
- buffer.readSequence();
317
- if (buffer.peek() != ObjectType.OID)
318
- break;
319
- var oid = buffer.readOID();
320
- var type = buffer.peek();
321
-
322
- if (type == null)
323
- break;
324
-
325
- var value;
326
-
327
- if (type == ObjectType.Boolean) {
328
- value = buffer.readBoolean();
329
- } else if (type == ObjectType.Integer) {
330
- value = readInt(buffer);
331
- } else if (type == ObjectType.OctetString) {
332
- value = buffer.readString(null, true);
333
- } else if (type == ObjectType.Null) {
334
- buffer.readByte();
335
- buffer.readByte();
336
- value = null;
337
- } else if (type == ObjectType.OID) {
338
- value = buffer.readOID();
339
- } else if (type == ObjectType.IpAddress) {
340
- var bytes = buffer.readString(ObjectType.IpAddress, true);
341
- if (bytes.length != 4)
342
- throw new ResponseInvalidError("Length '" + bytes.length
343
- + "' of IP address '" + bytes.toString("hex")
344
- + "' is not 4");
345
- value = bytes[0] + "." + bytes[1] + "." + bytes[2] + "." + bytes[3];
346
- } else if (type == ObjectType.Counter) {
347
- value = readUint(buffer);
348
- } else if (type == ObjectType.Gauge) {
349
- value = readUint(buffer);
350
- } else if (type == ObjectType.TimeTicks) {
351
- value = readUint(buffer);
352
- } else if (type == ObjectType.Opaque) {
353
- value = buffer.readString(ObjectType.Opaque, true);
354
- } else if (type == ObjectType.Counter64) {
355
- value = readUint64(buffer);
356
- } else if (type == ObjectType.NoSuchObject) {
357
- buffer.readByte();
358
- buffer.readByte();
359
- value = null;
360
- } else if (type == ObjectType.NoSuchInstance) {
361
- buffer.readByte();
362
- buffer.readByte();
363
- value = null;
364
- } else if (type == ObjectType.EndOfMibView) {
365
- buffer.readByte();
366
- buffer.readByte();
367
- value = null;
368
- } else {
369
- throw new ResponseInvalidError("Unknown type '" + type
370
- + "' in response");
371
- }
372
-
373
- varbinds.push({
374
- oid: oid,
375
- type: type,
376
- value: value
377
- });
378
- }
379
-}
380
-
381
-function writeUint(buffer, type, value) {
382
- var b = Buffer.alloc(4);
383
- b.writeUInt32BE(value, 0);
384
- buffer.writeBuffer(b, type);
385
-}
386
-
387
-function writeUint64(buffer, value) {
388
- buffer.writeBuffer(value, ObjectType.Counter64);
389
-}
390
-
391
-function writeVarbinds(buffer, varbinds) {
392
- buffer.startSequence();
393
- for (var i = 0; i < varbinds.length; i++) {
394
- buffer.startSequence();
395
- buffer.writeOID(varbinds[i].oid);
396
-
397
- if (varbinds[i].type && varbinds[i].hasOwnProperty("value")) {
398
- var type = varbinds[i].type;
399
- var value = varbinds[i].value;
400
-
401
- if (type == ObjectType.Boolean) {
402
- buffer.writeBoolean(value ? true : false);
403
- } else if (type == ObjectType.Integer) { // also Integer32
404
- buffer.writeInt(value);
405
- } else if (type == ObjectType.OctetString) {
406
- if (typeof value == "string")
407
- buffer.writeString(value);
408
- else
409
- buffer.writeBuffer(value, ObjectType.OctetString);
410
- } else if (type == ObjectType.Null) {
411
- buffer.writeNull();
412
- } else if (type == ObjectType.OID) {
413
- buffer.writeOID(value);
414
- } else if (type == ObjectType.IpAddress) {
415
- var bytes = value.split(".");
416
- if (bytes.length != 4)
417
- throw new RequestInvalidError("Invalid IP address '"
418
- + value + "'");
419
- buffer.writeBuffer(Buffer.from(bytes), 64);
420
- } else if (type == ObjectType.Counter) { // also Counter32
421
- writeUint(buffer, ObjectType.Counter, value);
422
- } else if (type == ObjectType.Gauge) { // also Gauge32 & Unsigned32
423
- writeUint(buffer, ObjectType.Gauge, value);
424
- } else if (type == ObjectType.TimeTicks) {
425
- writeUint(buffer, ObjectType.TimeTicks, value);
426
- } else if (type == ObjectType.Opaque) {
427
- buffer.writeBuffer(value, ObjectType.Opaque);
428
- } else if (type == ObjectType.Counter64) {
429
- writeUint64(buffer, value);
430
- } else if (type == ObjectType.EndOfMibView) {
431
- buffer.writeByte(130);
432
- buffer.writeByte(0);
433
- } else {
434
- throw new RequestInvalidError("Unknown type '" + type
435
- + "' in request");
436
- }
437
- } else {
438
- buffer.writeNull();
439
- }
440
-
441
- buffer.endSequence();
442
- }
443
- buffer.endSequence();
444
-}
445
-
446
-/*****************************************************************************
447
- ** PDU class definitions
448
- **/
449
-
450
-var SimplePdu = function () {
451
-};
452
-
453
-SimplePdu.prototype.toBuffer = function (buffer) {
454
- buffer.startSequence(this.type);
455
-
456
- buffer.writeInt(this.id);
457
- buffer.writeInt((this.type == PduType.GetBulkRequest)
458
- ? (this.options.nonRepeaters || 0)
459
- : 0);
460
- buffer.writeInt((this.type == PduType.GetBulkRequest)
461
- ? (this.options.maxRepetitions || 0)
462
- : 0);
463
-
464
- writeVarbinds(buffer, this.varbinds);
465
-
466
- buffer.endSequence();
467
-};
468
-
469
-SimplePdu.prototype.initializeFromVariables = function (id, varbinds, options) {
470
- this.id = id;
471
- this.varbinds = varbinds;
472
- this.options = options || {};
473
- this.contextName = (options && options.context) ? options.context : "";
474
-}
475
-
476
-SimplePdu.prototype.initializeFromBuffer = function (reader) {
477
- this.type = reader.peek();
478
- reader.readSequence();
479
-
480
- this.id = reader.readInt();
481
- this.nonRepeaters = reader.readInt();
482
- this.maxRepetitions = reader.readInt();
483
-
484
- this.varbinds = [];
485
- readVarbinds(reader, this.varbinds);
486
-
487
-};
488
-
489
-SimplePdu.prototype.getResponsePduForRequest = function () {
490
- var responsePdu = GetResponsePdu.createFromVariables(this.id, [], {});
491
- if (this.contextEngineID) {
492
- responsePdu.contextEngineID = this.contextEngineID;
493
- responsePdu.contextName = this.contextName;
494
- }
495
- return responsePdu;
496
-};
497
-
498
-SimplePdu.createFromVariables = function (pduClass, id, varbinds, options) {
499
- var pdu = new pduClass(id, varbinds, options);
500
- pdu.id = id;
501
- pdu.varbinds = varbinds;
502
- pdu.options = options || {};
503
- pdu.contextName = (options && options.context) ? options.context : "";
504
- return pdu;
505
-};
506
-
507
-var GetBulkRequestPdu = function () {
508
- this.type = PduType.GetBulkRequest;
509
- GetBulkRequestPdu.super_.apply(this, arguments);
510
-};
511
-
512
-util.inherits(GetBulkRequestPdu, SimplePdu);
513
-
514
-GetBulkRequestPdu.createFromBuffer = function (reader) {
515
- var pdu = new GetBulkRequestPdu();
516
- pdu.initializeFromBuffer(reader);
517
- return pdu;
518
-};
519
-
520
-var GetNextRequestPdu = function () {
521
- this.type = PduType.GetNextRequest;
522
- GetNextRequestPdu.super_.apply(this, arguments);
523
-};
524
-
525
-util.inherits(GetNextRequestPdu, SimplePdu);
526
-
527
-GetNextRequestPdu.createFromBuffer = function (reader) {
528
- var pdu = new GetNextRequestPdu();
529
- pdu.initializeFromBuffer(reader);
530
- return pdu;
531
-};
532
-
533
-var GetRequestPdu = function () {
534
- this.type = PduType.GetRequest;
535
- GetRequestPdu.super_.apply(this, arguments);
536
-};
537
-
538
-util.inherits(GetRequestPdu, SimplePdu);
539
-
540
-GetRequestPdu.createFromBuffer = function (reader) {
541
- var pdu = new GetRequestPdu();
542
- pdu.initializeFromBuffer(reader);
543
- return pdu;
544
-};
545
-
546
-GetRequestPdu.createFromVariables = function (id, varbinds, options) {
547
- var pdu = new GetRequestPdu();
548
- pdu.initializeFromVariables(id, varbinds, options);
549
- return pdu;
550
-};
551
-
552
-var InformRequestPdu = function () {
553
- this.type = PduType.InformRequest;
554
- InformRequestPdu.super_.apply(this, arguments);
555
-};
556
-
557
-util.inherits(InformRequestPdu, SimplePdu);
558
-
559
-InformRequestPdu.createFromBuffer = function (reader) {
560
- var pdu = new InformRequestPdu();
561
- pdu.initializeFromBuffer(reader);
562
- return pdu;
563
-};
564
-
565
-var SetRequestPdu = function () {
566
- this.type = PduType.SetRequest;
567
- SetRequestPdu.super_.apply(this, arguments);
568
-};
569
-
570
-util.inherits(SetRequestPdu, SimplePdu);
571
-
572
-SetRequestPdu.createFromBuffer = function (reader) {
573
- var pdu = new SetRequestPdu();
574
- pdu.initializeFromBuffer(reader);
575
- return pdu;
576
-};
577
-
578
-var TrapPdu = function () {
579
- this.type = PduType.Trap;
580
-};
581
-
582
-TrapPdu.prototype.toBuffer = function (buffer) {
583
- buffer.startSequence(this.type);
584
-
585
- buffer.writeOID(this.enterprise);
586
- buffer.writeBuffer(Buffer.from(this.agentAddr.split(".")),
587
- ObjectType.IpAddress);
588
- buffer.writeInt(this.generic);
589
- buffer.writeInt(this.specific);
590
- writeUint(buffer, ObjectType.TimeTicks,
591
- this.upTime || Math.floor(process.uptime() * 100));
592
-
593
- writeVarbinds(buffer, this.varbinds);
594
-
595
- buffer.endSequence();
596
-};
597
-
598
-TrapPdu.createFromBuffer = function (reader) {
599
- var pdu = new TrapPdu();
600
- reader.readSequence();
601
-
602
- pdu.enterprise = reader.readOID();
603
- pdu.agentAddr = readIpAddress(reader);
604
- pdu.generic = reader.readInt();
605
- pdu.specific = reader.readInt();
606
- pdu.upTime = readUint(reader)
607
-
608
- pdu.varbinds = [];
609
- readVarbinds(reader, pdu.varbinds);
610
-
611
- return pdu;
612
-};
613
-
614
-TrapPdu.createFromVariables = function (typeOrOid, varbinds, options) {
615
- var pdu = new TrapPdu();
616
- pdu.agentAddr = options.agentAddr || "127.0.0.1";
617
- pdu.upTime = options.upTime;
618
-
619
- if (typeof typeOrOid == "string") {
620
- pdu.generic = TrapType.EnterpriseSpecific;
621
- pdu.specific = parseInt(typeOrOid.match(/\.(\d+)$/)[1]);
622
- pdu.enterprise = typeOrOid.replace(/\.(\d+)$/, "");
623
- } else {
624
- pdu.generic = typeOrOid;
625
- pdu.specific = 0;
626
- pdu.enterprise = "1.3.6.1.4.1";
627
- }
628
-
629
- pdu.varbinds = varbinds;
630
-
631
- return pdu;
632
-};
633
-
634
-var TrapV2Pdu = function () {
635
- this.type = PduType.TrapV2;
636
- TrapV2Pdu.super_.apply(this, arguments);
637
-};
638
-
639
-util.inherits(TrapV2Pdu, SimplePdu);
640
-
641
-TrapV2Pdu.createFromBuffer = function (reader) {
642
- var pdu = new TrapV2Pdu();
643
- pdu.initializeFromBuffer(reader);
644
- return pdu;
645
-};
646
-
647
-TrapV2Pdu.createFromVariables = function (id, varbinds, options) {
648
- var pdu = new TrapV2Pdu();
649
- pdu.initializeFromVariables(id, varbinds, options);
650
- return pdu;
651
-};
652
-
653
-var SimpleResponsePdu = function () {
654
-};
655
-
656
-SimpleResponsePdu.prototype.toBuffer = function (writer) {
657
- writer.startSequence(this.type);
658
-
659
- writer.writeInt(this.id);
660
- writer.writeInt(this.errorStatus || 0);
661
- writer.writeInt(this.errorIndex || 0);
662
- writeVarbinds(writer, this.varbinds);
663
- writer.endSequence();
664
-
665
-};
666
-
667
-SimpleResponsePdu.prototype.initializeFromBuffer = function (reader) {
668
- reader.readSequence(this.type);
669
-
670
- this.id = reader.readInt();
671
- this.errorStatus = reader.readInt();
672
- this.errorIndex = reader.readInt();
673
-
674
- this.varbinds = [];
675
- readVarbinds(reader, this.varbinds);
676
-};
677
-
678
-SimpleResponsePdu.prototype.initializeFromVariables = function (id, varbinds, options) {
679
- this.id = id;
680
- this.varbinds = varbinds;
681
- this.options = options || {};
682
-};
683
-
684
-var GetResponsePdu = function () {
685
- this.type = PduType.GetResponse;
686
- GetResponsePdu.super_.apply(this, arguments);
687
-};
688
-
689
-util.inherits(GetResponsePdu, SimpleResponsePdu);
690
-
691
-GetResponsePdu.createFromBuffer = function (reader) {
692
- var pdu = new GetResponsePdu();
693
- pdu.initializeFromBuffer(reader);
694
- return pdu;
695
-};
696
-
697
-GetResponsePdu.createFromVariables = function (id, varbinds, options) {
698
- var pdu = new GetResponsePdu();
699
- pdu.initializeFromVariables(id, varbinds, options);
700
- return pdu;
701
-};
702
-
703
-var ReportPdu = function () {
704
- this.type = PduType.Report;
705
- ReportPdu.super_.apply(this, arguments);
706
-};
707
-
708
-util.inherits(ReportPdu, SimpleResponsePdu);
709
-
710
-ReportPdu.createFromBuffer = function (reader) {
711
- var pdu = new ReportPdu();
712
- pdu.initializeFromBuffer(reader);
713
- return pdu;
714
-};
715
-
716
-ReportPdu.createFromVariables = function (id, varbinds, options) {
717
- var pdu = new ReportPdu();
718
- pdu.initializeFromVariables(id, varbinds, options);
719
- return pdu;
720
-};
721
-
722
-var readPdu = function (reader, scoped) {
723
- var pdu;
724
- var contextEngineID;
725
- var contextName;
726
- if (scoped) {
727
- reader.readSequence();
728
- contextEngineID = reader.readString(ber.OctetString, true);
729
- contextName = reader.readString();
730
- }
731
- var type = reader.peek();
732
-
733
- if (type == PduType.GetResponse) {
734
- pdu = GetResponsePdu.createFromBuffer(reader);
735
- } else if (type == PduType.Report) {
736
- pdu = ReportPdu.createFromBuffer(reader);
737
- } else if (type == PduType.Trap) {
738
- pdu = TrapPdu.createFromBuffer(reader);
739
- } else if (type == PduType.TrapV2) {
740
- pdu = TrapV2Pdu.createFromBuffer(reader);
741
- } else if (type == PduType.InformRequest) {
742
- pdu = InformRequestPdu.createFromBuffer(reader);
743
- } else if (type == PduType.GetRequest) {
744
- pdu = GetRequestPdu.createFromBuffer(reader);
745
- } else if (type == PduType.SetRequest) {
746
- pdu = SetRequestPdu.createFromBuffer(reader);
747
- } else if (type == PduType.GetNextRequest) {
748
- pdu = GetNextRequestPdu.createFromBuffer(reader);
749
- } else if (type == PduType.GetBulkRequest) {
750
- pdu = GetBulkRequestPdu.createFromBuffer(reader);
751
- } else {
752
- throw new ResponseInvalidError("Unknown PDU type '" + type
753
- + "' in response");
754
- }
755
- if (scoped) {
756
- pdu.contextEngineID = contextEngineID;
757
- pdu.contextName = contextName;
758
- }
759
- pdu.scoped = scoped;
760
- return pdu;
761
-};
762
-
763
-var createDiscoveryPdu = function (context) {
764
- return GetRequestPdu.createFromVariables(_generateId(), [], {context: context});
765
-};
766
-
767
-var Authentication = {};
768
-
769
-Authentication.HMAC_BUFFER_SIZE = 1024 * 1024;
770
-Authentication.HMAC_BLOCK_SIZE = 64;
771
-Authentication.AUTHENTICATION_CODE_LENGTH = 12;
772
-Authentication.AUTH_PARAMETERS_PLACEHOLDER = Buffer.from('8182838485868788898a8b8c', 'hex');
773
-
774
-Authentication.algorithms = {};
775
-
776
-Authentication.algorithms[AuthProtocols.md5] = {
777
- // KEY_LENGTH: 16,
778
- CRYPTO_ALGORITHM: 'md5'
779
-};
780
-
781
-Authentication.algorithms[AuthProtocols.sha] = {
782
- // KEY_LENGTH: 20,
783
- CRYPTO_ALGORITHM: 'sha1'
784
-};
785
-
786
-// Adapted from RFC3414 Appendix A.2.1. Password to Key Sample Code for MD5
787
-Authentication.passwordToKey = function (authProtocol, authPasswordString, engineID) {
788
- var hashAlgorithm;
789
- var firstDigest;
790
- var finalDigest;
791
- var buf = Buffer.alloc(Authentication.HMAC_BUFFER_SIZE);
792
- var bufOffset = 0;
793
- var passwordIndex = 0;
794
- var count = 0;
795
- var password = Buffer.from(authPasswordString);
796
- var cryptoAlgorithm = Authentication.algorithms[authProtocol].CRYPTO_ALGORITHM;
797
-
798
- while (count < Authentication.HMAC_BUFFER_SIZE) {
799
- for (var i = 0; i < Authentication.HMAC_BLOCK_SIZE; i++) {
800
- buf.writeUInt8(password[passwordIndex++ % password.length], bufOffset++);
801
- }
802
- count += Authentication.HMAC_BLOCK_SIZE;
803
- }
804
- hashAlgorithm = crypto.createHash(cryptoAlgorithm);
805
- hashAlgorithm.update(buf);
806
- firstDigest = hashAlgorithm.digest();
807
- // debug ("First digest: " + firstDigest.toString('hex'));
808
-
809
- hashAlgorithm = crypto.createHash(cryptoAlgorithm);
810
- hashAlgorithm.update(firstDigest);
811
- hashAlgorithm.update(engineID);
812
- hashAlgorithm.update(firstDigest);
813
- finalDigest = hashAlgorithm.digest();
814
- debug("Localized key: " + finalDigest.toString('hex'));
815
-
816
- return finalDigest;
817
-};
818
-
819
-Authentication.addParametersToMessageBuffer = function (messageBuffer, authProtocol, authPassword, engineID) {
820
- var authenticationParametersOffset;
821
- var digestToAdd;
822
-
823
- // clear the authenticationParameters field in message
824
- authenticationParametersOffset = messageBuffer.indexOf(Authentication.AUTH_PARAMETERS_PLACEHOLDER);
825
- messageBuffer.fill(0, authenticationParametersOffset, authenticationParametersOffset + Authentication.AUTHENTICATION_CODE_LENGTH);
826
-
827
- digestToAdd = Authentication.calculateDigest(messageBuffer, authProtocol, authPassword, engineID);
828
- digestToAdd.copy(messageBuffer, authenticationParametersOffset, 0, Authentication.AUTHENTICATION_CODE_LENGTH);
829
- debug("Added Auth Parameters: " + digestToAdd.toString('hex'));
830
-};
831
-
832
-Authentication.isAuthentic = function (messageBuffer, authProtocol, authPassword, engineID, digestInMessage) {
833
- var authenticationParametersOffset;
834
- var calculatedDigest;
835
-
836
- // clear the authenticationParameters field in message
837
- authenticationParametersOffset = messageBuffer.indexOf(digestInMessage);
838
- messageBuffer.fill(0, authenticationParametersOffset, authenticationParametersOffset + Authentication.AUTHENTICATION_CODE_LENGTH);
839
-
840
- calculatedDigest = Authentication.calculateDigest(messageBuffer, authProtocol, authPassword, engineID);
841
-
842
- // replace previously cleared authenticationParameters field in message
843
- digestInMessage.copy(messageBuffer, authenticationParametersOffset, 0, Authentication.AUTHENTICATION_CODE_LENGTH);
844
-
845
- debug("Digest in message: " + digestInMessage.toString('hex'));
846
- debug("Calculated digest: " + calculatedDigest.toString('hex'));
847
- return calculatedDigest.equals(digestInMessage, Authentication.AUTHENTICATION_CODE_LENGTH);
848
-};
849
-
850
-Authentication.calculateDigest = function (messageBuffer, authProtocol, authPassword, engineID) {
851
- var authKey = Authentication.passwordToKey(authProtocol, authPassword, engineID);
852
-
853
- // Adapted from RFC3147 Section 6.3.1. Processing an Outgoing Message
854
- var hashAlgorithm;
855
- var kIpad;
856
- var kOpad;
857
- var firstDigest;
858
- var finalDigest;
859
- var truncatedDigest;
860
- var i;
861
- var cryptoAlgorithm = Authentication.algorithms[authProtocol].CRYPTO_ALGORITHM;
862
-
863
- if (authKey.length > Authentication.HMAC_BLOCK_SIZE) {
864
- hashAlgorithm = crypto.createHash(cryptoAlgorithm);
865
- hashAlgorithm.update(authKey);
866
- authKey = hashAlgorithm.digest();
867
- }
868
-
869
- // MD(K XOR opad, MD(K XOR ipad, msg))
870
- kIpad = Buffer.alloc(Authentication.HMAC_BLOCK_SIZE);
871
- kOpad = Buffer.alloc(Authentication.HMAC_BLOCK_SIZE);
872
- for (i = 0; i < authKey.length; i++) {
873
- kIpad[i] = authKey[i] ^ 0x36;
874
- kOpad[i] = authKey[i] ^ 0x5c;
875
- }
876
- kIpad.fill(0x36, authKey.length);
877
- kOpad.fill(0x5c, authKey.length);
878
-
879
- // inner MD
880
- hashAlgorithm = crypto.createHash(cryptoAlgorithm);
881
- hashAlgorithm.update(kIpad);
882
- hashAlgorithm.update(messageBuffer);
883
- firstDigest = hashAlgorithm.digest();
884
- // outer MD
885
- hashAlgorithm = crypto.createHash(cryptoAlgorithm);
886
- hashAlgorithm.update(kOpad);
887
- hashAlgorithm.update(firstDigest);
888
- finalDigest = hashAlgorithm.digest();
889
-
890
- truncatedDigest = Buffer.alloc(Authentication.AUTHENTICATION_CODE_LENGTH);
891
- finalDigest.copy(truncatedDigest, 0, 0, Authentication.AUTHENTICATION_CODE_LENGTH);
892
- return truncatedDigest;
893
-};
894
-
895
-var Encryption = {};
896
-
897
-Encryption.INPUT_KEY_LENGTH = 16;
898
-Encryption.DES_KEY_LENGTH = 8;
899
-Encryption.DES_BLOCK_LENGTH = 8;
900
-Encryption.CRYPTO_DES_ALGORITHM = 'des-cbc';
901
-Encryption.PRIV_PARAMETERS_PLACEHOLDER = Buffer.from('9192939495969798', 'hex');
902
-
903
-Encryption.encryptPdu = function (scopedPdu, privProtocol, privPassword, authProtocol, engineID) {
904
- var privLocalizedKey;
905
- var encryptionKey;
906
- var preIv;
907
- var salt;
908
- var iv;
909
- var i;
910
- var paddedScopedPduLength;
911
- var paddedScopedPdu;
912
- var encryptedPdu;
913
- var cbcProtocol = Encryption.CRYPTO_DES_ALGORITHM;
914
-
915
- privLocalizedKey = Authentication.passwordToKey(authProtocol, privPassword, engineID);
916
- encryptionKey = Buffer.alloc(Encryption.DES_KEY_LENGTH);
917
- privLocalizedKey.copy(encryptionKey, 0, 0, Encryption.DES_KEY_LENGTH);
918
- preIv = Buffer.alloc(Encryption.DES_BLOCK_LENGTH);
919
- privLocalizedKey.copy(preIv, 0, Encryption.DES_KEY_LENGTH, Encryption.DES_KEY_LENGTH + Encryption.DES_BLOCK_LENGTH);
920
-
921
- salt = Buffer.alloc(Encryption.DES_BLOCK_LENGTH);
922
- // set local SNMP engine boots part of salt to 1, as we have no persistent engine state
923
- salt.fill('00000001', 0, 4, 'hex');
924
- // set local integer part of salt to random
925
- salt.fill(crypto.randomBytes(4), 4, 8);
926
- iv = Buffer.alloc(Encryption.DES_BLOCK_LENGTH);
927
- for (i = 0; i < iv.length; i++) {
928
- iv[i] = preIv[i] ^ salt[i];
929
- }
930
-
931
- if (scopedPdu.length % Encryption.DES_BLOCK_LENGTH == 0) {
932
- paddedScopedPdu = scopedPdu;
933
- } else {
934
- paddedScopedPduLength = Encryption.DES_BLOCK_LENGTH * (Math.floor(scopedPdu.length / Encryption.DES_BLOCK_LENGTH) + 1);
935
- paddedScopedPdu = Buffer.alloc(paddedScopedPduLength);
936
- scopedPdu.copy(paddedScopedPdu, 0, 0, scopedPdu.length);
937
- }
938
- cipher = crypto.createCipheriv(cbcProtocol, encryptionKey, iv);
939
- encryptedPdu = cipher.update(paddedScopedPdu);
940
- encryptedPdu = Buffer.concat([encryptedPdu, cipher.final()]);
941
- debug("Key: " + encryptionKey.toString('hex'));
942
- debug("IV: " + iv.toString('hex'));
943
- debug("Plain: " + paddedScopedPdu.toString('hex'));
944
- debug("Encrypted: " + encryptedPdu.toString('hex'));
945
-
946
- return {
947
- encryptedPdu: encryptedPdu,
948
- msgPrivacyParameters: salt
949
- };
950
-};
951
-
952
-Encryption.decryptPdu = function (encryptedPdu, privProtocol, privParameters, privPassword, authProtocol, engineID, forceAutoPaddingDisable) {
953
- var privLocalizedKey;
954
- var decryptionKey;
955
- var preIv;
956
- var salt;
957
- var iv;
958
- var i;
959
- var decryptedPdu;
960
- var cbcProtocol = Encryption.CRYPTO_DES_ALGORITHM;
961
- ;
962
-
963
- privLocalizedKey = Authentication.passwordToKey(authProtocol, privPassword, engineID);
964
- decryptionKey = Buffer.alloc(Encryption.DES_KEY_LENGTH);
965
- privLocalizedKey.copy(decryptionKey, 0, 0, Encryption.DES_KEY_LENGTH);
966
- preIv = Buffer.alloc(Encryption.DES_BLOCK_LENGTH);
967
- privLocalizedKey.copy(preIv, 0, Encryption.DES_KEY_LENGTH, Encryption.DES_KEY_LENGTH + Encryption.DES_BLOCK_LENGTH);
968
-
969
- salt = privParameters;
970
- iv = Buffer.alloc(Encryption.DES_BLOCK_LENGTH);
971
- for (i = 0; i < iv.length; i++) {
972
- iv[i] = preIv[i] ^ salt[i];
973
- }
974
-
975
- decipher = crypto.createDecipheriv(cbcProtocol, decryptionKey, iv);
976
- if (forceAutoPaddingDisable) {
977
- decipher.setAutoPadding(false);
978
- }
979
- decryptedPdu = decipher.update(encryptedPdu);
980
- // This try-catch is a workaround for a seemingly incorrect error condition
981
- // - where sometimes a decrypt error is thrown with decipher.final()
982
- // It replaces this line which should have been sufficient:
983
- // decryptedPdu = Buffer.concat ([decryptedPdu, decipher.final()]);
984
- try {
985
- decryptedPdu = Buffer.concat([decryptedPdu, decipher.final()]);
986
- } catch (error) {
987
- // debug("Decrypt error: " + error);
988
- decipher = crypto.createDecipheriv(cbcProtocol, decryptionKey, iv);
989
- decipher.setAutoPadding(false);
990
- decryptedPdu = decipher.update(encryptedPdu);
991
- decryptedPdu = Buffer.concat([decryptedPdu, decipher.final()]);
992
- }
993
- debug("Key: " + decryptionKey.toString('hex'));
994
- debug("IV: " + iv.toString('hex'));
995
- debug("Encrypted: " + encryptedPdu.toString('hex'));
996
- debug("Plain: " + decryptedPdu.toString('hex'));
997
-
998
- return decryptedPdu;
999
-
1000
-};
1001
-
1002
-Encryption.addParametersToMessageBuffer = function (messageBuffer, msgPrivacyParameters) {
1003
- privacyParametersOffset = messageBuffer.indexOf(Encryption.PRIV_PARAMETERS_PLACEHOLDER);
1004
- msgPrivacyParameters.copy(messageBuffer, privacyParametersOffset, 0, Encryption.DES_IV_LENGTH);
1005
-};
1006
-
1007
-/*****************************************************************************
1008
- ** Message class definition
1009
- **/
1010
-
1011
-var Message = function () {
1012
-}
1013
-
1014
-Message.prototype.getReqId = function () {
1015
- return this.version == Version3 ? this.msgGlobalData.msgID : this.pdu.id;
1016
-};
1017
-
1018
-Message.prototype.toBuffer = function () {
1019
- if (this.version == Version3) {
1020
- return this.toBufferV3();
1021
- } else {
1022
- return this.toBufferCommunity();
1023
- }
1024
-}
1025
-
1026
-Message.prototype.toBufferCommunity = function () {
1027
- if (this.buffer)
1028
- return this.buffer;
1029
-
1030
- var writer = new ber.Writer();
1031
-
1032
- writer.startSequence();
1033
-
1034
- writer.writeInt(this.version);
1035
- writer.writeString(this.community);
1036
-
1037
- this.pdu.toBuffer(writer);
1038
-
1039
- writer.endSequence();
1040
-
1041
- this.buffer = writer.buffer;
1042
-
1043
- return this.buffer;
1044
-};
1045
-
1046
-Message.prototype.toBufferV3 = function () {
1047
- var encryptionResult;
1048
-
1049
- if (this.buffer)
1050
- return this.buffer;
1051
-
1052
- var writer = new ber.Writer();
1053
-
1054
- writer.startSequence();
1055
-
1056
- writer.writeInt(this.version);
1057
-
1058
- // HeaderData
1059
- writer.startSequence();
1060
- writer.writeInt(this.msgGlobalData.msgID);
1061
- writer.writeInt(this.msgGlobalData.msgMaxSize);
1062
- writer.writeByte(ber.OctetString);
1063
- writer.writeByte(1);
1064
- writer.writeByte(this.msgGlobalData.msgFlags);
1065
- writer.writeInt(this.msgGlobalData.msgSecurityModel);
1066
- writer.endSequence();
1067
-
1068
- // msgSecurityParameters
1069
- var msgSecurityParametersWriter = new ber.Writer();
1070
- msgSecurityParametersWriter.startSequence();
1071
- //msgSecurityParametersWriter.writeString (this.msgSecurityParameters.msgAuthoritativeEngineID);
1072
- // writing a zero-length buffer fails - should fix asn1-ber for this condition
1073
- if (this.msgSecurityParameters.msgAuthoritativeEngineID.length == 0) {
1074
- msgSecurityParametersWriter.writeString("");
1075
- } else {
1076
- msgSecurityParametersWriter.writeBuffer(this.msgSecurityParameters.msgAuthoritativeEngineID, ber.OctetString);
1077
- }
1078
- msgSecurityParametersWriter.writeInt(this.msgSecurityParameters.msgAuthoritativeEngineBoots);
1079
- msgSecurityParametersWriter.writeInt(this.msgSecurityParameters.msgAuthoritativeEngineTime);
1080
- msgSecurityParametersWriter.writeString(this.msgSecurityParameters.msgUserName);
1081
-
1082
- if (this.hasAuthentication()) {
1083
- msgSecurityParametersWriter.writeBuffer(Authentication.AUTH_PARAMETERS_PLACEHOLDER, ber.OctetString);
1084
- // should never happen where msgFlags has no authentication but authentication parameters still present
1085
- } else if (this.msgSecurityParameters.msgAuthenticationParameters.length > 0) {
1086
- msgSecurityParametersWriter.writeBuffer(this.msgSecurityParameters.msgAuthenticationParameters, ber.OctetString);
1087
- } else {
1088
- msgSecurityParametersWriter.writeString("");
1089
- }
1090
-
1091
- if (this.hasPrivacy()) {
1092
- msgSecurityParametersWriter.writeBuffer(Encryption.PRIV_PARAMETERS_PLACEHOLDER, ber.OctetString);
1093
- // should never happen where msgFlags has no privacy but privacy parameters still present
1094
- } else if (this.msgSecurityParameters.msgPrivacyParameters.length > 0) {
1095
- msgSecurityParametersWriter.writeBuffer(this.msgSecurityParameters.msgPrivacyParameters, ber.OctetString);
1096
- } else {
1097
- msgSecurityParametersWriter.writeString("");
1098
- }
1099
- msgSecurityParametersWriter.endSequence();
1100
-
1101
- writer.writeBuffer(msgSecurityParametersWriter.buffer, ber.OctetString);
1102
-
1103
- // ScopedPDU
1104
- var scopedPduWriter = new ber.Writer();
1105
- scopedPduWriter.startSequence();
1106
- var contextEngineID = this.pdu.contextEngineID ? this.pdu.contextEngineID : this.msgSecurityParameters.msgAuthoritativeEngineID;
1107
- if (contextEngineID.length == 0) {
1108
- scopedPduWriter.writeString("");
1109
- } else {
1110
- scopedPduWriter.writeBuffer(contextEngineID, ber.OctetString);
1111
- }
1112
- scopedPduWriter.writeString(this.pdu.contextName);
1113
- this.pdu.toBuffer(scopedPduWriter);
1114
- scopedPduWriter.endSequence();
1115
-
1116
- if (this.hasPrivacy()) {
1117
- encryptionResult = Encryption.encryptPdu(scopedPduWriter.buffer, this.user.privProtocol, this.user.privKey, this.user.authProtocol, this.msgSecurityParameters.msgAuthoritativeEngineID);
1118
- writer.writeBuffer(encryptionResult.encryptedPdu, ber.OctetString);
1119
- } else {
1120
- writer.writeBuffer(scopedPduWriter.buffer);
1121
- }
1122
-
1123
- writer.endSequence();
1124
-
1125
- this.buffer = writer.buffer;
1126
-
1127
- if (this.hasPrivacy()) {
1128
- Encryption.addParametersToMessageBuffer(this.buffer, encryptionResult.msgPrivacyParameters);
1129
- }
1130
-
1131
- if (this.hasAuthentication()) {
1132
- Authentication.addParametersToMessageBuffer(this.buffer, this.user.authProtocol, this.user.authKey,
1133
- this.msgSecurityParameters.msgAuthoritativeEngineID);
1134
- }
1135
-
1136
- return this.buffer;
1137
-};
1138
-
1139
-Message.prototype.processIncomingSecurity = function (user, responseCb) {
1140
- if (this.hasPrivacy()) {
1141
- if (!this.decryptPdu(user, responseCb)) {
1142
- return false;
1143
- }
1144
- }
1145
-
1146
- if (this.hasAuthentication() && !this.isAuthenticationDisabled()) {
1147
- return this.checkAuthentication(user, responseCb);
1148
- } else {
1149
- return true;
1150
- }
1151
-};
1152
-
1153
-Message.prototype.decryptPdu = function (user, responseCb) {
1154
- var decryptedPdu;
1155
- var decryptedPduReader;
1156
- try {
1157
- decryptedPdu = Encryption.decryptPdu(this.encryptedPdu, user.privProtocol,
1158
- this.msgSecurityParameters.msgPrivacyParameters, user.privKey, user.authProtocol,
1159
- this.msgSecurityParameters.msgAuthoritativeEngineID);
1160
- decryptedPduReader = new ber.Reader(decryptedPdu);
1161
- this.pdu = readPdu(decryptedPduReader, true);
1162
- return true;
1163
- // really really occasionally the decrypt truncates a single byte
1164
- // causing an ASN read failure in readPdu()
1165
- // in this case, disabling auto padding decrypts the PDU correctly
1166
- // this try-catch provides the workaround for this condition
1167
- } catch (possibleTruncationError) {
1168
- try {
1169
- decryptedPdu = Encryption.decryptPdu(this.encryptedPdu, user.privProtocol,
1170
- this.msgSecurityParameters.msgPrivacyParameters, user.privKey, user.authProtocol,
1171
- this.msgSecurityParameters.msgAuthoritativeEngineID, true);
1172
- decryptedPduReader = new ber.Reader(decryptedPdu);
1173
- this.pdu = readPdu(decryptedPduReader, true);
1174
- return true;
1175
- } catch (error) {
1176
- responseCb(new ResponseInvalidError("Failed to decrypt PDU: " + error));
1177
- return false;
1178
- }
1179
- }
1180
-
1181
-};
1182
-
1183
-Message.prototype.checkAuthentication = function (user, responseCb) {
1184
- if (Authentication.isAuthentic(this.buffer, user.authProtocol, user.authKey,
1185
- this.msgSecurityParameters.msgAuthoritativeEngineID, this.msgSecurityParameters.msgAuthenticationParameters)) {
1186
- return true;
1187
- } else {
1188
- responseCb(new ResponseInvalidError("Authentication digest "
1189
- + this.msgSecurityParameters.msgAuthenticationParameters.toString('hex')
1190
- + " received in message does not match digest "
1191
- + Authentication.calculateDigest(buffer, user.authProtocol, user.authKey,
1192
- this.msgSecurityParameters.msgAuthoritativeEngineID).toString('hex')
1193
- + " calculated for message"));
1194
- return false;
1195
- }
1196
-
1197
-};
1198
-
1199
-Message.prototype.hasAuthentication = function () {
1200
- return this.msgGlobalData && this.msgGlobalData.msgFlags && this.msgGlobalData.msgFlags & 1;
1201
-};
1202
-
1203
-Message.prototype.hasPrivacy = function () {
1204
- return this.msgGlobalData && this.msgGlobalData.msgFlags && this.msgGlobalData.msgFlags & 2;
1205
-};
1206
-
1207
-Message.prototype.isReportable = function () {
1208
- return this.msgGlobalData && this.msgGlobalData.msgFlags && this.msgGlobalData.msgFlags & 4;
1209
-};
1210
-
1211
-Message.prototype.setReportable = function (flag) {
1212
- if (this.msgGlobalData && this.msgGlobalData.msgFlags) {
1213
- if (flag) {
1214
- this.msgGlobalData.msgFlags = this.msgGlobalData.msgFlags | 4;
1215
- } else {
1216
- this.msgGlobalData.msgFlags = this.msgGlobalData.msgFlags & (255 - 4);
1217
- }
1218
- }
1219
-};
1220
-
1221
-Message.prototype.isAuthenticationDisabled = function () {
1222
- return this.disableAuthentication;
1223
-};
1224
-
1225
-Message.prototype.hasAuthoritativeEngineID = function () {
1226
- return this.msgSecurityParameters && this.msgSecurityParameters.msgAuthoritativeEngineID &&
1227
- this.msgSecurityParameters.msgAuthoritativeEngineID != "";
1228
-};
1229
-
1230
-Message.prototype.createReportResponseMessage = function (engine, context) {
1231
- var user = {
1232
- name: "",
1233
- level: SecurityLevel.noAuthNoPriv
1234
- };
1235
- var responseSecurityParameters = {
1236
- msgAuthoritativeEngineID: engine.engineID,
1237
- msgAuthoritativeEngineBoots: engine.engineBoots,
1238
- msgAuthoritativeEngineTime: engine.engineTime,
1239
- msgUserName: user.name,
1240
- msgAuthenticationParameters: "",
1241
- msgPrivacyParameters: ""
1242
- };
1243
- var reportPdu = ReportPdu.createFromVariables(this.pdu.id, [], {});
1244
- reportPdu.contextName = context;
1245
- var responseMessage = Message.createRequestV3(user, responseSecurityParameters, reportPdu);
1246
- responseMessage.msgGlobalData.msgID = this.msgGlobalData.msgID;
1247
- return responseMessage;
1248
-};
1249
-
1250
-Message.prototype.createResponseForRequest = function (responsePdu) {
1251
- if (this.version == Version3) {
1252
- return this.createV3ResponseFromRequest(responsePdu);
1253
- } else {
1254
- return this.createCommunityResponseFromRequest(responsePdu);
1255
- }
1256
-};
1257
-
1258
-Message.prototype.createCommunityResponseFromRequest = function (responsePdu) {
1259
- return Message.createCommunity(this.version, this.community, responsePdu);
1260
-};
1261
-
1262
-Message.prototype.createV3ResponseFromRequest = function (responsePdu) {
1263
- var responseUser = {
1264
- name: this.user.name,
1265
- level: this.user.name,
1266
- authProtocol: this.user.authProtocol,
1267
- authKey: this.user.authKey,
1268
- privProtocol: this.user.privProtocol,
1269
- privKey: this.user.privKey
1270
- };
1271
- var responseSecurityParameters = {
1272
- msgAuthoritativeEngineID: this.msgSecurityParameters.msgAuthoritativeEngineID,
1273
- msgAuthoritativeEngineBoots: this.msgSecurityParameters.msgAuthoritativeEngineBoots,
1274
- msgAuthoritativeEngineTime: this.msgSecurityParameters.msgAuthoritativeEngineTime,
1275
- msgUserName: this.msgSecurityParameters.msgUserName,
1276
- msgAuthenticationParameters: "",
1277
- msgPrivacyParameters: ""
1278
- };
1279
- var responseGlobalData = {
1280
- msgID: this.msgGlobalData.msgID,
1281
- msgMaxSize: 65507,
1282
- msgFlags: this.msgGlobalData.msgFlags & (255 - 4),
1283
- msgSecurityModel: 3
1284
- };
1285
- return Message.createV3(responseUser, responseGlobalData, responseSecurityParameters, responsePdu);
1286
-};
1287
-
1288
-Message.createCommunity = function (version, community, pdu) {
1289
- var message = new Message();
1290
-
1291
- message.version = version;
1292
- message.community = community;
1293
- message.pdu = pdu;
1294
-
1295
- return message;
1296
-};
1297
-
1298
-Message.createRequestV3 = function (user, msgSecurityParameters, pdu) {
1299
- var authFlag = user.level == SecurityLevel.authNoPriv || user.level == SecurityLevel.authPriv ? 1 : 0;
1300
- var privFlag = user.level == SecurityLevel.authPriv ? 1 : 0;
1301
- var reportableFlag = (pdu.type == PduType.GetResponse || pdu.type == PduType.TrapV2) ? 0 : 1;
1302
- var msgGlobalData = {
1303
- msgID: _generateId(), // random ID
1304
- msgMaxSize: 65507,
1305
- msgFlags: reportableFlag * 4 | privFlag * 2 | authFlag * 1,
1306
- msgSecurityModel: 3
1307
- };
1308
- return Message.createV3(user, msgGlobalData, msgSecurityParameters, pdu);
1309
-};
1310
-
1311
-Message.createV3 = function (user, msgGlobalData, msgSecurityParameters, pdu) {
1312
- var message = new Message();
1313
-
1314
- message.version = 3;
1315
- message.user = user;
1316
- message.msgGlobalData = msgGlobalData;
1317
- message.msgSecurityParameters = {
1318
- msgAuthoritativeEngineID: msgSecurityParameters.msgAuthoritativeEngineID || Buffer.from(""),
1319
- msgAuthoritativeEngineBoots: msgSecurityParameters.msgAuthoritativeEngineBoots || 0,
1320
- msgAuthoritativeEngineTime: msgSecurityParameters.msgAuthoritativeEngineTime || 0,
1321
- msgUserName: user.name || "",
1322
- msgAuthenticationParameters: "",
1323
- msgPrivacyParameters: ""
1324
- };
1325
- message.pdu = pdu;
1326
-
1327
- return message;
1328
-};
1329
-
1330
-Message.createDiscoveryV3 = function (pdu) {
1331
- var msgSecurityParameters = {
1332
- msgAuthoritativeEngineID: Buffer.from(""),
1333
- msgAuthoritativeEngineBoots: 0,
1334
- msgAuthoritativeEngineTime: 0
1335
- };
1336
- var emptyUser = {
1337
- name: "",
1338
- level: SecurityLevel.noAuthNoPriv
1339
- };
1340
- return Message.createRequestV3(emptyUser, msgSecurityParameters, pdu);
1341
-}
1342
-
1343
-Message.createFromBuffer = function (buffer, user) {
1344
- var reader = new ber.Reader(buffer);
1345
- var message = new Message();
1346
-
1347
- reader.readSequence();
1348
-
1349
- message.version = reader.readInt();
1350
-
1351
- if (message.version != 3) {
1352
- message.community = reader.readString();
1353
- message.pdu = readPdu(reader, false);
1354
- } else {
1355
- // HeaderData
1356
- message.msgGlobalData = {};
1357
- reader.readSequence();
1358
- message.msgGlobalData.msgID = reader.readInt();
1359
- message.msgGlobalData.msgMaxSize = reader.readInt();
1360
- message.msgGlobalData.msgFlags = reader.readString(ber.OctetString, true)[0];
1361
- message.msgGlobalData.msgSecurityModel = reader.readInt();
1362
-
1363
- // msgSecurityParameters
1364
- message.msgSecurityParameters = {};
1365
- var msgSecurityParametersReader = new ber.Reader(reader.readString(ber.OctetString, true));
1366
- msgSecurityParametersReader.readSequence();
1367
- message.msgSecurityParameters.msgAuthoritativeEngineID = msgSecurityParametersReader.readString(ber.OctetString, true);
1368
- message.msgSecurityParameters.msgAuthoritativeEngineBoots = msgSecurityParametersReader.readInt();
1369
- message.msgSecurityParameters.msgAuthoritativeEngineTime = msgSecurityParametersReader.readInt();
1370
- message.msgSecurityParameters.msgUserName = msgSecurityParametersReader.readString();
1371
- message.msgSecurityParameters.msgAuthenticationParameters = Buffer.from(msgSecurityParametersReader.readString(ber.OctetString, true));
1372
- message.msgSecurityParameters.msgPrivacyParameters = Buffer.from(msgSecurityParametersReader.readString(ber.OctetString, true));
1373
- scopedPdu = true;
1374
-
1375
- if (message.hasPrivacy()) {
1376
- message.encryptedPdu = reader.readString(ber.OctetString, true);
1377
- message.pdu = null;
1378
- } else {
1379
- message.pdu = readPdu(reader, true);
1380
- }
1381
- }
1382
-
1383
- message.buffer = buffer;
1384
-
1385
- return message;
1386
-};
1387
-
1388
-
1389
-var Req = function (session, message, feedCb, responseCb, options) {
1390
-
1391
- this.message = message;
1392
- this.responseCb = responseCb;
1393
- this.retries = session.retries;
1394
- this.timeout = session.timeout;
1395
- this.onResponse = session.onSimpleGetResponse;
1396
- this.feedCb = feedCb;
1397
- this.port = (options && options.port) ? options.port : session.port;
1398
- this.context = session.context;
1399
-};
1400
-
1401
-Req.prototype.getId = function () {
1402
- return this.message.getReqId();
1403
-};
1404
-
1405
-
1406
-/*****************************************************************************
1407
- ** Session class definition
1408
- **/
1409
-
1410
-var Session = function (target, authenticator, options) {
1411
- this.target = target || "127.0.0.1";
1412
-
1413
- this.version = (options && options.version)
1414
- ? options.version
1415
- : Version1;
1416
-
1417
- if (this.version == Version3) {
1418
- this.user = authenticator;
1419
- } else {
1420
- this.community = authenticator || "public";
1421
- }
1422
-
1423
- this.transport = (options && options.transport)
1424
- ? options.transport
1425
- : "udp4";
1426
- this.port = (options && options.port)
1427
- ? options.port
1428
- : 161;
1429
- this.trapPort = (options && options.trapPort)
1430
- ? options.trapPort
1431
- : 162;
1432
-
1433
- this.retries = (options && (options.retries || options.retries == 0))
1434
- ? options.retries
1435
- : 1;
1436
- this.timeout = (options && options.timeout)
1437
- ? options.timeout
1438
- : 5000;
1439
-
1440
- this.sourceAddress = (options && options.sourceAddress)
1441
- ? options.sourceAddress
1442
- : undefined;
1443
- this.sourcePort = (options && options.sourcePort)
1444
- ? parseInt(options.sourcePort)
1445
- : undefined;
1446
-
1447
- this.idBitsSize = (options && options.idBitsSize)
1448
- ? parseInt(options.idBitsSize)
1449
- : 32;
1450
-
1451
- this.context = (options && options.context) ? options.context : "";
1452
-
1453
- DEBUG = options.debug;
1454
-
1455
- this.reqs = {};
1456
- this.reqCount = 0;
1457
-
1458
- this.dgram = dgram.createSocket(this.transport);
1459
- this.dgram.unref();
1460
-
1461
- var me = this;
1462
- this.dgram.on("message", me.onMsg.bind(me));
1463
- this.dgram.on("close", me.onClose.bind(me));
1464
- this.dgram.on("error", me.onError.bind(me));
1465
-
1466
- if (this.sourceAddress || this.sourcePort)
1467
- this.dgram.bind(this.sourcePort, this.sourceAddress);
1468
-};
1469
-
1470
-util.inherits(Session, events.EventEmitter);
1471
-
1472
-Session.prototype.close = function () {
1473
- this.dgram.close();
1474
- return this;
1475
-};
1476
-
1477
-Session.prototype.cancelRequests = function (error) {
1478
- var id;
1479
- for (id in this.reqs) {
1480
- var req = this.reqs[id];
1481
- this.unregisterRequest(req.getId());
1482
- req.responseCb(error);
1483
- }
1484
-};
1485
-
1486
-function _generateId(bitSize) {
1487
- if (bitSize === 16) {
1488
- return Math.floor(Math.random() * 10000) % 65535;
1489
- }
1490
- return Math.floor(Math.random() * 100000000) % 4294967295;
1491
-}
1492
-
1493
-Session.prototype.get = function (oids, responseCb) {
1494
- function feedCb(req, message) {
1495
- var pdu = message.pdu;
1496
- var varbinds = [];
1497
-
1498
- if (req.message.pdu.varbinds.length != pdu.varbinds.length) {
1499
- req.responseCb(new ResponseInvalidError("Requested OIDs do not "
1500
- + "match response OIDs"));
1501
- } else {
1502
- for (var i = 0; i < req.message.pdu.varbinds.length; i++) {
1503
- if (req.message.pdu.varbinds[i].oid != pdu.varbinds[i].oid) {
1504
- req.responseCb(new ResponseInvalidError("OID '"
1505
- + req.message.pdu.varbinds[i].oid
1506
- + "' in request at positiion '" + i + "' does not "
1507
- + "match OID '" + pdu.varbinds[i].oid + "' in response "
1508
- + "at position '" + i + "'"));
1509
- return;
1510
- } else {
1511
- varbinds.push(pdu.varbinds[i]);
1512
- }
1513
- }
1514
-
1515
- req.responseCb(null, varbinds);
1516
- }
1517
- }
1518
-
1519
- var pduVarbinds = [];
1520
-
1521
- for (var i = 0; i < oids.length; i++) {
1522
- var varbind = {
1523
- oid: oids[i]
1524
- };
1525
- pduVarbinds.push(varbind);
1526
- }
1527
-
1528
- this.simpleGet(GetRequestPdu, feedCb, pduVarbinds, responseCb);
1529
-
1530
- return this;
1531
-};
1532
-
1533
-Session.prototype.getBulk = function () {
1534
- var oids, nonRepeaters, maxRepetitions, responseCb;
1535
-
1536
- if (arguments.length >= 4) {
1537
- oids = arguments[0];
1538
- nonRepeaters = arguments[1];
1539
- maxRepetitions = arguments[2];
1540
- responseCb = arguments[3];
1541
- } else if (arguments.length >= 3) {
1542
- oids = arguments[0];
1543
- nonRepeaters = arguments[1];
1544
- maxRepetitions = 10;
1545
- responseCb = arguments[2];
1546
- } else {
1547
- oids = arguments[0];
1548
- nonRepeaters = 0;
1549
- maxRepetitions = 10;
1550
- responseCb = arguments[1];
1551
- }
1552
-
1553
- function feedCb(req, message) {
1554
- var pdu = message.pdu;
1555
- var varbinds = [];
1556
- var i = 0;
1557
-
1558
- // first walk through and grab non-repeaters
1559
- if (pdu.varbinds.length < nonRepeaters) {
1560
- req.responseCb(new ResponseInvalidError("Varbind count in "
1561
- + "response '" + pdu.varbinds.length + "' is less than "
1562
- + "non-repeaters '" + nonRepeaters + "' in request"));
1563
- } else {
1564
- for (; i < nonRepeaters; i++) {
1565
- if (isVarbindError(pdu.varbinds[i])) {
1566
- varbinds.push(pdu.varbinds[i]);
1567
- } else if (!oidFollowsOid(req.message.pdu.varbinds[i].oid,
1568
- pdu.varbinds[i].oid)) {
1569
- req.responseCb(new ResponseInvalidError("OID '"
1570
- + req.message.pdu.varbinds[i].oid + "' in request at "
1571
- + "positiion '" + i + "' does not precede "
1572
- + "OID '" + pdu.varbinds[i].oid + "' in response "
1573
- + "at position '" + i + "'"));
1574
- return;
1575
- } else {
1576
- varbinds.push(pdu.varbinds[i]);
1577
- }
1578
- }
1579
- }
1580
-
1581
- var repeaters = req.message.pdu.varbinds.length - nonRepeaters;
1582
-
1583
- // secondly walk through and grab repeaters
1584
- if (pdu.varbinds.length % (repeaters)) {
1585
- req.responseCb(new ResponseInvalidError("Varbind count in "
1586
- + "response '" + pdu.varbinds.length + "' is not a "
1587
- + "multiple of repeaters '" + repeaters
1588
- + "' plus non-repeaters '" + nonRepeaters + "' in request"));
1589
- } else {
1590
- while (i < pdu.varbinds.length) {
1591
- for (var j = 0; j < repeaters; j++, i++) {
1592
- var reqIndex = nonRepeaters + j;
1593
- var respIndex = i;
1594
-
1595
- if (isVarbindError(pdu.varbinds[respIndex])) {
1596
- if (!varbinds[reqIndex])
1597
- varbinds[reqIndex] = [];
1598
- varbinds[reqIndex].push(pdu.varbinds[respIndex]);
1599
- } else if (!oidFollowsOid(
1600
- req.message.pdu.varbinds[reqIndex].oid,
1601
- pdu.varbinds[respIndex].oid)) {
1602
- req.responseCb(new ResponseInvalidError("OID '"
1603
- + req.message.pdu.varbinds[reqIndex].oid
1604
- + "' in request at positiion '" + (reqIndex)
1605
- + "' does not precede OID '"
1606
- + pdu.varbinds[respIndex].oid
1607
- + "' in response at position '" + (respIndex) + "'"));
1608
- return;
1609
- } else {
1610
- if (!varbinds[reqIndex])
1611
- varbinds[reqIndex] = [];
1612
- varbinds[reqIndex].push(pdu.varbinds[respIndex]);
1613
- }
1614
- }
1615
- }
1616
- }
1617
-
1618
- req.responseCb(null, varbinds);
1619
- }
1620
-
1621
- var pduVarbinds = [];
1622
-
1623
- for (var i = 0; i < oids.length; i++) {
1624
- var varbind = {
1625
- oid: oids[i]
1626
- };
1627
- pduVarbinds.push(varbind);
1628
- }
1629
-
1630
- var options = {
1631
- nonRepeaters: nonRepeaters,
1632
- maxRepetitions: maxRepetitions
1633
- };
1634
-
1635
- this.simpleGet(GetBulkRequestPdu, feedCb, pduVarbinds, responseCb,
1636
- options);
1637
-
1638
- return this;
1639
-};
1640
-
1641
-Session.prototype.getNext = function (oids, responseCb) {
1642
- function feedCb(req, message) {
1643
- var pdu = message.pdu;
1644
- var varbinds = [];
1645
-
1646
- if (req.message.pdu.varbinds.length != pdu.varbinds.length) {
1647
- req.responseCb(new ResponseInvalidError("Requested OIDs do not "
1648
- + "match response OIDs"));
1649
- } else {
1650
- for (var i = 0; i < req.message.pdu.varbinds.length; i++) {
1651
- if (isVarbindError(pdu.varbinds[i])) {
1652
- varbinds.push(pdu.varbinds[i]);
1653
- } else if (!oidFollowsOid(req.message.pdu.varbinds[i].oid,
1654
- pdu.varbinds[i].oid)) {
1655
- req.responseCb(new ResponseInvalidError("OID '"
1656
- + req.message.pdu.varbinds[i].oid + "' in request at "
1657
- + "positiion '" + i + "' does not precede "
1658
- + "OID '" + pdu.varbinds[i].oid + "' in response "
1659
- + "at position '" + i + "'"));
1660
- return;
1661
- } else {
1662
- varbinds.push(pdu.varbinds[i]);
1663
- }
1664
- }
1665
-
1666
- req.responseCb(null, varbinds);
1667
- }
1668
- }
1669
-
1670
- var pduVarbinds = [];
1671
-
1672
- for (var i = 0; i < oids.length; i++) {
1673
- var varbind = {
1674
- oid: oids[i]
1675
- };
1676
- pduVarbinds.push(varbind);
1677
- }
1678
-
1679
- this.simpleGet(GetNextRequestPdu, feedCb, pduVarbinds, responseCb);
1680
-
1681
- return this;
1682
-};
1683
-
1684
-Session.prototype.inform = function () {
1685
- var typeOrOid = arguments[0];
1686
- var varbinds, options = {}, responseCb;
1687
-
1688
- /**
1689
- ** Support the following signatures:
1690
- **
1691
- ** typeOrOid, varbinds, options, callback
1692
- ** typeOrOid, varbinds, callback
1693
- ** typeOrOid, options, callback
1694
- ** typeOrOid, callback
1695
- **/
1696
- if (arguments.length >= 4) {
1697
- varbinds = arguments[1];
1698
- options = arguments[2];
1699
- responseCb = arguments[3];
1700
- } else if (arguments.length >= 3) {
1701
- if (arguments[1].constructor != Array) {
1702
- varbinds = [];
1703
- options = arguments[1];
1704
- responseCb = arguments[2];
1705
- } else {
1706
- varbinds = arguments[1];
1707
- responseCb = arguments[2];
1708
- }
1709
- } else {
1710
- varbinds = [];
1711
- responseCb = arguments[1];
1712
- }
1713
-
1714
- if (this.version == Version1) {
1715
- responseCb(new RequestInvalidError("Inform not allowed for SNMPv1"));
1716
- return;
1717
- }
1718
-
1719
- function feedCb(req, message) {
1720
- var pdu = message.pdu;
1721
- var varbinds = [];
1722
-
1723
- if (req.message.pdu.varbinds.length != pdu.varbinds.length) {
1724
- req.responseCb(new ResponseInvalidError("Inform OIDs do not "
1725
- + "match response OIDs"));
1726
- } else {
1727
- for (var i = 0; i < req.message.pdu.varbinds.length; i++) {
1728
- if (req.message.pdu.varbinds[i].oid != pdu.varbinds[i].oid) {
1729
- req.responseCb(new ResponseInvalidError("OID '"
1730
- + req.message.pdu.varbinds[i].oid
1731
- + "' in inform at positiion '" + i + "' does not "
1732
- + "match OID '" + pdu.varbinds[i].oid + "' in response "
1733
- + "at position '" + i + "'"));
1734
- return;
1735
- } else {
1736
- varbinds.push(pdu.varbinds[i]);
1737
- }
1738
- }
1739
-
1740
- req.responseCb(null, varbinds);
1741
- }
1742
- }
1743
-
1744
- if (typeof typeOrOid != "string")
1745
- typeOrOid = "1.3.6.1.6.3.1.1.5." + (typeOrOid + 1);
1746
-
1747
- var pduVarbinds = [
1748
- {
1749
- oid: "1.3.6.1.2.1.1.3.0",
1750
- type: ObjectType.TimeTicks,
1751
- value: options.upTime || Math.floor(process.uptime() * 100)
1752
- },
1753
- {
1754
- oid: "1.3.6.1.6.3.1.1.4.1.0",
1755
- type: ObjectType.OID,
1756
- value: typeOrOid
1757
- }
1758
- ];
1759
-
1760
- for (var i = 0; i < varbinds.length; i++) {
1761
- var varbind = {
1762
- oid: varbinds[i].oid,
1763
- type: varbinds[i].type,
1764
- value: varbinds[i].value
1765
- };
1766
- pduVarbinds.push(varbind);
1767
- }
1768
-
1769
- options.port = this.trapPort;
1770
-
1771
- this.simpleGet(InformRequestPdu, feedCb, pduVarbinds, responseCb, options);
1772
-
1773
- return this;
1774
-};
1775
-
1776
-Session.prototype.onClose = function () {
1777
- this.cancelRequests(new Error("Socket forcibly closed"));
1778
- this.emit("close");
1779
-};
1780
-
1781
-Session.prototype.onError = function (error) {
1782
- this.emit(error);
1783
-};
1784
-
1785
-Session.prototype.onMsg = function (buffer) {
1786
- try {
1787
- var message = Message.createFromBuffer(buffer);
1788
-
1789
- var req = this.unregisterRequest(message.getReqId());
1790
- if (!req)
1791
- return;
1792
-
1793
- if (!message.processIncomingSecurity(this.user, req.responseCb))
1794
- return;
1795
-
1796
- try {
1797
- if (message.version != req.message.version) {
1798
- req.responseCb(new ResponseInvalidError("Version in request '"
1799
- + req.message.version + "' does not match version in "
1800
- + "response '" + message.version + "'"));
1801
- } else if (message.community != req.message.community) {
1802
- req.responseCb(new ResponseInvalidError("Community '"
1803
- + req.message.community + "' in request does not match "
1804
- + "community '" + message.community + "' in response"));
1805
- } else if (message.pdu.type == PduType.GetResponse) {
1806
- req.onResponse(req, message);
1807
- } else if (message.pdu.type == PduType.Report) {
1808
- if (!req.originalPdu) {
1809
- req.responseCb(new ResponseInvalidError("Unexpected Report PDU"));
1810
- return;
1811
- }
1812
- this.msgSecurityParameters = {
1813
- msgAuthoritativeEngineID: message.msgSecurityParameters.msgAuthoritativeEngineID,
1814
- msgAuthoritativeEngineBoots: message.msgSecurityParameters.msgAuthoritativeEngineBoots,
1815
- msgAuthoritativeEngineTime: message.msgSecurityParameters.msgAuthoritativeEngineTime
1816
- };
1817
- req.originalPdu.contextName = this.context;
1818
- this.sendV3Req(req.originalPdu, req.feedCb, req.responseCb, req.options, req.port);
1819
- } else {
1820
- req.responseCb(new ResponseInvalidError("Unknown PDU type '"
1821
- + message.pdu.type + "' in response"));
1822
- }
1823
- } catch (error) {
1824
- req.responseCb(error);
1825
- }
1826
- } catch (error) {
1827
- this.emit("error", error);
1828
- }
1829
-};
1830
-
1831
-Session.prototype.onSimpleGetResponse = function (req, message) {
1832
- var pdu = message.pdu;
1833
-
1834
- if (pdu.errorStatus > 0) {
1835
- var statusString = ErrorStatus[pdu.errorStatus]
1836
- || ErrorStatus.GeneralError;
1837
- var statusCode = ErrorStatus[statusString]
1838
- || ErrorStatus[ErrorStatus.GeneralError];
1839
-
1840
- if (pdu.errorIndex <= 0 || pdu.errorIndex > pdu.varbinds.length) {
1841
- req.responseCb(new RequestFailedError(statusString, statusCode));
1842
- } else {
1843
- var oid = pdu.varbinds[pdu.errorIndex - 1].oid;
1844
- var error = new RequestFailedError(statusString + ": " + oid,
1845
- statusCode);
1846
- req.responseCb(error);
1847
- }
1848
- } else {
1849
- req.feedCb(req, message);
1850
- }
1851
-};
1852
-
1853
-Session.prototype.registerRequest = function (req) {
1854
- if (!this.reqs[req.getId()]) {
1855
- this.reqs[req.getId()] = req;
1856
- if (this.reqCount <= 0)
1857
- this.dgram.ref();
1858
- this.reqCount++;
1859
- }
1860
- var me = this;
1861
- req.timer = setTimeout(function () {
1862
- if (req.retries-- > 0) {
1863
- me.send(req);
1864
- } else {
1865
- me.unregisterRequest(req.getId());
1866
- req.responseCb(new RequestTimedOutError(
1867
- "Request timed out"));
1868
- }
1869
- }, req.timeout);
1870
-};
1871
-
1872
-Session.prototype.send = function (req, noWait) {
1873
- try {
1874
- var me = this;
1875
-
1876
- var buffer = req.message.toBuffer();
1877
-
1878
- this.dgram.send(buffer, 0, buffer.length, req.port, this.target,
1879
- function (error, bytes) {
1880
- if (error) {
1881
- req.responseCb(error);
1882
- } else {
1883
- if (noWait) {
1884
- req.responseCb(null);
1885
- } else {
1886
- me.registerRequest(req);
1887
- }
1888
- }
1889
- });
1890
- } catch (error) {
1891
- req.responseCb(error);
1892
- }
1893
-
1894
- return this;
1895
-};
1896
-
1897
-Session.prototype.set = function (varbinds, responseCb) {
1898
- function feedCb(req, message) {
1899
- var pdu = message.pdu;
1900
- var varbinds = [];
1901
-
1902
- if (req.message.pdu.varbinds.length != pdu.varbinds.length) {
1903
- req.responseCb(new ResponseInvalidError("Requested OIDs do not "
1904
- + "match response OIDs"));
1905
- } else {
1906
- for (var i = 0; i < req.message.pdu.varbinds.length; i++) {
1907
- if (req.message.pdu.varbinds[i].oid != pdu.varbinds[i].oid) {
1908
- req.responseCb(new ResponseInvalidError("OID '"
1909
- + req.message.pdu.varbinds[i].oid
1910
- + "' in request at positiion '" + i + "' does not "
1911
- + "match OID '" + pdu.varbinds[i].oid + "' in response "
1912
- + "at position '" + i + "'"));
1913
- return;
1914
- } else {
1915
- varbinds.push(pdu.varbinds[i]);
1916
- }
1917
- }
1918
-
1919
- req.responseCb(null, varbinds);
1920
- }
1921
- }
1922
-
1923
- var pduVarbinds = [];
1924
-
1925
- for (var i = 0; i < varbinds.length; i++) {
1926
- var varbind = {
1927
- oid: varbinds[i].oid,
1928
- type: varbinds[i].type,
1929
- value: varbinds[i].value
1930
- };
1931
- pduVarbinds.push(varbind);
1932
- }
1933
-
1934
- this.simpleGet(SetRequestPdu, feedCb, pduVarbinds, responseCb);
1935
-
1936
- return this;
1937
-};
1938
-
1939
-Session.prototype.simpleGet = function (pduClass, feedCb, varbinds,
1940
- responseCb, options) {
1941
- try {
1942
- var id = _generateId(this.idBitsSize);
1943
- var pdu = SimplePdu.createFromVariables(pduClass, id, varbinds, options);
1944
- var message;
1945
- var req;
1946
-
1947
- if (this.version == Version3) {
1948
- if (this.msgSecurityParameters) {
1949
- this.sendV3Req(pdu, feedCb, responseCb, options, this.port);
1950
- } else {
1951
- // SNMPv3 discovery
1952
- var discoveryPdu = createDiscoveryPdu(this.context);
1953
- var discoveryMessage = Message.createDiscoveryV3(discoveryPdu);
1954
- var discoveryReq = new Req(this, discoveryMessage, feedCb, responseCb, options);
1955
- discoveryReq.originalPdu = pdu;
1956
- this.send(discoveryReq);
1957
- }
1958
- } else {
1959
- message = Message.createCommunity(this.version, this.community, pdu);
1960
- req = new Req(this, message, feedCb, responseCb, options);
1961
- this.send(req);
1962
- }
1963
- } catch (error) {
1964
- if (responseCb)
1965
- responseCb(error);
1966
- }
1967
-}
1968
-
1969
-function subtreeCb(req, varbinds) {
1970
- var done = 0;
1971
-
1972
- for (var i = varbinds.length; i > 0; i--) {
1973
- if (!oidInSubtree(req.baseOid, varbinds[i - 1].oid)) {
1974
- done = 1;
1975
- varbinds.pop();
1976
- }
1977
- }
1978
-
1979
- if (varbinds.length > 0)
1980
- req.feedCb(varbinds);
1981
-
1982
- if (done)
1983
- return true;
1984
-}
1985
-
1986
-Session.prototype.subtree = function () {
1987
- var me = this;
1988
- var oid = arguments[0];
1989
- var maxRepetitions, feedCb, doneCb;
1990
-
1991
- if (arguments.length < 4) {
1992
- maxRepetitions = 20;
1993
- feedCb = arguments[1];
1994
- doneCb = arguments[2];
1995
- } else {
1996
- maxRepetitions = arguments[1];
1997
- feedCb = arguments[2];
1998
- doneCb = arguments[3];
1999
- }
2000
-
2001
- var req = {
2002
- feedCb: feedCb,
2003
- doneCb: doneCb,
2004
- maxRepetitions: maxRepetitions,
2005
- baseOid: oid
2006
- };
2007
-
2008
- this.walk(oid, maxRepetitions, subtreeCb.bind(me, req), doneCb);
2009
-
2010
- return this;
2011
-};
2012
-
2013
-function tableColumnsResponseCb(req, error) {
2014
- if (error) {
2015
- req.responseCb(error);
2016
- } else if (req.error) {
2017
- req.responseCb(req.error);
2018
- } else {
2019
- if (req.columns.length > 0) {
2020
- var column = req.columns.pop();
2021
- var me = this;
2022
- this.subtree(req.rowOid + column, req.maxRepetitions,
2023
- tableColumnsFeedCb.bind(me, req),
2024
- tableColumnsResponseCb.bind(me, req));
2025
- } else {
2026
- req.responseCb(null, req.table);
2027
- }
2028
- }
2029
-}
2030
-
2031
-function tableColumnsFeedCb(req, varbinds) {
2032
- for (var i = 0; i < varbinds.length; i++) {
2033
- if (isVarbindError(varbinds[i])) {
2034
- req.error = new RequestFailedError(varbindError(varbind[i]));
2035
- return true;
2036
- }
2037
-
2038
- var oid = varbinds[i].oid.replace(req.rowOid, "");
2039
- if (oid && oid != varbinds[i].oid) {
2040
- var match = oid.match(/^(\d+)\.(.+)$/);
2041
- if (match && match[1] > 0) {
2042
- if (!req.table[match[2]])
2043
- req.table[match[2]] = {};
2044
- req.table[match[2]][match[1]] = varbinds[i].value;
2045
- }
2046
- }
2047
- }
2048
-}
2049
-
2050
-Session.prototype.tableColumns = function () {
2051
- var me = this;
2052
-
2053
- var oid = arguments[0];
2054
- var columns = arguments[1];
2055
- var maxRepetitions, responseCb;
2056
-
2057
- if (arguments.length < 4) {
2058
- responseCb = arguments[2];
2059
- maxRepetitions = 20;
2060
- } else {
2061
- maxRepetitions = arguments[2];
2062
- responseCb = arguments[3];
2063
- }
2064
-
2065
- var req = {
2066
- responseCb: responseCb,
2067
- maxRepetitions: maxRepetitions,
2068
- baseOid: oid,
2069
- rowOid: oid + ".1.",
2070
- columns: columns.slice(0),
2071
- table: {}
2072
- };
2073
-
2074
- if (req.columns.length > 0) {
2075
- var column = req.columns.pop();
2076
- this.subtree(req.rowOid + column, maxRepetitions,
2077
- tableColumnsFeedCb.bind(me, req),
2078
- tableColumnsResponseCb.bind(me, req));
2079
- }
2080
-
2081
- return this;
2082
-};
2083
-
2084
-function tableResponseCb(req, error) {
2085
- if (error)
2086
- req.responseCb(error);
2087
- else if (req.error)
2088
- req.responseCb(req.error);
2089
- else
2090
- req.responseCb(null, req.table);
2091
-}
2092
-
2093
-function tableFeedCb(req, varbinds) {
2094
- for (var i = 0; i < varbinds.length; i++) {
2095
- if (isVarbindError(varbinds[i])) {
2096
- req.error = new RequestFailedError(varbindError(varbind[i]));
2097
- return true;
2098
- }
2099
-
2100
- var oid = varbinds[i].oid.replace(req.rowOid, "");
2101
- if (oid && oid != varbinds[i].oid) {
2102
- var match = oid.match(/^(\d+)\.(.+)$/);
2103
- if (match && match[1] > 0) {
2104
- if (!req.table[match[2]])
2105
- req.table[match[2]] = {};
2106
- req.table[match[2]][match[1]] = varbinds[i].value;
2107
- }
2108
- }
2109
- }
2110
-}
2111
-
2112
-Session.prototype.table = function () {
2113
- var me = this;
2114
-
2115
- var oid = arguments[0];
2116
- var maxRepetitions, responseCb;
2117
-
2118
- if (arguments.length < 3) {
2119
- responseCb = arguments[1];
2120
- maxRepetitions = 20;
2121
- } else {
2122
- maxRepetitions = arguments[1];
2123
- responseCb = arguments[2];
2124
- }
2125
-
2126
- var req = {
2127
- responseCb: responseCb,
2128
- maxRepetitions: maxRepetitions,
2129
- baseOid: oid,
2130
- rowOid: oid + ".1.",
2131
- table: {}
2132
- };
2133
-
2134
- this.subtree(oid, maxRepetitions, tableFeedCb.bind(me, req),
2135
- tableResponseCb.bind(me, req));
2136
-
2137
- return this;
2138
-};
2139
-
2140
-Session.prototype.trap = function () {
2141
- var req = {};
2142
-
2143
- try {
2144
- var typeOrOid = arguments[0];
2145
- var varbinds, options = {}, responseCb;
2146
- var message;
2147
-
2148
- /**
2149
- ** Support the following signatures:
2150
- **
2151
- ** typeOrOid, varbinds, options, callback
2152
- ** typeOrOid, varbinds, agentAddr, callback
2153
- ** typeOrOid, varbinds, callback
2154
- ** typeOrOid, agentAddr, callback
2155
- ** typeOrOid, options, callback
2156
- ** typeOrOid, callback
2157
- **/
2158
- if (arguments.length >= 4) {
2159
- varbinds = arguments[1];
2160
- if (typeof arguments[2] == "string") {
2161
- options.agentAddr = arguments[2];
2162
- } else if (arguments[2].constructor != Array) {
2163
- options = arguments[2];
2164
- }
2165
- responseCb = arguments[3];
2166
- } else if (arguments.length >= 3) {
2167
- if (typeof arguments[1] == "string") {
2168
- varbinds = [];
2169
- options.agentAddr = arguments[1];
2170
- } else if (arguments[1].constructor != Array) {
2171
- varbinds = [];
2172
- options = arguments[1];
2173
- } else {
2174
- varbinds = arguments[1];
2175
- agentAddr = null;
2176
- }
2177
- responseCb = arguments[2];
2178
- } else {
2179
- varbinds = [];
2180
- responseCb = arguments[1];
2181
- }
2182
-
2183
- var pdu, pduVarbinds = [];
2184
-
2185
- for (var i = 0; i < varbinds.length; i++) {
2186
- var varbind = {
2187
- oid: varbinds[i].oid,
2188
- type: varbinds[i].type,
2189
- value: varbinds[i].value
2190
- };
2191
- pduVarbinds.push(varbind);
2192
- }
2193
-
2194
- var id = _generateId(this.idBitsSize);
2195
-
2196
- if (this.version == Version2c || this.version == Version3) {
2197
- if (typeof typeOrOid != "string")
2198
- typeOrOid = "1.3.6.1.6.3.1.1.5." + (typeOrOid + 1);
2199
-
2200
- pduVarbinds.unshift(
2201
- {
2202
- oid: "1.3.6.1.2.1.1.3.0",
2203
- type: ObjectType.TimeTicks,
2204
- value: options.upTime || Math.floor(process.uptime() * 100)
2205
- },
2206
- {
2207
- oid: "1.3.6.1.6.3.1.1.4.1.0",
2208
- type: ObjectType.OID,
2209
- value: typeOrOid
2210
- }
2211
- );
2212
-
2213
- pdu = TrapV2Pdu.createFromVariables(id, pduVarbinds, options);
2214
- } else {
2215
- pdu = TrapPdu.createFromVariables(typeOrOid, pduVarbinds, options);
2216
- }
2217
-
2218
- if (this.version == Version3) {
2219
- var msgSecurityParameters = {
2220
- msgAuthoritativeEngineID: this.user.engineID,
2221
- msgAuthoritativeEngineBoots: 0,
2222
- msgAuthoritativeEngineTime: 0
2223
- };
2224
- message = Message.createRequestV3(this.user, msgSecurityParameters, pdu);
2225
- } else {
2226
- message = Message.createCommunity(this.version, this.community, pdu);
2227
- }
2228
-
2229
- req = {
2230
- id: id,
2231
- message: message,
2232
- responseCb: responseCb,
2233
- port: this.trapPort
2234
- };
2235
-
2236
- this.send(req, true);
2237
- } catch (error) {
2238
- if (req.responseCb)
2239
- req.responseCb(error);
2240
- }
2241
-
2242
- return this;
2243
-};
2244
-
2245
-Session.prototype.unregisterRequest = function (id) {
2246
- var req = this.reqs[id];
2247
- if (req) {
2248
- delete this.reqs[id];
2249
- clearTimeout(req.timer);
2250
- delete req.timer;
2251
- this.reqCount--;
2252
- if (this.reqCount <= 0)
2253
- this.dgram.unref();
2254
- return req;
2255
- } else {
2256
- return null;
2257
- }
2258
-};
2259
-
2260
-function walkCb(req, error, varbinds) {
2261
- var done = 0;
2262
- var oid;
2263
-
2264
- if (error) {
2265
- if (error instanceof RequestFailedError) {
2266
- if (error.status != ErrorStatus.NoSuchName) {
2267
- req.doneCb(error);
2268
- return;
2269
- } else {
2270
- // signal the version 1 walk code below that it should stop
2271
- done = 1;
2272
- }
2273
- } else {
2274
- req.doneCb(error);
2275
- return;
2276
- }
2277
- }
2278
-
2279
- if (this.version == Version2c || this.version == Version3) {
2280
- for (var i = varbinds[0].length; i > 0; i--) {
2281
- if (varbinds[0][i - 1].type == ObjectType.EndOfMibView) {
2282
- varbinds[0].pop();
2283
- done = 1;
2284
- }
2285
- }
2286
- if (req.feedCb(varbinds[0]))
2287
- done = 1;
2288
- if (!done)
2289
- oid = varbinds[0][varbinds[0].length - 1].oid;
2290
- } else {
2291
- if (!done) {
2292
- if (req.feedCb(varbinds)) {
2293
- done = 1;
2294
- } else {
2295
- oid = varbinds[0].oid;
2296
- }
2297
- }
2298
- }
2299
-
2300
- if (done)
2301
- req.doneCb(null);
2302
- else
2303
- this.walk(oid, req.maxRepetitions, req.feedCb, req.doneCb,
2304
- req.baseOid);
2305
-}
2306
-
2307
-Session.prototype.walk = function () {
2308
- var me = this;
2309
- var oid = arguments[0];
2310
- var maxRepetitions, feedCb, doneCb, baseOid;
2311
-
2312
- if (arguments.length < 4) {
2313
- maxRepetitions = 20;
2314
- feedCb = arguments[1];
2315
- doneCb = arguments[2];
2316
- } else {
2317
- maxRepetitions = arguments[1];
2318
- feedCb = arguments[2];
2319
- doneCb = arguments[3];
2320
- }
2321
-
2322
- var req = {
2323
- maxRepetitions: maxRepetitions,
2324
- feedCb: feedCb,
2325
- doneCb: doneCb
2326
- };
2327
-
2328
- if (this.version == Version2c || this.version == Version3)
2329
- this.getBulk([oid], 0, maxRepetitions,
2330
- walkCb.bind(me, req));
2331
- else
2332
- this.getNext([oid], walkCb.bind(me, req));
2333
-
2334
- return this;
2335
-};
2336
-
2337
-Session.prototype.sendV3Req = function (pdu, feedCb, responseCb, options, port) {
2338
- var message = Message.createRequestV3(this.user, this.msgSecurityParameters, pdu);
2339
- var reqOptions = options || {};
2340
- var req = new Req(this, message, feedCb, responseCb, reqOptions);
2341
- req.port = port;
2342
- this.send(req);
2343
-};
2344
-
2345
-var Engine = function (engineID, engineBoots, engineTime) {
2346
- if (engineID) {
2347
- this.engineID = Buffer.from(engineID, 'hex');
2348
- } else {
2349
- this.generateEngineID();
2350
- }
2351
- this.engineBoots = 0;
2352
- this.engineTime = 10;
2353
-};
2354
-
2355
-Engine.prototype.generateEngineID = function () {
2356
- // generate a 17-byte engine ID in the following format:
2357
- // 0x80 + 0x00B983 (enterprise OID) | 0x80 (enterprise-specific format) | 12 bytes of random
2358
- this.engineID = Buffer.alloc(17);
2359
- this.engineID.fill('8000B98380', 'hex', 0, 5);
2360
- this.engineID.fill(crypto.randomBytes(12), 5, 17, 'hex');
2361
-}
2362
-
2363
-var Listener = function (options, receiver) {
2364
- this.receiver = receiver;
2365
- this.callback = receiver.onMsg;
2366
- this.family = options.transport || 'udp4';
2367
- this.port = options.port || 161;
2368
- this.disableAuthorization = options.disableAuthorization || false;
2369
-};
2370
-
2371
-Listener.prototype.startListening = function (receiver) {
2372
- var me = this;
2373
- this.dgram = dgram.createSocket(this.family);
2374
- this.dgram.bind(this.port);
2375
- this.dgram.on("message", me.callback.bind(me.receiver));
2376
-};
2377
-
2378
-Listener.prototype.send = function (message, rinfo) {
2379
- var me = this;
2380
-
2381
- var buffer = message.toBuffer();
2382
-
2383
- this.dgram.send(buffer, 0, buffer.length, rinfo.port, rinfo.address,
2384
- function (error, bytes) {
2385
- if (error) {
2386
- // me.callback (error);
2387
- console.error("Error sending: " + error.message);
2388
- } else {
2389
- // debug ("Listener sent response message");
2390
- }
2391
- });
2392
-};
2393
-
2394
-Listener.formatCallbackData = function (pdu, rinfo) {
2395
- if (pdu.contextEngineID) {
2396
- pdu.contextEngineID = pdu.contextEngineID.toString('hex');
2397
- }
2398
- delete pdu.nonRepeaters;
2399
- delete pdu.maxRepetitions;
2400
- return {
2401
- pdu: pdu,
2402
- rinfo: rinfo
2403
- };
2404
-};
2405
-
2406
-Listener.processIncoming = function (buffer, authorizer, callback) {
2407
- var message = Message.createFromBuffer(buffer);
2408
- var community;
2409
-
2410
- // Authorization
2411
- if (message.version == Version3) {
2412
- message.user = authorizer.users.filter(localUser => localUser.name ==
2413
- message.msgSecurityParameters.msgUserName)[0];
2414
- message.disableAuthentication = authorizer.disableAuthorization;
2415
- if (!message.user) {
2416
- if (message.msgSecurityParameters.msgUserName != "" && !authorizer.disableAuthorization) {
2417
- callback(new RequestFailedError("Local user not found for message with user " +
2418
- message.msgSecurityParameters.msgUserName));
2419
- return;
2420
- } else if (message.hasAuthentication()) {
2421
- callback(new RequestFailedError("Local user not found and message requires authentication with user " +
2422
- message.msgSecurityParameters.msgUserName));
2423
- return;
2424
- } else {
2425
- message.user = {
2426
- name: "",
2427
- level: SecurityLevel.noAuthNoPriv
2428
- };
2429
- }
2430
- }
2431
- if (!message.processIncomingSecurity(message.user, callback)) {
2432
- return;
2433
- }
2434
- } else {
2435
- community = authorizer.communities.filter(localCommunity => localCommunity == message.community)[0];
2436
- if (!community && !authorizer.disableAuthorization) {
2437
- callback(new RequestFailedError("Local community not found for message with community " + message.community));
2438
- return;
2439
- }
2440
- }
2441
-
2442
- return message;
2443
-};
2444
-
2445
-var Authorizer = function () {
2446
- this.communities = [];
2447
- this.users = [];
2448
-}
2449
-
2450
-Authorizer.prototype.addCommunity = function (community) {
2451
- if (this.getCommunity(community)) {
2452
- return;
2453
- } else {
2454
- this.communities.push(community);
2455
- }
2456
-};
2457
-
2458
-Authorizer.prototype.getCommunity = function (community) {
2459
- return this.communities.filter(localCommunity => localCommunity == community)[0] || null;
2460
-};
2461
-
2462
-Authorizer.prototype.getCommunities = function () {
2463
- return this.communities;
2464
-};
2465
-
2466
-Authorizer.prototype.deleteCommunity = function (community) {
2467
- var index = this.communities.indexOf(community);
2468
- if (index > -1) {
2469
- this.communities.splice(index, 1);
2470
- }
2471
-};
2472
-
2473
-Authorizer.prototype.addUser = function (user) {
2474
- if (this.getUser(user.name)) {
2475
- this.deleteUser(user.name);
2476
- }
2477
- this.users.push(user);
2478
-};
2479
-
2480
-Authorizer.prototype.getUser = function (userName) {
2481
- return this.users.filter(localUser => localUser.name == userName)[0] || null;
2482
-};
2483
-
2484
-Authorizer.prototype.getUsers = function () {
2485
- return this.users;
2486
-};
2487
-
2488
-Authorizer.prototype.deleteUser = function (userName) {
2489
- var index = this.users.findIndex(localUser => localUser.name == userName);
2490
- if (index > -1) {
2491
- this.users.splice(index, 1);
2492
- }
2493
-};
2494
-
2495
-
2496
-/*****************************************************************************
2497
- ** Receiver class definition
2498
- **/
2499
-
2500
-var Receiver = function (options, callback) {
2501
- DEBUG = options.debug;
2502
- this.listener = new Listener(options, this);
2503
- this.authorizer = new Authorizer();
2504
- this.engine = new Engine(options.engineID);
2505
-
2506
- this.engineBoots = 0;
2507
- this.engineTime = 10;
2508
- this.disableAuthorization = false;
2509
-
2510
- this.callback = callback;
2511
- this.family = options.transport || 'udp4';
2512
- this.port = options.port || 162;
2513
- options.port = this.port;
2514
- this.disableAuthorization = options.disableAuthorization || false;
2515
- this.context = (options && options.context) ? options.context : "";
2516
- this.listener = new Listener(options, this);
2517
-};
2518
-
2519
-Receiver.prototype.addCommunity = function (community) {
2520
- this.authorizer.addCommunity(community);
2521
-};
2522
-
2523
-Receiver.prototype.getCommunity = function (community) {
2524
- return this.authorizer.getCommunity(community);
2525
-};
2526
-
2527
-Receiver.prototype.getCommunities = function () {
2528
- return this.authorizer.getCommunities();
2529
-};
2530
-
2531
-Receiver.prototype.deleteCommunity = function (community) {
2532
- this.authorizer.deleteCommunities(community);
2533
-};
2534
-
2535
-Receiver.prototype.addUser = function (user) {
2536
- this.authorizer.addUser(user);
2537
-};
2538
-
2539
-Receiver.prototype.getUser = function (userName) {
2540
- return this.authorizer.getUser(userName);
2541
-};
2542
-
2543
-Receiver.prototype.getUsers = function () {
2544
- return this.authorizer.getUsers();
2545
-};
2546
-
2547
-Receiver.prototype.deleteUser = function (userName) {
2548
- this.authorizer.deleteUser(userName);
2549
-};
2550
-
2551
-Receiver.prototype.onMsg = function (buffer, rinfo) {
2552
- var message = Listener.processIncoming(buffer, this.authorizer, this.callback);
2553
- var reportMessage;
2554
-
2555
- if (!message) {
2556
- return;
2557
- }
2558
-
2559
- // The only GetRequest PDUs supported are those used for SNMPv3 discovery
2560
- if (message.pdu.type == PduType.GetRequest) {
2561
- if (message.version != Version3) {
2562
- this.callback(new RequestInvalidError("Only SNMPv3 discovery GetRequests are supported"));
2563
- return;
2564
- } else if (message.hasAuthentication()) {
2565
- this.callback(new RequestInvalidError("Only discovery (noAuthNoPriv) GetRequests are supported but this message has authentication"));
2566
- return;
2567
- } else if (!message.isReportable()) {
2568
- this.callback(new RequestInvalidError("Only discovery GetRequests are supported and this message does not have the reportable flag set"));
2569
- return;
2570
- }
2571
- var reportMessage = message.createReportResponseMessage(this.engine, this.context);
2572
- this.listener.send(reportMessage, rinfo);
2573
- return;
2574
- }
2575
- ;
2576
-
2577
- // Inform/trap processing
2578
- debug(JSON.stringify(message.pdu, null, 2));
2579
- if (message.pdu.type == PduType.Trap || message.pdu.type == PduType.TrapV2) {
2580
- this.callback(null, this.formatCallbackData(message.pdu, rinfo));
2581
- } else if (message.pdu.type == PduType.InformRequest) {
2582
- message.pdu.type = PduType.GetResponse;
2583
- message.buffer = null;
2584
- message.setReportable(false);
2585
- this.listener.send(message, rinfo);
2586
- message.pdu.type = PduType.InformRequest;
2587
- this.callback(null, this.formatCallbackData(message.pdu, rinfo));
2588
- } else {
2589
- this.callback(new RequestInvalidError("Unexpected PDU type " + message.pdu.type + " (" + PduType[message.pdu.type] + ")"));
2590
- }
2591
-}
2592
-
2593
-Receiver.prototype.formatCallbackData = function (pdu, rinfo) {
2594
- if (pdu.contextEngineID) {
2595
- pdu.contextEngineID = pdu.contextEngineID.toString('hex');
2596
- }
2597
- delete pdu.nonRepeaters;
2598
- delete pdu.maxRepetitions;
2599
- return {
2600
- pdu: pdu,
2601
- rinfo: rinfo
2602
- };
2603
-};
2604
-
2605
-Receiver.prototype.close = function () {
2606
- this.listener.close();
2607
-};
2608
-
2609
-Receiver.create = function (options, callback) {
2610
- var receiver = new Receiver(options, callback);
2611
- receiver.listener.startListening();
2612
- return receiver;
2613
-};
2614
-
2615
-var MibNode = function (address, parent) {
2616
- this.address = address;
2617
- this.oid = this.address.join('.');
2618
- ;
2619
- this.parent = parent;
2620
- this.children = {};
2621
-};
2622
-
2623
-MibNode.prototype.child = function (index) {
2624
- return this.children[index];
2625
-};
2626
-
2627
-MibNode.prototype.listChildren = function (lowest) {
2628
- var sorted = [];
2629
-
2630
- lowest = lowest || 0;
2631
-
2632
- this.children.forEach(function (c, i) {
2633
- if (i >= lowest)
2634
- sorted.push(i);
2635
- });
2636
-
2637
- sorted.sort(function (a, b) {
2638
- return (a - b);
2639
- });
2640
-
2641
- return sorted;
2642
-};
2643
-
2644
-MibNode.prototype.isDescendant = function (address) {
2645
- return MibNode.oidIsDescended(this.address, address);
2646
-};
2647
-
2648
-MibNode.prototype.isAncestor = function (address) {
2649
- return MibNode.oidIsDescended(address, this.address);
2650
-};
2651
-
2652
-MibNode.prototype.getAncestorProvider = function () {
2653
- if (this.provider) {
2654
- return this;
2655
- } else if (!this.parent) {
2656
- return null;
2657
- } else {
2658
- return this.parent.getAncestorProvider();
2659
- }
2660
-};
2661
-
2662
-MibNode.prototype.getInstanceNodeForTableRow = function () {
2663
- var childCount = Object.keys(this.children).length;
2664
- if (childCount == 0) {
2665
- if (this.value) {
2666
- return this;
2667
- } else {
2668
- return null;
2669
- }
2670
- } else if (childCount == 1) {
2671
- return this.children[0].getInstanceNodeForTableRow();
2672
- } else if (childCount > 1) {
2673
- return null;
2674
- }
2675
-};
2676
-
2677
-MibNode.prototype.getInstanceNodeForTableRowIndex = function (index) {
2678
- var childCount = Object.keys(this.children).length;
2679
- if (childCount == 0) {
2680
- if (this.value) {
2681
- return this;
2682
- } else {
2683
- // not found
2684
- return null;
2685
- }
2686
- } else {
2687
- if (index.length == 0) {
2688
- return this.getInstanceNodeForTableRow();
2689
- } else {
2690
- var nextChildIndexPart = index[0];
2691
- if (!nextChildIndexPart) {
2692
- return null;
2693
- }
2694
- remainingIndex = index.slice(1);
2695
- return this.children[nextChildIndexPart].getInstanceNodeForTableRowIndex(remainingIndex);
2696
- }
2697
- }
2698
-};
2699
-
2700
-MibNode.prototype.getNextInstanceNode = function () {
2701
-
2702
- node = this;
2703
- if (this.value) {
2704
- // Need upwards traversal first
2705
- node = this;
2706
- while (node) {
2707
- siblingIndex = node.address.slice(-1)[0];
2708
- node = node.parent;
2709
- if (!node) {
2710
- // end of MIB
2711
- return null;
2712
- } else {
2713
- childrenAddresses = Object.keys(node.children).sort((a, b) => a - b);
2714
- siblingPosition = childrenAddresses.indexOf(siblingIndex.toString());
2715
- if (siblingPosition + 1 < childrenAddresses.length) {
2716
- node = node.children[childrenAddresses[siblingPosition + 1]];
2717
- break;
2718
- }
2719
- }
2720
- }
2721
- }
2722
- // Descent
2723
- while (node) {
2724
- if (node.value) {
2725
- return node;
2726
- }
2727
- childrenAddresses = Object.keys(node.children).sort((a, b) => a - b);
2728
- node = node.children[childrenAddresses[0]];
2729
- if (!node) {
2730
- // unexpected
2731
- return null;
2732
- }
2733
- }
2734
-};
2735
-
2736
-MibNode.prototype.delete = function () {
2737
- if (Object.keys(this.children) > 0) {
2738
- throw new Error("Cannot delete non-leaf MIB node");
2739
- }
2740
- addressLastPart = this.address.slice(-1)[0];
2741
- delete this.parent.children[addressLastPart];
2742
- this.parent = null;
2743
-};
2744
-
2745
-MibNode.prototype.pruneUpwards = function () {
2746
- if (!this.parent) {
2747
- return
2748
- }
2749
- if (Object.keys(this.children).length == 0) {
2750
- var lastAddressPart = this.address.splice(-1)[0].toString();
2751
- delete this.parent.children[lastAddressPart];
2752
- this.parent.pruneUpwards();
2753
- this.parent = null;
2754
- }
2755
-}
2756
-
2757
-MibNode.prototype.dump = function (options) {
2758
- var valueString;
2759
- if ((!options.leavesOnly || options.showProviders) && this.provider) {
2760
- console.log(this.oid + " [" + MibProviderType[this.provider.type] + ": " + this.provider.name + "]");
2761
- } else if ((!options.leavesOnly) || Object.keys(this.children).length == 0) {
2762
- if (this.value) {
2763
- valueString = " = ";
2764
- valueString += options.showTypes ? ObjectType[this.valueType] + ": " : "";
2765
- valueString += options.showValues ? this.value : "";
2766
- } else {
2767
- valueString = "";
2768
- }
2769
- console.log(this.oid + valueString);
2770
- }
2771
- for (node of Object.keys(this.children).sort((a, b) => a - b)) {
2772
- this.children[node].dump(options);
2773
- }
2774
-};
2775
-
2776
-MibNode.oidIsDescended = function (oid, ancestor) {
2777
- var ancestorAddress = Mib.convertOidToAddress(ancestor);
2778
- var address = Mib.convertOidToAddress(oid);
2779
- var isAncestor = true;
2780
-
2781
- if (address.length <= ancestorAddress.length) {
2782
- return false;
2783
- }
2784
-
2785
- ancestorAddress.forEach(function (o, i) {
2786
- if (address[i] !== ancestorAddress[i]) {
2787
- isAncestor = false;
2788
- }
2789
- });
2790
-
2791
- return isAncestor;
2792
-};
2793
-
2794
-var Mib = function () {
2795
- this.root = new MibNode([], null);
2796
- this.providers = {};
2797
- this.providerNodes = {};
2798
-};
2799
-
2800
-Mib.prototype.addNodesForOid = function (oidString) {
2801
- var address = Mib.convertOidToAddress(oidString);
2802
- return this.addNodesForAddress(address);
2803
-};
2804
-
2805
-Mib.prototype.addNodesForAddress = function (address) {
2806
- var address;
2807
- var node;
2808
- var i;
2809
-
2810
- node = this.root;
2811
-
2812
- for (i = 0; i < address.length; i++) {
2813
- if (!node.children.hasOwnProperty(address[i])) {
2814
- node.children[address[i]] = new MibNode(address.slice(0, i + 1), node);
2815
- }
2816
- node = node.children[address[i]];
2817
- }
2818
-
2819
- return node;
2820
-};
2821
-
2822
-Mib.prototype.lookup = function (oid) {
2823
- var address;
2824
- var i;
2825
- var node;
2826
-
2827
- address = Mib.convertOidToAddress(oid);
2828
- node = this.root;
2829
- for (i = 0; i < address.length; i++) {
2830
- if (!node.children.hasOwnProperty(address[i])) {
2831
- return null
2832
- }
2833
- node = node.children[address[i]];
2834
- }
2835
-
2836
- return node;
2837
-};
2838
-
2839
-Mib.prototype.getProviderNodeForInstance = function (instanceNode) {
2840
- if (instanceNode.provider) {
2841
- throw new ReferenceError("Instance node has provider which should never happen");
2842
- }
2843
- return instanceNode.getAncestorProvider();
2844
-};
2845
-
2846
-Mib.prototype.addProviderToNode = function (provider) {
2847
- var node = this.addNodesForOid(provider.oid);
2848
-
2849
- node.provider = provider;
2850
- if (provider.type == MibProviderType.Table) {
2851
- if (!provider.index) {
2852
- provider.index = [1];
2853
- }
2854
- }
2855
- this.providerNodes[provider.name] = node;
2856
- return node;
2857
-};
2858
-
2859
-Mib.prototype.registerProvider = function (provider) {
2860
- this.providers[provider.name] = provider;
2861
-};
2862
-
2863
-Mib.prototype.unregisterProvider = function (name) {
2864
- var providerNode = this.providerNodes[name];
2865
- if (providerNode) {
2866
- providerNodeParent = providerNode.parent;
2867
- providerNode.delete();
2868
- providerNodeParent.pruneUpwards();
2869
- delete this.providerNodes[name];
2870
- }
2871
- delete this.providers[name];
2872
-};
2873
-
2874
-Mib.prototype.getProvider = function (name) {
2875
- return this.providers[name];
2876
-};
2877
-
2878
-Mib.prototype.getProviders = function () {
2879
- return this.providers;
2880
-};
2881
-
2882
-Mib.prototype.getScalarValue = function (scalarName) {
2883
- var providerNode = this.providerNodes[scalarName];
2884
- if (!providerNode || !providerNode.provider || providerNode.provider.type != MibProviderType.Scalar) {
2885
- throw new ReferenceError("Failed to get node for registered MIB provider " + scalarName);
2886
- }
2887
- var instanceAddress = providerNode.address.concat([0]);
2888
- if (!this.lookup(instanceAddress)) {
2889
- throw new Error("Failed created instance node for registered MIB provider " + scalarName);
2890
- }
2891
- var instanceNode = this.lookup(instanceAddress);
2892
- return instanceNode.value;
2893
-};
2894
-
2895
-Mib.prototype.setScalarValue = function (scalarName, newValue) {
2896
- var providerNode;
2897
- var instanceNode;
2898
-
2899
- if (!this.providers[scalarName]) {
2900
- throw new ReferenceError("Provider " + scalarName + " not registered with this MIB");
2901
- }
2902
-
2903
- providerNode = this.providerNodes[scalarName];
2904
- if (!providerNode) {
2905
- providerNode = this.addProviderToNode(this.providers[scalarName]);
2906
- }
2907
- if (!providerNode || !providerNode.provider || providerNode.provider.type != MibProviderType.Scalar) {
2908
- throw new ReferenceError("Could not find MIB node for registered provider " + scalarName);
2909
- }
2910
- var instanceAddress = providerNode.address.concat([0]);
2911
- instanceNode = this.lookup(instanceAddress);
2912
- if (!instanceNode) {
2913
- this.addNodesForAddress(instanceAddress);
2914
- instanceNode = this.lookup(instanceAddress);
2915
- instanceNode.valueType = providerNode.provider.scalarType;
2916
- }
2917
- instanceNode.value = newValue;
2918
-};
2919
-
2920
-Mib.prototype.getProviderNodeForTable = function (table) {
2921
- var providerNode;
2922
- var provider;
2923
-
2924
- providerNode = this.providerNodes[table];
2925
- if (!providerNode) {
2926
- throw new ReferenceError("No MIB provider registered for " + table);
2927
- }
2928
- provider = providerNode.provider;
2929
- if (!providerNode) {
2930
- throw new ReferenceError("No MIB provider definition for registered provider " + table);
2931
- }
2932
- if (provider.type != MibProviderType.Table) {
2933
- throw new TypeError("Registered MIB provider " + table +
2934
- " is not of the correct type (is type " + MibProviderType[provider.type] + ")");
2935
- }
2936
- return providerNode;
2937
-};
2938
-
2939
-Mib.prototype.addTableRow = function (table, row) {
2940
- var providerNode;
2941
- var provider;
2942
- var instance = [];
2943
- var instanceAddress;
2944
- var instanceNode;
2945
-
2946
- if (this.providers[table] && !this.providerNodes[table]) {
2947
- this.addProviderToNode(this.providers[table]);
2948
- }
2949
- providerNode = this.getProviderNodeForTable(table);
2950
- provider = providerNode.provider;
2951
- for (var indexPart of provider.index) {
2952
- columnPosition = provider.columns.findIndex(column => column.number == indexPart);
2953
- instance.push(row[columnPosition]);
2954
- }
2955
- for (var i = 0; i < providerNode.provider.columns.length; i++) {
2956
- var column = providerNode.provider.columns[i];
2957
- instanceAddress = providerNode.address.concat(column.number).concat(instance);
2958
- this.addNodesForAddress(instanceAddress);
2959
- instanceNode = this.lookup(instanceAddress);
2960
- instanceNode.valueType = column.type;
2961
- instanceNode.value = row[i];
2962
- }
2963
-};
2964
-
2965
-Mib.prototype.getTableColumnDefinitions = function (table) {
2966
- var providerNode;
2967
- var provider;
2968
-
2969
- providerNode = this.getProviderNodeForTable(table);
2970
- provider = providerNode.provider;
2971
- return provider.columns;
2972
-};
2973
-
2974
-Mib.prototype.getTableColumnCells = function (table, columnNumber) {
2975
- providerNode = this.getProviderNodeForTable(table);
2976
- columnNode = providerNode.children[columnNumber];
2977
- column = []
2978
- for (var row of Object.keys(columnNode.children)) {
2979
- instanceNode = columnNode.children[row].getInstanceNodeForTableRow();
2980
- column.push(instanceNode.value);
2981
- }
2982
- return column;
2983
-};
2984
-
2985
-Mib.prototype.getTableRowCells = function (table, rowIndex) {
2986
- var providerNode;
2987
- var columnNode;
2988
- var instanceNode;
2989
- var row = [];
2990
-
2991
- providerNode = this.getProviderNodeForTable(table);
2992
- for (var columnNumber of Object.keys(providerNode.children)) {
2993
- columnNode = providerNode.children[columnNumber];
2994
- instanceNode = columnNode.getInstanceNodeForTableRowIndex(rowIndex);
2995
- row.push(instanceNode.value);
2996
- }
2997
- return row;
2998
-};
2999
-
3000
-Mib.prototype.getTableCells = function (table, byRows) {
3001
- var providerNode;
3002
- var columnNode;
3003
- var data = [];
3004
-
3005
- providerNode = this.getProviderNodeForTable(table);
3006
- for (var columnNumber of Object.keys(providerNode.children)) {
3007
- columnNode = providerNode.children[columnNumber];
3008
- column = [];
3009
- data.push(column);
3010
- for (var row of Object.keys(columnNode.children)) {
3011
- instanceNode = columnNode.children[row].getInstanceNodeForTableRow();
3012
- column.push(instanceNode.value);
3013
- }
3014
- }
3015
-
3016
- if (byRows) {
3017
- return Object.keys(data[0]).map(function (c) {
3018
- return data.map(function (r) {
3019
- return r[c];
3020
- });
3021
- });
3022
- } else {
3023
- return data;
3024
- }
3025
-
3026
-};
3027
-
3028
-Mib.prototype.getTableSingleCell = function (table, columnNumber, rowIndex) {
3029
- var providerNode;
3030
- var columnNode;
3031
- var instanceNode;
3032
-
3033
- providerNode = this.getProviderNodeForTable(table);
3034
- columnNode = providerNode.children[columnNumber];
3035
- instanceNode = columnNode.getInstanceNodeForTableRowIndex(rowIndex);
3036
- return instanceNode.value;
3037
-};
3038
-
3039
-Mib.prototype.setTableSingleCell = function (table, columnNumber, rowIndex, value) {
3040
- var providerNode;
3041
- var columnNode;
3042
- var instanceNode;
3043
-
3044
- providerNode = this.getProviderNodeForTable(table);
3045
- columnNode = providerNode.children[columnNumber];
3046
- instanceNode = columnNode.getInstanceNodeForTableRowIndex(rowIndex);
3047
- instanceNode.value = value;
3048
-};
3049
-
3050
-Mib.prototype.deleteTableRow = function (table, rowIndex) {
3051
- var providerNode;
3052
- var columnNode;
3053
- var instanceNode;
3054
- var row = [];
3055
-
3056
- providerNode = this.getProviderNodeForTable(table);
3057
- for (var columnNumber of Object.keys(providerNode.children)) {
3058
- columnNode = providerNode.children[columnNumber];
3059
- instanceNode = columnNode.getInstanceNodeForTableRowIndex(rowIndex);
3060
- if (instanceNode) {
3061
- instanceParentNode = instanceNode.parent;
3062
- instanceNode.delete();
3063
- instanceParentNode.pruneUpwards();
3064
- } else {
3065
- throw new ReferenceError("Cannot find row for index " + rowIndex + " at registered provider " + table);
3066
- }
3067
- }
3068
- return row;
3069
-};
3070
-
3071
-Mib.prototype.dump = function (options) {
3072
- if (!options) {
3073
- options = {};
3074
- }
3075
- var completedOptions = {
3076
- leavesOnly: options.leavesOnly || true,
3077
- showProviders: options.leavesOnly || true,
3078
- showValues: options.leavesOnly || true,
3079
- showTypes: options.leavesOnly || true
3080
- };
3081
- this.root.dump(completedOptions);
3082
-};
3083
-
3084
-Mib.convertOidToAddress = function (oid) {
3085
- var address;
3086
- var oidArray;
3087
- var i;
3088
-
3089
- if (typeof (oid) === 'object' && util.isArray(oid)) {
3090
- address = oid;
3091
- } else if (typeof (oid) === 'string') {
3092
- address = oid.split('.');
3093
- } else {
3094
- throw new TypeError('oid (string or array) is required');
3095
- }
3096
-
3097
- if (address.length < 3)
3098
- throw new RangeError('object identifier is too short');
3099
-
3100
- oidArray = [];
3101
- for (i = 0; i < address.length; i++) {
3102
- var n;
3103
-
3104
- if (address[i] === '')
3105
- continue;
3106
-
3107
- if (address[i] === true || address[i] === false) {
3108
- throw new TypeError('object identifier component ' +
3109
- address[i] + ' is malformed');
3110
- }
3111
-
3112
- n = Number(address[i]);
3113
-
3114
- if (isNaN(n)) {
3115
- throw new TypeError('object identifier component ' +
3116
- address[i] + ' is malformed');
3117
- }
3118
- if (n % 1 !== 0) {
3119
- throw new TypeError('object identifier component ' +
3120
- address[i] + ' is not an integer');
3121
- }
3122
- if (i === 0 && n > 2) {
3123
- throw new RangeError('object identifier does not ' +
3124
- 'begin with 0, 1, or 2');
3125
- }
3126
- if (i === 1 && n > 39) {
3127
- throw new RangeError('object identifier second ' +
3128
- 'component ' + n + ' exceeds encoding limit of 39');
3129
- }
3130
- if (n < 0) {
3131
- throw new RangeError('object identifier component ' +
3132
- address[i] + ' is negative');
3133
- }
3134
- if (n > MAX_INT32) {
3135
- throw new RangeError('object identifier component ' +
3136
- address[i] + ' is too large');
3137
- }
3138
- oidArray.push(n);
3139
- }
3140
-
3141
- return oidArray;
3142
-
3143
-};
3144
-
3145
-var MibRequest = function (requestDefinition) {
3146
- this.operation = requestDefinition.operation;
3147
- this.address = Mib.convertOidToAddress(requestDefinition.oid);
3148
- this.oid = this.address.join('.');
3149
- this.providerNode = requestDefinition.providerNode;
3150
- this.instanceNode = requestDefinition.instanceNode;
3151
-};
3152
-
3153
-MibRequest.prototype.isScalar = function () {
3154
- return this.providerNode && this.providerNode.provider &&
3155
- this.providerNode.provider.type == MibProviderType.Scalar;
3156
-};
3157
-
3158
-MibRequest.prototype.isTabular = function () {
3159
- return this.providerNode && this.providerNode.provider &&
3160
- this.providerNode.provider.type == MibProviderType.Table;
3161
-};
3162
-
3163
-var Agent = function (options, callback) {
3164
- DEBUG = options.debug;
3165
- this.listener = new Listener(options, this);
3166
- this.engine = new Engine(options.engineID);
3167
- this.authorizer = new Authorizer();
3168
- this.mib = new Mib();
3169
- this.callback = callback || function () {
3170
- };
3171
- this.context = "";
3172
-};
3173
-
3174
-Agent.prototype.getMib = function () {
3175
- return this.mib;
3176
-};
3177
-
3178
-Agent.prototype.getAuthorizer = function () {
3179
- return this.authorizer;
3180
-};
3181
-
3182
-Agent.prototype.registerProvider = function (provider) {
3183
- this.mib.registerProvider(provider);
3184
-};
3185
-
3186
-Agent.prototype.unregisterProvider = function (provider) {
3187
- this.mib.unregisterProvider(provider);
3188
-};
3189
-
3190
-Agent.prototype.getProvider = function (provider) {
3191
- return this.mib.getProvider(provider);
3192
-};
3193
-
3194
-Agent.prototype.getProviders = function () {
3195
- return this.mib.getProviders();
3196
-};
3197
-
3198
-Agent.prototype.onMsg = function (buffer, rinfo) {
3199
- var message = Listener.processIncoming(buffer, this.authorizer, this.callback);
3200
- var reportMessage;
3201
- var responseMessage;
3202
-
3203
- if (!message) {
3204
- return;
3205
- }
3206
-
3207
- // SNMPv3 discovery
3208
- if (message.version == Version3 && message.pdu.type == PduType.GetRequest &&
3209
- !message.hasAuthoritativeEngineID() && message.isReportable()) {
3210
- reportMessage = message.createReportResponseMessage(this.engine, this.context);
3211
- this.listener.send(reportMessage, rinfo);
3212
- return;
3213
- }
3214
-
3215
- // Request processing
3216
- debug(JSON.stringify(message.pdu, null, 2));
3217
- if (message.pdu.type == PduType.GetRequest) {
3218
- responseMessage = this.request(message, rinfo);
3219
- } else if (message.pdu.type == PduType.SetRequest) {
3220
- responseMessage = this.request(message, rinfo);
3221
- } else if (message.pdu.type == PduType.GetNextRequest) {
3222
- responseMessage = this.getNextRequest(message, rinfo);
3223
- } else if (message.pdu.type == PduType.GetBulkRequest) {
3224
- responseMessage = this.getBulkRequest(message, rinfo);
3225
- } else {
3226
- this.callback(new RequestInvalidError("Unexpected PDU type " +
3227
- message.pdu.type + " (" + PduType[message.pdu.type] + ")"));
3228
- }
3229
-
3230
-};
3231
-
3232
-Agent.prototype.request = function (requestMessage, rinfo) {
3233
- var me = this;
3234
- var varbindsCompleted = 0;
3235
- var requestPdu = requestMessage.pdu;
3236
- var varbindsLength = requestPdu.varbinds.length;
3237
- var responsePdu = requestPdu.getResponsePduForRequest();
3238
-
3239
- for (var i = 0; i < requestPdu.varbinds.length; i++) {
3240
- var requestVarbind = requestPdu.varbinds[i];
3241
- var instanceNode = this.mib.lookup(requestVarbind.oid);
3242
- var providerNode;
3243
- var mibRequest;
3244
- var handler;
3245
- var responseVarbindType;
3246
-
3247
- if (!instanceNode) {
3248
- mibRequest = new MibRequest({
3249
- operation: requestPdu.type,
3250
- oid: requestVarbind.oid
3251
- });
3252
- handler = function getNsoHandler(mibRequestForNso) {
3253
- mibRequestForNso.done({
3254
- errorStatus: ErrorStatus.NoSuchName,
3255
- errorIndex: i
3256
- });
3257
- };
3258
- } else {
3259
- providerNode = this.mib.getProviderNodeForInstance(instanceNode);
3260
- mibRequest = new MibRequest({
3261
- operation: requestPdu.type,
3262
- providerNode: providerNode,
3263
- instanceNode: instanceNode,
3264
- oid: requestVarbind.oid
3265
- });
3266
- handler = providerNode.provider.handler;
3267
- }
3268
-
3269
- mibRequest.done = function (error) {
3270
- if (error) {
3271
- responsePdu.errorStatus = error.errorStatus;
3272
- responsePdu.errorIndex = error.errorIndex;
3273
- responseVarbind = {
3274
- oid: mibRequest.oid,
3275
- type: ObjectType.Null,
3276
- value: null
3277
- };
3278
- } else {
3279
- if (requestPdu.type == PduType.SetRequest) {
3280
- mibRequest.instanceNode.value = requestVarbind.value;
3281
- }
3282
- if (requestPdu.type == PduType.GetNextRequest && requestVarbind.type == ObjectType.EndOfMibView) {
3283
- responseVarbindType = ObjectType.EndOfMibView;
3284
- } else {
3285
- responseVarbindType = mibRequest.instanceNode.valueType;
3286
- }
3287
- responseVarbind = {
3288
- oid: mibRequest.oid,
3289
- type: responseVarbindType,
3290
- value: mibRequest.instanceNode.value
3291
- };
3292
- }
3293
- me.setSingleVarbind(responsePdu, i, responseVarbind);
3294
- if (++varbindsCompleted == varbindsLength) {
3295
- me.sendResponse.call(me, rinfo, requestMessage, responsePdu);
3296
- }
3297
- };
3298
- if (handler) {
3299
- handler(mibRequest);
3300
- } else {
3301
- mibRequest.done();
3302
- }
3303
- }
3304
- ;
3305
-};
3306
-
3307
-Agent.prototype.addGetNextVarbind = function (targetVarbinds, startOid) {
3308
- var startNode = this.mib.lookup(startOid);
3309
- var getNextNode;
3310
-
3311
- if (!startNode) {
3312
- // Off-tree start specified
3313
- targetVarbinds.push({
3314
- oid: requestVarbind.oid,
3315
- type: ObjectType.Null,
3316
- value: null
3317
- });
3318
- } else {
3319
- getNextNode = startNode.getNextInstanceNode();
3320
- if (!getNextNode) {
3321
- // End of MIB
3322
- targetVarbinds.push({
3323
- oid: requestVarbind.oid,
3324
- type: ObjectType.EndOfMibView,
3325
- value: null
3326
- });
3327
- } else {
3328
- // Normal response
3329
- targetVarbinds.push({
3330
- oid: getNextNode.oid,
3331
- type: getNextNode.valueType,
3332
- value: getNextNode.value
3333
- });
3334
- }
3335
- }
3336
- return getNextNode;
3337
-};
3338
-
3339
-Agent.prototype.getNextRequest = function (requestMessage, rinfo) {
3340
- var requestPdu = requestMessage.pdu;
3341
- var varbindsLength = requestPdu.varbinds.length;
3342
- var getNextVarbinds = [];
3343
-
3344
- for (var i = 0; i < varbindsLength; i++) {
3345
- this.addGetNextVarbind(getNextVarbinds, requestPdu.varbinds[i].oid);
3346
- }
3347
-
3348
- requestMessage.pdu.varbinds = getNextVarbinds;
3349
- this.request(requestMessage, rinfo);
3350
-};
3351
-
3352
-Agent.prototype.getBulkRequest = function (requestMessage, rinfo) {
3353
- var requestPdu = requestMessage.pdu;
3354
- var requestVarbinds = requestPdu.varbinds;
3355
- var getBulkVarbinds = [];
3356
- var startOid = [];
3357
- var getNextNode;
3358
-
3359
- for (var n = 0; n < requestPdu.nonRepeaters; n++) {
3360
- this.addGetNextVarbind(getBulkVarbinds, requestVarbinds[n].oid);
3361
- }
3362
-
3363
- for (var v = requestPdu.nonRepeaters; v < requestVarbinds.length; v++) {
3364
- startOid.push(requestVarbinds[v].oid);
3365
- }
3366
-
3367
- for (var r = 0; r < requestPdu.maxRepetitions; r++) {
3368
- for (var v = requestPdu.nonRepeaters; v < requestVarbinds.length; v++) {
3369
- getNextNode = this.addGetNextVarbind(getBulkVarbinds, startOid[v - requestPdu.nonRepeaters]);
3370
- if (getNextNode) {
3371
- startOid[v - requestPdu.nonRepeaters] = getNextNode.oid;
3372
- }
3373
- }
3374
- }
3375
-
3376
- requestMessage.pdu.varbinds = getBulkVarbinds;
3377
- this.request(requestMessage, rinfo);
3378
-};
3379
-
3380
-Agent.prototype.setSingleVarbind = function (responsePdu, index, responseVarbind) {
3381
- responsePdu.varbinds[index] = responseVarbind;
3382
-};
3383
-
3384
-Agent.prototype.sendResponse = function (rinfo, requestMessage, responsePdu) {
3385
- var responseMessage = requestMessage.createResponseForRequest(responsePdu);
3386
- this.listener.send(responseMessage, rinfo);
3387
- this.callback(null, Listener.formatCallbackData(responseMessage.pdu, rinfo));
3388
-};
3389
-
3390
-Agent.create = function (options, callback) {
3391
- var agent = new Agent(options, callback);
3392
- agent.listener.startListening();
3393
- return agent;
3394
-};
3395
-
3396
-/*****************************************************************************
3397
- ** Exports
3398
- **/
3399
-
3400
-exports.Session = Session;
3401
-
3402
-exports.createSession = function (target, community, options) {
3403
- if (options.version && !(options.version == Version1 || options.version == Version2c)) {
3404
- throw new ResponseInvalidError("SNMP community session requested but version '" + options.version + "' specified in options not valid");
3405
- } else {
3406
- return new Session(target, community, options);
3407
- }
3408
-};
3409
-
3410
-exports.createV3Session = function (target, user, options) {
3411
- if (options.version && options.version != Version3) {
3412
- throw new ResponseInvalidError("SNMPv3 session requested but version '" + options.version + "' specified in options");
3413
- } else {
3414
- options.version = Version3;
3415
- }
3416
- return new Session(target, user, options);
3417
-};
3418
-
3419
-exports.createReceiver = Receiver.create;
3420
-exports.createAgent = Agent.create;
3421
-
3422
-exports.isVarbindError = isVarbindError;
3423
-exports.varbindError = varbindError;
3424
-
3425
-exports.Version1 = Version1;
3426
-exports.Version2c = Version2c;
3427
-exports.Version3 = Version3;
3428
-exports.Version = Version;
3429
-
3430
-exports.ErrorStatus = ErrorStatus;
3431
-exports.TrapType = TrapType;
3432
-exports.ObjectType = ObjectType;
3433
-exports.PduType = PduType;
3434
-exports.MibProviderType = MibProviderType;
3435
-exports.SecurityLevel = SecurityLevel;
3436
-exports.AuthProtocols = AuthProtocols;
3437
-exports.PrivProtocols = PrivProtocols;
3438
-
3439
-exports.ResponseInvalidError = ResponseInvalidError;
3440
-exports.RequestInvalidError = RequestInvalidError;
3441
-exports.RequestFailedError = RequestFailedError;
3442
-exports.RequestTimedOutError = RequestTimedOutError;
3443
-
3444
-/**
3445
- ** We've added this for testing.
3446
- **/
3447
-exports.ObjectParser = {
3448
- readInt: readInt,
3449
- readUint: readUint
3450
-};
3451
-exports.Authentication = Authentication;
3452
-exports.Encryption = Encryption;
collectors/node.d.plugin/node_modules/netdata.js
deleted
-654
@@ -1,654 +0,0 @@
1
-'use strict';
2
-
3
-// netdata
4
-// real-time performance and health monitoring, done right!
5
-// (C) 2016 Costa Tsaousis <costa@tsaousis.gr>
6
-// SPDX-License-Identifier: GPL-3.0-or-later
7
-
8
-var url = require('url');
9
-var http = require('http');
10
-var util = require('util');
11
-
12
-/*
13
-var netdata = require('netdata');
14
-
15
-var example_chart = {
16
- id: 'id', // the unique id of the chart
17
- name: 'name', // the name of the chart
18
- title: 'title', // the title of the chart
19
- units: 'units', // the units of the chart dimensions
20
- family: 'family', // the family of the chart
21
- context: 'context', // the context of the chart
22
- type: netdata.chartTypes.line, // the type of the chart
23
- priority: 0, // the priority relative to others in the same family
24
- update_every: 1, // the expected update frequency of the chart
25
- dimensions: {
26
- 'dim1': {
27
- id: 'dim1', // the unique id of the dimension
28
- name: 'name', // the name of the dimension
29
- algorithm: netdata.chartAlgorithms.absolute, // the id of the netdata algorithm
30
- multiplier: 1, // the multiplier
31
- divisor: 1, // the divisor
32
- hidden: false, // is hidden (boolean)
33
- },
34
- 'dim2': {
35
- id: 'dim2', // the unique id of the dimension
36
- name: 'name', // the name of the dimension
37
- algorithm: 'absolute', // the id of the netdata algorithm
38
- multiplier: 1, // the multiplier
39
- divisor: 1, // the divisor
40
- hidden: false, // is hidden (boolean)
41
- }
42
- // add as many dimensions as needed
43
- }
44
-};
45
-*/
46
-
47
-var netdata = {
48
- options: {
49
- filename: __filename,
50
- DEBUG: false,
51
- update_every: 1
52
- },
53
-
54
- chartAlgorithms: {
55
- incremental: 'incremental',
56
- absolute: 'absolute',
57
- percentage_of_absolute_row: 'percentage-of-absolute-row',
58
- percentage_of_incremental_row: 'percentage-of-incremental-row'
59
- },
60
-
61
- chartTypes: {
62
- line: 'line',
63
- area: 'area',
64
- stacked: 'stacked'
65
- },
66
-
67
- services: new Array(),
68
- modules_configuring: 0,
69
- charts: {},
70
-
71
- processors: {
72
- http: {
73
- name: 'http',
74
-
75
- process: function(service, callback) {
76
- var __DEBUG = netdata.options.DEBUG;
77
-
78
- if(__DEBUG === true)
79
- netdata.debug(service.module.name + ': ' + service.name + ': making ' + this.name + ' request: ' + netdata.stringify(service.request));
80
-
81
- var req = http.request(service.request, function(response) {
82
- if(__DEBUG === true) netdata.debug(service.module.name + ': ' + service.name + ': got server response...');
83
-
84
- var end = false;
85
- var data = '';
86
- response.setEncoding('utf8');
87
-
88
- if(response.statusCode !== 200) {
89
- if(end === false) {
90
- service.error('Got HTTP code ' + response.statusCode + ', failed to get data.');
91
- end = true;
92
- return callback(null);
93
- }
94
- }
95
-
96
- response.on('data', function(chunk) {
97
- if(end === false) data += chunk;
98
- });
99
-
100
- response.on('error', function() {
101
- if(end === false) {
102
- service.error(': Read error, failed to get data.');
103
- end = true;
104
- return callback(null);
105
- }
106
- });
107
-
108
- response.on('end', function() {
109
- if(end === false) {
110
- if(__DEBUG === true) netdata.debug(service.module.name + ': ' + service.name + ': read completed.');
111
- end = true;
112
- return callback(data);
113
- }
114
- });
115
- });
116
-
117
- req.on('error', function(e) {
118
- if(__DEBUG === true) netdata.debug('Failed to make request: ' + netdata.stringify(service.request) + ', message: ' + e.message);
119
- service.error('Failed to make request, message: ' + e.message);
120
- return callback(null);
121
- });
122
-
123
- // write data to request body
124
- if(typeof service.postData !== 'undefined' && service.request.method === 'POST') {
125
- if(__DEBUG === true) netdata.debug(service.module.name + ': ' + service.name + ': posting data: ' + service.postData);
126
- req.write(service.postData);
127
- }
128
-
129
- req.end();
130
- }
131
- }
132
- },
133
-
134
- stringify: function(obj) {
135
- return util.inspect(obj, {depth: 10});
136
- },
137
-
138
- zeropad2: function(s) {
139
- return ("00" + s).slice(-2);
140
- },
141
-
142
- logdate: function(d) {
143
- if(typeof d === 'undefined') d = new Date();
144
- return d.getFullYear().toString() + '-' + this.zeropad2(d.getMonth() + 1) + '-' + this.zeropad2(d.getDate())
145
- + ' ' + this.zeropad2(d.getHours()) + ':' + this.zeropad2(d.getMinutes()) + ':' + this.zeropad2(d.getSeconds());
146
- },
147
-
148
- // show debug info, if debug is enabled
149
- debug: function(msg) {
150
- if(this.options.DEBUG === true) {
151
- console.error(this.logdate() + ': ' + netdata.options.filename + ': DEBUG: ' + ((typeof(msg) === 'object')?netdata.stringify(msg):msg).toString());
152
- }
153
- },
154
-
155
- // log an error
156
- error: function(msg) {
157
- console.error(this.logdate() + ': ' + netdata.options.filename + ': ERROR: ' + ((typeof(msg) === 'object')?netdata.stringify(msg):msg).toString());
158
- },
159
-
160
- // send data to netdata
161
- send: function(msg) {
162
- console.log(msg.toString());
163
- },
164
-
165
- service: function(service) {
166
- if(typeof service === 'undefined')
167
- service = {};
168
-
169
- var now = Date.now();
170
-
171
- service._current_chart = null; // the current chart we work on
172
- service._queue = ''; // data to be sent to netdata
173
-
174
- service.error_reported = false; // error log flood control
175
-
176
- service.added = false; // added to netdata.services
177
- service.enabled = true;
178
- service.updates = 0;
179
- service.running = false;
180
- service.started = 0;
181
- service.ended = 0;
182
-
183
- if(typeof service.module === 'undefined') {
184
- service.module = { name: 'not-defined-module' };
185
- service.error('Attempted to create service without a module.');
186
- service.enabled = false;
187
- }
188
-
189
- if(typeof service.name === 'undefined') {
190
- service.name = 'unnamed@' + service.module.name + '/' + now;
191
- }
192
-
193
- if(typeof service.processor === 'undefined')
194
- service.processor = netdata.processors.http;
195
-
196
- if(typeof service.update_every === 'undefined')
197
- service.update_every = service.module.update_every;
198
-
199
- if(typeof service.update_every === 'undefined')
200
- service.update_every = netdata.options.update_every;
201
-
202
- if(service.update_every < netdata.options.update_every)
203
- service.update_every = netdata.options.update_every;
204
-
205
- // align the runs
206
- service.next_run = now - (now % (service.update_every * 1000)) + (service.update_every * 1000);
207
-
208
- service.commit = function() {
209
- if(this.added !== true) {
210
- this.added = true;
211
-
212
- var now = Date.now();
213
- this.next_run = now - (now % (service.update_every * 1000)) + (service.update_every * 1000);
214
-
215
- netdata.services.push(this);
216
- if(netdata.options.DEBUG === true) netdata.debug(this.module.name + ': ' + this.name + ': service committed.');
217
- }
218
- };
219
-
220
- service.execute = function(responseProcessor) {
221
- var __DEBUG = netdata.options.DEBUG;
222
-
223
- if(service.enabled === false)
224
- return responseProcessor(null);
225
-
226
- this.module.active++;
227
- this.running = true;
228
- this.started = Date.now();
229
- this.updates++;
230
-
231
- if(__DEBUG === true)
232
- netdata.debug(this.module.name + ': ' + this.name + ': making ' + this.processor.name + ' request: ' + netdata.stringify(this));
233
-
234
- this.processor.process(this, function(response) {
235
- service.ended = Date.now();
236
- service.duration = service.ended - service.started;
237
-
238
- if(typeof response === 'undefined')
239
- response = null;
240
-
241
- if(response !== null)
242
- service.errorClear();
243
-
244
- if(__DEBUG === true)
245
- netdata.debug(service.module.name + ': ' + service.name + ': processing ' + service.processor.name + ' response (received in ' + (service.ended - service.started).toString() + ' ms)');
246
-
247
- try {
248
- responseProcessor(service, response);
249
- }
250
- catch(e) {
251
- netdata.error(e);
252
- service.error("responseProcessor failed process response data.");
253
- }
254
-
255
- service.running = false;
256
- service.module.active--;
257
- if(service.module.active < 0) {
258
- service.module.active = 0;
259
- if(__DEBUG === true)
260
- netdata.debug(service.module.name + ': active module counter below zero.');
261
- }
262
-
263
- if(service.module.active === 0) {
264
- // check if we run under configure
265
- if(service.module.configure_callback !== null) {
266
- if(__DEBUG === true)
267
- netdata.debug(service.module.name + ': configuration finish callback called from processResponse().');
268
-
269
- var configure_callback = service.module.configure_callback;
270
- service.module.configure_callback = null;
271
- configure_callback();
272
- }
273
- }
274
- });
275
- };
276
-
277
- service.update = function() {
278
- if(netdata.options.DEBUG === true)
279
- netdata.debug(this.module.name + ': ' + this.name + ': starting data collection...');
280
-
281
- this.module.update(this, function() {
282
- if(netdata.options.DEBUG === true)
283
- netdata.debug(service.module.name + ': ' + service.name + ': data collection ended in ' + service.duration.toString() + ' ms.');
284
- });
285
- };
286
-
287
- service.error = function(message) {
288
- if(this.error_reported === false) {
289
- netdata.error(this.module.name + ': ' + this.name + ': ' + message);
290
- this.error_reported = true;
291
- }
292
- else if(netdata.options.DEBUG === true)
293
- netdata.debug(this.module.name + ': ' + this.name + ': ' + message);
294
- };
295
-
296
- service.errorClear = function() {
297
- this.error_reported = false;
298
- };
299
-
300
- service.queue = function(txt) {
301
- this._queue += txt + '\n';
302
- };
303
-
304
- service._send_chart_to_netdata = function(chart) {
305
- // internal function to send a chart to netdata
306
- this.queue('CHART "' + chart.id + '" "' + chart.name + '" "' + chart.title + '" "' + chart.units + '" "' + chart.family + '" "' + chart.context + '" "' + chart.type + '" ' + chart.priority.toString() + ' ' + chart.update_every.toString());
307
-
308
- if(typeof(chart.dimensions) !== 'undefined') {
309
- var dims = Object.keys(chart.dimensions);
310
- var len = dims.length;
311
- while(len--) {
312
- var d = chart.dimensions[dims[len]];
313
-
314
- this.queue('DIMENSION "' + d.id + '" "' + d.name + '" "' + d.algorithm + '" ' + d.multiplier.toString() + ' ' + d.divisor.toString() + ' ' + ((d.hidden === true) ? 'hidden' : '').toString());
315
- d._created = true;
316
- d._updated = false;
317
- }
318
- }
319
-
320
- chart._created = true;
321
- chart._updated = false;
322
- };
323
-
324
- // begin data collection for a chart
325
- service.begin = function(chart) {
326
- if(this._current_chart !== null && this._current_chart !== chart) {
327
- this.error('Called begin() for chart ' + chart.id + ' while chart ' + this._current_chart.id + ' is still open. Closing it.');
328
- this.end();
329
- }
330
-
331
- if(typeof(chart.id) === 'undefined' || netdata.charts[chart.id] !== chart) {
332
- this.error('Called begin() for chart ' + chart.id + ' that is not mine. Where did you find it? Ignoring it.');
333
- return false;
334
- }
335
-
336
- if(netdata.options.DEBUG === true) netdata.debug('setting current chart to ' + chart.id);
337
- this._current_chart = chart;
338
- this._current_chart._began = true;
339
-
340
- if(this._current_chart._dimensions_count !== 0) {
341
- if(this._current_chart._created === false || this._current_chart._updated === true)
342
- this._send_chart_to_netdata(this._current_chart);
343
-
344
- var now = this.ended;
345
- this.queue('BEGIN ' + this._current_chart.id + ' ' + ((this._current_chart._last_updated > 0)?((now - this._current_chart._last_updated) * 1000):'').toString());
346
- }
347
- // else this.error('Called begin() for chart ' + chart.id + ' which is empty.');
348
-
349
- this._current_chart._last_updated = now;
350
- this._current_chart._began = true;
351
- this._current_chart._counter++;
352
-
353
- return true;
354
- };
355
-
356
- // set a collected value for a chart
357
- // we do most things on the first value we attempt to set
358
- service.set = function(dimension, value) {
359
- if(this._current_chart === null) {
360
- this.error('Called set(' + dimension + ', ' + value + ') without an open chart.');
361
- return false;
362
- }
363
-
364
- if(typeof(this._current_chart.dimensions[dimension]) === 'undefined') {
365
- this.error('Called set(' + dimension + ', ' + value + ') but dimension "' + dimension + '" does not exist in chart "' + this._current_chart.id + '".');
366
- return false;
367
- }
368
-
369
- if(typeof value === 'undefined' || value === null)
370
- return false;
371
-
372
- if(this._current_chart._dimensions_count !== 0)
373
- this.queue('SET ' + dimension + ' = ' + value.toString());
374
-
375
- return true;
376
- };
377
-
378
- // end data collection for the current chart - after calling begin()
379
- service.end = function() {
380
- if(this._current_chart !== null && this._current_chart._began === false) {
381
- this.error('Called end() without an open chart.');
382
- return false;
383
- }
384
-
385
- if(this._current_chart._dimensions_count !== 0) {
386
- this.queue('END');
387
- netdata.send(this._queue);
388
- }
389
-
390
- this._queue = '';
391
- this._current_chart._began = false;
392
- if(netdata.options.DEBUG === true) netdata.debug('sent chart ' + this._current_chart.id);
393
- this._current_chart = null;
394
- return true;
395
- };
396
-
397
- // discard the collected values for the current chart - after calling begin()
398
- service.flush = function() {
399
- if(this._current_chart === null || this._current_chart._began === false) {
400
- this.error('Called flush() without an open chart.');
401
- return false;
402
- }
403
-
404
- this._queue = '';
405
- this._current_chart._began = false;
406
- this._current_chart = null;
407
- return true;
408
- };
409
-
410
- // create a netdata chart
411
- service.chart = function(id, chart) {
412
- var __DEBUG = netdata.options.DEBUG;
413
-
414
- if(typeof(netdata.charts[id]) === 'undefined') {
415
- netdata.charts[id] = {
416
- _created: false,
417
- _updated: true,
418
- _began: false,
419
- _counter: 0,
420
- _last_updated: 0,
421
- _dimensions_count: 0,
422
- id: id,
423
- name: id,
424
- title: 'untitled chart',
425
- units: 'a unit',
426
- family: '',
427
- context: '',
428
- type: netdata.chartTypes.line,
429
- priority: 50000,
430
- update_every: netdata.options.update_every,
431
- dimensions: {}
432
- };
433
- }
434
-
435
- var c = netdata.charts[id];
436
-
437
- if(typeof(chart.name) !== 'undefined' && chart.name !== c.name) {
438
- if(__DEBUG === true) netdata.debug('chart ' + id + ' updated its name');
439
- c.name = chart.name;
440
- c._updated = true;
441
- }
442
-
443
- if(typeof(chart.title) !== 'undefined' && chart.title !== c.title) {
444
- if(__DEBUG === true) netdata.debug('chart ' + id + ' updated its title');
445
- c.title = chart.title;
446
- c._updated = true;
447
- }
448
-
449
- if(typeof(chart.units) !== 'undefined' && chart.units !== c.units) {
450
- if(__DEBUG === true) netdata.debug('chart ' + id + ' updated its units');
451
- c.units = chart.units;
452
- c._updated = true;
453
- }
454
-
455
- if(typeof(chart.family) !== 'undefined' && chart.family !== c.family) {
456
- if(__DEBUG === true) netdata.debug('chart ' + id + ' updated its family');
457
- c.family = chart.family;
458
- c._updated = true;
459
- }
460
-
461
- if(typeof(chart.context) !== 'undefined' && chart.context !== c.context) {
462
- if(__DEBUG === true) netdata.debug('chart ' + id + ' updated its context');
463
- c.context = chart.context;
464
- c._updated = true;
465
- }
466
-
467
- if(typeof(chart.type) !== 'undefined' && chart.type !== c.type) {
468
- if(__DEBUG === true) netdata.debug('chart ' + id + ' updated its type');
469
- c.type = chart.type;
470
- c._updated = true;
471
- }
472
-
473
- if(typeof(chart.priority) !== 'undefined' && chart.priority !== c.priority) {
474
- if(__DEBUG === true) netdata.debug('chart ' + id + ' updated its priority');
475
- c.priority = chart.priority;
476
- c._updated = true;
477
- }
478
-
479
- if(typeof(chart.update_every) !== 'undefined' && chart.update_every !== c.update_every) {
480
- if(__DEBUG === true) netdata.debug('chart ' + id + ' updated its update_every from ' + c.update_every + ' to ' + chart.update_every);
481
- c.update_every = chart.update_every;
482
- c._updated = true;
483
- }
484
-
485
- if(typeof(chart.dimensions) !== 'undefined') {
486
- var dims = Object.keys(chart.dimensions);
487
- var len = dims.length;
488
- while(len--) {
489
- var x = dims[len];
490
-
491
- if(typeof(c.dimensions[x]) === 'undefined') {
492
- c._dimensions_count++;
493
-
494
- c.dimensions[x] = {
495
- _created: false,
496
- _updated: false,
497
- id: x, // the unique id of the dimension
498
- name: x, // the name of the dimension
499
- algorithm: netdata.chartAlgorithms.absolute, // the id of the netdata algorithm
500
- multiplier: 1, // the multiplier
501
- divisor: 1, // the divisor
502
- hidden: false // is hidden (boolean)
503
- };
504
-
505
- if(__DEBUG === true) netdata.debug('chart ' + id + ' created dimension ' + x);
506
- c._updated = true;
507
- }
508
-
509
- var dim = chart.dimensions[x];
510
- var d = c.dimensions[x];
511
-
512
- if(typeof(dim.name) !== 'undefined' && d.name !== dim.name) {
513
- if(__DEBUG === true) netdata.debug('chart ' + id + ', dimension ' + x + ' updated its name');
514
- d.name = dim.name;
515
- d._updated = true;
516
- }
517
-
518
- if(typeof(dim.algorithm) !== 'undefined' && d.algorithm !== dim.algorithm) {
519
- if(__DEBUG === true) netdata.debug('chart ' + id + ', dimension ' + x + ' updated its algorithm from ' + d.algorithm + ' to ' + dim.algorithm);
520
- d.algorithm = dim.algorithm;
521
- d._updated = true;
522
- }
523
-
524
- if(typeof(dim.multiplier) !== 'undefined' && d.multiplier !== dim.multiplier) {
525
- if(__DEBUG === true) netdata.debug('chart ' + id + ', dimension ' + x + ' updated its multiplier');
526
- d.multiplier = dim.multiplier;
527
- d._updated = true;
528
- }
529
-
530
- if(typeof(dim.divisor) !== 'undefined' && d.divisor !== dim.divisor) {
531
- if(__DEBUG === true) netdata.debug('chart ' + id + ', dimension ' + x + ' updated its divisor');
532
- d.divisor = dim.divisor;
533
- d._updated = true;
534
- }
535
-
536
- if(typeof(dim.hidden) !== 'undefined' && d.hidden !== dim.hidden) {
537
- if(__DEBUG === true) netdata.debug('chart ' + id + ', dimension ' + x + ' updated its hidden status');
538
- d.hidden = dim.hidden;
539
- d._updated = true;
540
- }
541
-
542
- if(d._updated) c._updated = true;
543
- }
544
- }
545
-
546
- //if(netdata.options.DEBUG === true) netdata.debug(netdata.charts);
547
- return netdata.charts[id];
548
- };
549
-
550
- return service;
551
- },
552
-
553
- runAllServices: function() {
554
- if(netdata.options.DEBUG === true) netdata.debug('runAllServices()');
555
-
556
- var now = Date.now();
557
- var len = netdata.services.length;
558
- while(len--) {
559
- var service = netdata.services[len];
560
-
561
- if(service.enabled === false || service.running === true) continue;
562
- if(now <= service.next_run) continue;
563
-
564
- service.update();
565
-
566
- now = Date.now();
567
- service.next_run = now - (now % (service.update_every * 1000)) + (service.update_every * 1000);
568
- }
569
-
570
- // 1/10th of update_every in pause
571
- setTimeout(netdata.runAllServices, netdata.options.update_every * 100);
572
- },
573
-
574
- start: function() {
575
- if(netdata.options.DEBUG === true) this.debug('started, services: ' + netdata.stringify(this.services));
576
-
577
- if(this.services.length === 0) {
578
- this.disableNodePlugin();
579
-
580
- // eslint suggested way to exit
581
- var exit = process.exit;
582
- exit(1);
583
- }
584
- else this.runAllServices();
585
- },
586
-
587
- // disable the whole node.js plugin
588
- disableNodePlugin: function() {
589
- this.send('DISABLE');
590
-
591
- // eslint suggested way to exit
592
- var exit = process.exit;
593
- exit(1);
594
- },
595
-
596
- requestFromParams: function(protocol, hostname, port, path, method) {
597
- return {
598
- protocol: protocol,
599
- hostname: hostname,
600
- port: port,
601
- path: path,
602
- //family: 4,
603
- method: method,
604
- headers: {
605
- 'Content-Type': 'application/x-www-form-urlencoded',
606
- 'Connection': 'keep-alive'
607
- },
608
- agent: new http.Agent({
609
- keepAlive: true,
610
- keepAliveMsecs: netdata.options.update_every * 1000,
611
- maxSockets: 2, // it must be 2 to work
612
- maxFreeSockets: 1
613
- })
614
- };
615
- },
616
-
617
- requestFromURL: function(a_url) {
618
- var u = url.parse(a_url);
619
- return netdata.requestFromParams(u.protocol, u.hostname, u.port, u.path, 'GET');
620
- },
621
-
622
- configure: function(module, config, callback) {
623
- if(netdata.options.DEBUG === true) this.debug(module.name + ': configuring (update_every: ' + this.options.update_every + ')...');
624
-
625
- module.active = 0;
626
- module.update_every = this.options.update_every;
627
-
628
- if(typeof config.update_every !== 'undefined')
629
- module.update_every = config.update_every;
630
-
631
- module.enable_autodetect = (config.enable_autodetect)?true:false;
632
-
633
- if(typeof(callback) === 'function')
634
- module.configure_callback = callback;
635
- else
636
- module.configure_callback = null;
637
-
638
- var added = module.configure(config);
639
-
640
- if(netdata.options.DEBUG === true) this.debug(module.name + ': configured, reporting ' + added + ' eligible services.');
641
-
642
- if(module.configure_callback !== null && added === 0) {
643
- if(netdata.options.DEBUG === true) this.debug(module.name + ': configuration finish callback called from configure().');
644
- var configure_callback = module.configure_callback;
645
- module.configure_callback = null;
646
- configure_callback();
647
- }
648
-
649
- return added;
650
- }
651
-};
652
-
653
-if(netdata.options.DEBUG === true) netdata.debug('loaded netdata from:', __filename);
654
-module.exports = netdata;
collectors/node.d.plugin/node_modules/pixl-xml.js
deleted
-607
@@ -1,607 +0,0 @@
1
-// SPDX-License-Identifier: MIT
2
-/*
3
- JavaScript XML Library
4
- Plus a bunch of object utility functions
5
-
6
- Usage:
7
- var XML = require('pixl-xml');
8
- var myxmlstring = '<?xml version="1.0"?><Document>' +
9
- '<Simple>Hello</Simple>' +
10
- '<Node Key="Value">Content</Node>' +
11
- '</Document>';
12
-
13
- var tree = XML.parse( myxmlstring, { preserveAttributes: true });
14
- console.log( tree );
15
-
16
- tree.Simple = "Hello2";
17
- tree.Node._Attribs.Key = "Value2";
18
- tree.Node._Data = "Content2";
19
- tree.New = "I added this";
20
-
21
- console.log( XML.stringify( tree, 'Document' ) );
22
-
23
- Copyright (c) 2004 - 2015 Joseph Huckaby
24
- Released under the MIT License
25
- This version is for Node.JS, converted in 2012.
26
-*/
27
-
28
-var fs = require('fs');
29
-
30
-var indent_string = "\t";
31
-var xml_header = '<?xml version="1.0"?>';
32
-var sort_args = null;
33
-var re_valid_tag_name = /^\w[\w\-\:]*$/;
34
-
35
-var XML = exports.XML = function XML(args) {
36
- // class constructor for XML parser class
37
- // pass in args hash or text to parse
38
- if (!args) args = '';
39
- if (isa_hash(args)) {
40
- for (var key in args) this[key] = args[key];
41
- }
42
- else this.text = args || '';
43
-
44
- // stringify buffers
45
- if (this.text instanceof Buffer) {
46
- this.text = this.text.toString();
47
- }
48
-
49
- if (!this.text.match(/^\s*</)) {
50
- // try as file path
51
- var file = this.text;
52
- this.text = fs.readFileSync(file, { encoding: 'utf8' });
53
- if (!this.text) throw new Error("File not found: " + file);
54
- }
55
-
56
- this.tree = {};
57
- this.errors = [];
58
- this.piNodeList = [];
59
- this.dtdNodeList = [];
60
- this.documentNodeName = '';
61
-
62
- if (this.lowerCase) {
63
- this.attribsKey = this.attribsKey.toLowerCase();
64
- this.dataKey = this.dataKey.toLowerCase();
65
- }
66
-
67
- this.patTag.lastIndex = 0;
68
- if (this.text) this.parse();
69
-}
70
-
71
-XML.prototype.preserveAttributes = false;
72
-XML.prototype.lowerCase = false;
73
-
74
-XML.prototype.patTag = /([^<]*?)<([^>]+)>/g;
75
-XML.prototype.patSpecialTag = /^\s*([\!\?])/;
76
-XML.prototype.patPITag = /^\s*\?/;
77
-XML.prototype.patCommentTag = /^\s*\!--/;
78
-XML.prototype.patDTDTag = /^\s*\!DOCTYPE/;
79
-XML.prototype.patCDATATag = /^\s*\!\s*\[\s*CDATA/;
80
-XML.prototype.patStandardTag = /^\s*(\/?)([\w\-\:\.]+)\s*(.*)$/;
81
-XML.prototype.patSelfClosing = /\/\s*$/;
82
-XML.prototype.patAttrib = new RegExp("([\\w\\-\\:\\.]+)\\s*=\\s*([\\\"\\'])([^\\2]*?)\\2", "g");
83
-XML.prototype.patPINode = /^\s*\?\s*([\w\-\:]+)\s*(.*)$/;
84
-XML.prototype.patEndComment = /--$/;
85
-XML.prototype.patNextClose = /([^>]*?)>/g;
86
-XML.prototype.patExternalDTDNode = new RegExp("^\\s*\\!DOCTYPE\\s+([\\w\\-\\:]+)\\s+(SYSTEM|PUBLIC)\\s+\\\"([^\\\"]+)\\\"");
87
-XML.prototype.patInlineDTDNode = /^\s*\!DOCTYPE\s+([\w\-\:]+)\s+\[/;
88
-XML.prototype.patEndDTD = /\]$/;
89
-XML.prototype.patDTDNode = /^\s*\!DOCTYPE\s+([\w\-\:]+)\s+\[(.*)\]/;
90
-XML.prototype.patEndCDATA = /\]\]$/;
91
-XML.prototype.patCDATANode = /^\s*\!\s*\[\s*CDATA\s*\[([^]*)\]\]/;
92
-
93
-XML.prototype.attribsKey = '_Attribs';
94
-XML.prototype.dataKey = '_Data';
95
-
96
-XML.prototype.parse = function(branch, name) {
97
- // parse text into XML tree, recurse for nested nodes
98
- if (!branch) branch = this.tree;
99
- if (!name) name = null;
100
- var foundClosing = false;
101
- var matches = null;
102
-
103
- // match each tag, plus preceding text
104
- while ( matches = this.patTag.exec(this.text) ) {
105
- var before = matches[1];
106
- var tag = matches[2];
107
-
108
- // text leading up to tag = content of parent node
109
- if (before.match(/\S/)) {
110
- if (typeof(branch[this.dataKey]) != 'undefined') branch[this.dataKey] += ' '; else branch[this.dataKey] = '';
111
- branch[this.dataKey] += trim(decode_entities(before));
112
- }
113
-
114
- // parse based on tag type
115
- if (tag.match(this.patSpecialTag)) {
116
- // special tag
117
- if (tag.match(this.patPITag)) tag = this.parsePINode(tag);
118
- else if (tag.match(this.patCommentTag)) tag = this.parseCommentNode(tag);
119
- else if (tag.match(this.patDTDTag)) tag = this.parseDTDNode(tag);
120
- else if (tag.match(this.patCDATATag)) {
121
- tag = this.parseCDATANode(tag);
122
- if (typeof(branch[this.dataKey]) != 'undefined') branch[this.dataKey] += ' '; else branch[this.dataKey] = '';
123
- branch[this.dataKey] += trim(decode_entities(tag));
124
- } // cdata
125
- else {
126
- this.throwParseError( "Malformed special tag", tag );
127
- break;
128
- } // error
129
-
130
- if (tag == null) break;
131
- continue;
132
- } // special tag
133
- else {
134
- // Tag is standard, so parse name and attributes (if any)
135
- var matches = tag.match(this.patStandardTag);
136
- if (!matches) {
137
- this.throwParseError( "Malformed tag", tag );
138
- break;
139
- }
140
-
141
- var closing = matches[1];
142
- var nodeName = this.lowerCase ? matches[2].toLowerCase() : matches[2];
143
- var attribsRaw = matches[3];
144
-
145
- // If this is a closing tag, make sure it matches its opening tag
146
- if (closing) {
147
- if (nodeName == (name || '')) {
148
- foundClosing = 1;
149
- break;
150
- }
151
- else {
152
- this.throwParseError( "Mismatched closing tag (expected </" + name + ">)", tag );
153
- break;
154
- }
155
- } // closing tag
156
- else {
157
- // Not a closing tag, so parse attributes into hash. If tag
158
- // is self-closing, no recursive parsing is needed.
159
- var selfClosing = !!attribsRaw.match(this.patSelfClosing);
160
- var leaf = {};
161
- var attribs = leaf;
162
-
163
- // preserve attributes means they go into a sub-hash named "_Attribs"
164
- // the XML composer honors this for restoring the tree back into XML
165
- if (this.preserveAttributes) {
166
- leaf[this.attribsKey] = {};
167
- attribs = leaf[this.attribsKey];
168
- }
169
-
170
- // parse attributes
171
- this.patAttrib.lastIndex = 0;
172
- while ( matches = this.patAttrib.exec(attribsRaw) ) {
173
- var key = this.lowerCase ? matches[1].toLowerCase() : matches[1];
174
- attribs[ key ] = decode_entities( matches[3] );
175
- } // foreach attrib
176
-
177
- // if no attribs found, but we created the _Attribs subhash, clean it up now
178
- if (this.preserveAttributes && !num_keys(attribs)) {
179
- delete leaf[this.attribsKey];
180
- }
181
-
182
- // Recurse for nested nodes
183
- if (!selfClosing) {
184
- this.parse( leaf, nodeName );
185
- if (this.error()) break;
186
- }
187
-
188
- // Compress into simple node if text only
189
- var num_leaf_keys = num_keys(leaf);
190
- if ((typeof(leaf[this.dataKey]) != 'undefined') && (num_leaf_keys == 1)) {
191
- leaf = leaf[this.dataKey];
192
- }
193
- else if (!num_leaf_keys) {
194
- leaf = '';
195
- }
196
-
197
- // Add leaf to parent branch
198
- if (typeof(branch[nodeName]) != 'undefined') {
199
- if (isa_array(branch[nodeName])) {
200
- branch[nodeName].push( leaf );
201
- }
202
- else {
203
- var temp = branch[nodeName];
204
- branch[nodeName] = [ temp, leaf ];
205
- }
206
- }
207
- else {
208
- branch[nodeName] = leaf;
209
- }
210
-
211
- if (this.error() || (branch == this.tree)) break;
212
- } // not closing
213
- } // standard tag
214
- } // main reg exp
215
-
216
- // Make sure we found the closing tag
217
- if (name && !foundClosing) {
218
- this.throwParseError( "Missing closing tag (expected </" + name + ">)", name );
219
- }
220
-
221
- // If we are the master node, finish parsing and setup our doc node
222
- if (branch == this.tree) {
223
- if (typeof(this.tree[this.dataKey]) != 'undefined') delete this.tree[this.dataKey];
224
-
225
- if (num_keys(this.tree) > 1) {
226
- this.throwParseError( 'Only one top-level node is allowed in document', first_key(this.tree) );
227
- return;
228
- }
229
-
230
- this.documentNodeName = first_key(this.tree);
231
- if (this.documentNodeName) {
232
- this.tree = this.tree[this.documentNodeName];
233
- }
234
- }
235
-};
236
-
237
-XML.prototype.throwParseError = function(key, tag) {
238
- // log error and locate current line number in source XML document
239
- var parsedSource = this.text.substring(0, this.patTag.lastIndex);
240
- var eolMatch = parsedSource.match(/\n/g);
241
- var lineNum = (eolMatch ? eolMatch.length : 0) + 1;
242
- lineNum -= tag.match(/\n/) ? tag.match(/\n/g).length : 0;
243
-
244
- this.errors.push({
245
- type: 'Parse',
246
- key: key,
247
- text: '<' + tag + '>',
248
- line: lineNum
249
- });
250
-
251
- // Throw actual error (must wrap parse in try/catch)
252
- throw new Error( this.getLastError() );
253
-};
254
-
255
-XML.prototype.error = function() {
256
- // return number of errors
257
- return this.errors.length;
258
-};
259
-
260
-XML.prototype.getError = function(error) {
261
- // get formatted error
262
- var text = '';
263
- if (!error) return '';
264
-
265
- text = (error.type || 'General') + ' Error';
266
- if (error.code) text += ' ' + error.code;
267
- text += ': ' + error.key;
268
-
269
- if (error.line) text += ' on line ' + error.line;
270
- if (error.text) text += ': ' + error.text;
271
-
272
- return text;
273
-};
274
-
275
-XML.prototype.getLastError = function() {
276
- // Get most recently thrown error in plain text format
277
- if (!this.error()) return '';
278
- return this.getError( this.errors[this.errors.length - 1] );
279
-};
280
-
281
-XML.prototype.parsePINode = function(tag) {
282
- // Parse Processor Instruction Node, e.g. <?xml version="1.0"?>
283
- if (!tag.match(this.patPINode)) {
284
- this.throwParseError( "Malformed processor instruction", tag );
285
- return null;
286
- }
287
-
288
- this.piNodeList.push( tag );
289
- return tag;
290
-};
291
-
292
-XML.prototype.parseCommentNode = function(tag) {
293
- // Parse Comment Node, e.g. <!-- hello -->
294
- var matches = null;
295
- this.patNextClose.lastIndex = this.patTag.lastIndex;
296
-
297
- while (!tag.match(this.patEndComment)) {
298
- if (matches = this.patNextClose.exec(this.text)) {
299
- tag += '>' + matches[1];
300
- }
301
- else {
302
- this.throwParseError( "Unclosed comment tag", tag );
303
- return null;
304
- }
305
- }
306
-
307
- this.patTag.lastIndex = this.patNextClose.lastIndex;
308
- return tag;
309
-};
310
-
311
-XML.prototype.parseDTDNode = function(tag) {
312
- // Parse Document Type Descriptor Node, e.g. <!DOCTYPE ... >
313
- var matches = null;
314
-
315
- if (tag.match(this.patExternalDTDNode)) {
316
- // tag is external, and thus self-closing
317
- this.dtdNodeList.push( tag );
318
- }
319
- else if (tag.match(this.patInlineDTDNode)) {
320
- // Tag is inline, so check for nested nodes.
321
- this.patNextClose.lastIndex = this.patTag.lastIndex;
322
-
323
- while (!tag.match(this.patEndDTD)) {
324
- if (matches = this.patNextClose.exec(this.text)) {
325
- tag += '>' + matches[1];
326
- }
327
- else {
328
- this.throwParseError( "Unclosed DTD tag", tag );
329
- return null;
330
- }
331
- }
332
-
333
- this.patTag.lastIndex = this.patNextClose.lastIndex;
334
-
335
- // Make sure complete tag is well-formed, and push onto DTD stack.
336
- if (tag.match(this.patDTDNode)) {
337
- this.dtdNodeList.push( tag );
338
- }
339
- else {
340
- this.throwParseError( "Malformed DTD tag", tag );
341
- return null;
342
- }
343
- }
344
- else {
345
- this.throwParseError( "Malformed DTD tag", tag );
346
- return null;
347
- }
348
-
349
- return tag;
350
-};
351
-
352
-XML.prototype.parseCDATANode = function(tag) {
353
- // Parse CDATA Node, e.g. <![CDATA[Brooks & Shields]]>
354
- var matches = null;
355
- this.patNextClose.lastIndex = this.patTag.lastIndex;
356
-
357
- while (!tag.match(this.patEndCDATA)) {
358
- if (matches = this.patNextClose.exec(this.text)) {
359
- tag += '>' + matches[1];
360
- }
361
- else {
362
- this.throwParseError( "Unclosed CDATA tag", tag );
363
- return null;
364
- }
365
- }
366
-
367
- this.patTag.lastIndex = this.patNextClose.lastIndex;
368
-
369
- if (matches = tag.match(this.patCDATANode)) {
370
- return matches[1];
371
- }
372
- else {
373
- this.throwParseError( "Malformed CDATA tag", tag );
374
- return null;
375
- }
376
-};
377
-
378
-XML.prototype.getTree = function() {
379
- // get reference to parsed XML tree
380
- return this.tree;
381
-};
382
-
383
-XML.prototype.compose = function() {
384
- // compose tree back into XML
385
- var raw = compose_xml( this.tree, this.documentNodeName );
386
- var body = raw.substring( raw.indexOf("\n") + 1, raw.length );
387
- var xml = '';
388
-
389
- if (this.piNodeList.length) {
390
- for (var idx = 0, len = this.piNodeList.length; idx < len; idx++) {
391
- xml += '<' + this.piNodeList[idx] + '>' + "\n";
392
- }
393
- }
394
- else {
395
- xml += xml_header + "\n";
396
- }
397
-
398
- if (this.dtdNodeList.length) {
399
- for (var idx = 0, len = this.dtdNodeList.length; idx < len; idx++) {
400
- xml += '<' + this.dtdNodeList[idx] + '>' + "\n";
401
- }
402
- }
403
-
404
- xml += body;
405
- return xml;
406
-};
407
-
408
-//
409
-// Static Utility Functions:
410
-//
411
-
412
-var parse_xml = exports.parse = function parse_xml(text, opts) {
413
- // turn text into XML tree quickly
414
- if (!opts) opts = {};
415
- opts.text = text;
416
- var parser = new XML(opts);
417
- return parser.error() ? parser.getLastError() : parser.getTree();
418
-};
419
-
420
-var trim = exports.trim = function trim(text) {
421
- // strip whitespace from beginning and end of string
422
- if (text == null) return '';
423
-
424
- if (text && text.replace) {
425
- text = text.replace(/^\s+/, "");
426
- text = text.replace(/\s+$/, "");
427
- }
428
-
429
- return text;
430
-};
431
-
432
-var encode_entities = exports.encodeEntities = function encode_entities(text) {
433
- // Simple entitize exports.for = function for composing XML
434
- if (text == null) return '';
435
-
436
- if (text && text.replace) {
437
- text = text.replace(/\&/g, "&"); // MUST BE FIRST
438
- text = text.replace(/</g, "<");
439
- text = text.replace(/>/g, ">");
440
- }
441
-
442
- return text;
443
-};
444
-
445
-var encode_attrib_entities = exports.encodeAttribEntities = function encode_attrib_entities(text) {
446
- // Simple entitize exports.for = function for composing XML attributes
447
- if (text == null) return '';
448
-
449
- if (text && text.replace) {
450
- text = text.replace(/\&/g, "&"); // MUST BE FIRST
451
- text = text.replace(/</g, "<");
452
- text = text.replace(/>/g, ">");
453
- text = text.replace(/\"/g, """);
454
- text = text.replace(/\'/g, "'");
455
- }
456
-
457
- return text;
458
-};
459
-
460
-var decode_entities = exports.decodeEntities = function decode_entities(text) {
461
- // Decode XML entities into raw ASCII
462
- if (text == null) return '';
463
-
464
- if (text && text.replace && text.match(/\&/)) {
465
- text = text.replace(/\<\;/g, "<");
466
- text = text.replace(/\>\;/g, ">");
467
- text = text.replace(/\"\;/g, '"');
468
- text = text.replace(/\&apos\;/g, "'");
469
- text = text.replace(/\&\;/g, "&"); // MUST BE LAST
470
- }
471
-
472
- return text;
473
-};
474
-
475
-var compose_xml = exports.stringify = function compose_xml(node, name, indent) {
476
- // Compose node into XML including attributes
477
- // Recurse for child nodes
478
- var xml = "";
479
-
480
- // If this is the root node, set the indent to 0
481
- // and setup the XML header (PI node)
482
- if (!indent) {
483
- indent = 0;
484
- xml = xml_header + "\n";
485
-
486
- if (!name) {
487
- // no name provided, assume content is wrapped in it
488
- name = first_key(node);
489
- node = node[name];
490
- }
491
- }
492
-
493
- // Setup the indent text
494
- var indent_text = "";
495
- for (var k = 0; k < indent; k++) indent_text += indent_string;
496
-
497
- if ((typeof(node) == 'object') && (node != null)) {
498
- // node is object -- now see if it is an array or hash
499
- if (!node.length) { // what about zero-length array?
500
- // node is hash
501
- xml += indent_text + "<" + name;
502
-
503
- var num_keys = 0;
504
- var has_attribs = 0;
505
- for (var key in node) num_keys++; // there must be a better way...
506
-
507
- if (node["_Attribs"]) {
508
- has_attribs = 1;
509
- var sorted_keys = hash_keys_to_array(node["_Attribs"]).sort();
510
- for (var idx = 0, len = sorted_keys.length; idx < len; idx++) {
511
- var key = sorted_keys[idx];
512
- xml += " " + key + "=\"" + encode_attrib_entities(node["_Attribs"][key]) + "\"";
513
- }
514
- } // has attribs
515
-
516
- if (num_keys > has_attribs) {
517
- // has child elements
518
- xml += ">";
519
-
520
- if (node["_Data"]) {
521
- // simple text child node
522
- xml += encode_entities(node["_Data"]) + "</" + name + ">\n";
523
- } // just text
524
- else {
525
- xml += "\n";
526
-
527
- var sorted_keys = hash_keys_to_array(node).sort();
528
- for (var idx = 0, len = sorted_keys.length; idx < len; idx++) {
529
- var key = sorted_keys[idx];
530
- if ((key != "_Attribs") && key.match(re_valid_tag_name)) {
531
- // recurse for node, with incremented indent value
532
- xml += compose_xml( node[key], key, indent + 1 );
533
- } // not _Attribs key
534
- } // foreach key
535
-
536
- xml += indent_text + "</" + name + ">\n";
537
- } // real children
538
- }
539
- else {
540
- // no child elements, so self-close
541
- xml += "/>\n";
542
- }
543
- } // standard node
544
- else {
545
- // node is array
546
- for (var idx = 0; idx < node.length; idx++) {
547
- // recurse for node in array with same indent
548
- xml += compose_xml( node[idx], name, indent );
549
- }
550
- } // array of nodes
551
- } // complex node
552
- else {
553
- // node is simple string
554
- xml += indent_text + "<" + name + ">" + encode_entities(node) + "</" + name + ">\n";
555
- } // simple text node
556
-
557
- return xml;
558
-};
559
-
560
-var always_array = exports.alwaysArray = function always_array(obj, key) {
561
- // if object is not array, return array containing object
562
- // if key is passed, work like XMLalwaysarray() instead
563
- if (key) {
564
- if ((typeof(obj[key]) != 'object') || (typeof(obj[key].length) == 'undefined')) {
565
- var temp = obj[key];
566
- delete obj[key];
567
- obj[key] = new Array();
568
- obj[key][0] = temp;
569
- }
570
- return null;
571
- }
572
- else {
573
- if ((typeof(obj) != 'object') || (typeof(obj.length) == 'undefined')) { return [ obj ]; }
574
- else return obj;
575
- }
576
-};
577
-
578
-var hash_keys_to_array = exports.hashKeysToArray = function hash_keys_to_array(hash) {
579
- // convert hash keys to array (discard values)
580
- var array = [];
581
- for (var key in hash) array.push(key);
582
- return array;
583
-};
584
-
585
-var isa_hash = exports.isaHash = function isa_hash(arg) {
586
- // determine if arg is a hash
587
- return( !!arg && (typeof(arg) == 'object') && (typeof(arg.length) == 'undefined') );
588
-};
589
-
590
-var isa_array = exports.isaArray = function isa_array(arg) {
591
- // determine if arg is an array or is array-like
592
- if (typeof(arg) == 'array') return true;
593
- return( !!arg && (typeof(arg) == 'object') && (typeof(arg.length) != 'undefined') );
594
-};
595
-
596
-var first_key = exports.firstKey = function first_key(hash) {
597
- // return first key from hash (unordered)
598
- for (var key in hash) return key;
599
- return null; // no keys in hash
600
-};
601
-
602
-var num_keys = exports.numKeys = function num_keys(hash) {
603
- // count the number of keys in a hash
604
- var count = 0;
605
- for (var a in hash) count++;
606
- return count;
607
-};
collectors/node.d.plugin/snmp/Makefile.inc
deleted
-13
@@ -1,13 +0,0 @@
1
-# SPDX-License-Identifier: GPL-3.0-or-later
2
-
3
-# THIS IS NOT A COMPLETE Makefile
4
-# IT IS INCLUDED BY ITS PARENT'S Makefile.am
5
-# IT IS REQUIRED TO REFERENCE ALL FILES RELATIVE TO THE PARENT
6
-
7
-# install these files
8
-dist_node_DATA += snmp/snmp.node.js
9
-# dist_nodeconfig_DATA += snmp/snmp.conf
10
-
11
-# do not install these files, but include them in the distribution
12
-dist_noinst_DATA += snmp/README.md snmp/Makefile.inc
13
-
collectors/node.d.plugin/snmp/README.md
deleted
-445
@@ -1,445 +0,0 @@
1
-<!--
2
-title: "SNMP device monitoring with Netdata"
3
-custom_edit_url: https://github.com/netdata/netdata/edit/master/collectors/node.d.plugin/snmp/README.md
4
-sidebar_label: "SNMP"
5
--->
6
-
7
-# SNMP device monitoring with Netdata
8
-
9
-Collects data from any SNMP device and uses the [net-snmp](https://github.com/markabrahams/node-net-snmp) module.
10
-
11
-It supports:
12
-
13
-- all SNMP versions: SNMPv1, SNMPv2c and SNMPv3
14
-- any number of SNMP devices
15
-- each SNMP device can be used to collect data for any number of charts
16
-- each chart may have any number of dimensions
17
-- each SNMP device may have a different update frequency
18
-- each SNMP device will accept one or more batches to report values (you can set `max_request_size` per SNMP server, to control the size of batches).
19
-
20
-## Requirements
21
-
22
-- `nodejs` minimum required version 4
23
-
24
-## Configuration
25
-
26
-You will need to create the file `/etc/netdata/node.d/snmp.conf` with data like the following.
27
-
28
-In this example:
29
-
30
-- the SNMP device is `10.11.12.8`.
31
-- the SNMP community is `public`.
32
-- we will update the values every 10 seconds (`update_every: 10` under the server `10.11.12.8`).
33
-- we define 2 charts `snmp_switch.bandwidth_port1` and `snmp_switch.bandwidth_port2`, each having 2 dimensions: `in` and `out`. Note that the charts and dimensions must not contain any white space or special characters, other than `.` and `_`.
34
-
35
-```json
36
-{
37
- "enable_autodetect": false,
38
- "update_every": 5,
39
- "max_request_size": 100,
40
- "servers": [
41
- {
42
- "hostname": "10.11.12.8",
43
- "community": "public",
44
- "update_every": 10,
45
- "max_request_size": 50,
46
- "options": {
47
- "timeout": 10000
48
- },
49
- "charts": {
50
- "snmp_switch.bandwidth_port1": {
51
- "title": "Switch Bandwidth for port 1",
52
- "units": "kilobits/s",
53
- "type": "area",
54
- "priority": 1,
55
- "family": "ports",
56
- "dimensions": {
57
- "in": {
58
- "oid": "1.3.6.1.2.1.2.2.1.10.1",
59
- "algorithm": "incremental",
60
- "multiplier": 8,
61
- "divisor": 1024,
62
- "offset": 0
63
- },
64
- "out": {
65
- "oid": "1.3.6.1.2.1.2.2.1.16.1",
66
- "algorithm": "incremental",
67
- "multiplier": -8,
68
- "divisor": 1024,
69
- "offset": 0
70
- }
71
- }
72
- },
73
- "snmp_switch.bandwidth_port2": {
74
- "title": "Switch Bandwidth for port 2",
75
- "units": "kilobits/s",
76
- "type": "area",
77
- "priority": 1,
78
- "family": "ports",
79
- "dimensions": {
80
- "in": {
81
- "oid": "1.3.6.1.2.1.2.2.1.10.2",
82
- "algorithm": "incremental",
83
- "multiplier": 8,
84
- "divisor": 1024,
85
- "offset": 0
86
- },
87
- "out": {
88
- "oid": "1.3.6.1.2.1.2.2.1.16.2",
89
- "algorithm": "incremental",
90
- "multiplier": -8,
91
- "divisor": 1024,
92
- "offset": 0
93
- }
94
- }
95
- }
96
- }
97
- }
98
- ]
99
-}
100
-```
101
-
102
-`update_every` is the update frequency for each server, in seconds.
103
-
104
-`max_request_size` limits the maximum number of OIDs that will be requested in a single call. The default is 50. Lower this number of you get `TooBig` errors in Netdata's `error.log`.
105
-
106
-`family` sets the name of the submenu of the dashboard each chart will appear under.
107
-
108
-`multiplier` and `divisor` are passed by the plugin to the Netdata daemon and are applied to the metric to convert it properly to `units`. For incremental counters with the exception of Counter64 type metrics, `offset` is added to the metric from within the SNMP plugin. This means that the value you will see in debug mode in the `DEBUG: setting current chart to... SET` line for a metric will not have been multiplied or divided, but it will have had the offset added to it.
109
-
110
-<details markdown="1"><summary><b>Caution: Counter64 metrics do not support `offset` (issue #5028).</b></summary>
111
-The SNMP plugin supports Counter64 metrics with the only limitation that the `offset` parameter should not be defined. Due to the way Javascript handles large numbers and the fact that the offset is applied to metrics inside the plugin, the offset will be ignored silently.
112
-</details>
113
-
114
-If you need to define many charts using incremental OIDs, you can use something like this:
115
-
116
-```json
117
-{
118
- "enable_autodetect": false,
119
- "update_every": 10,
120
- "servers": [
121
- {
122
- "hostname": "10.11.12.8",
123
- "community": "public",
124
- "update_every": 10,
125
- "options": {
126
- "timeout": 20000
127
- },
128
- "charts": {
129
- "snmp_switch.bandwidth_port": {
130
- "title": "Switch Bandwidth for port ",
131
- "units": "kilobits/s",
132
- "type": "area",
133
- "priority": 1,
134
- "family": "ports",
135
- "multiply_range": [
136
- 1,
137
- 24
138
- ],
139
- "dimensions": {
140
- "in": {
141
- "oid": "1.3.6.1.2.1.2.2.1.10.",
142
- "algorithm": "incremental",
143
- "multiplier": 8,
144
- "divisor": 1024,
145
- "offset": 0
146
- },
147
- "out": {
148
- "oid": "1.3.6.1.2.1.2.2.1.16.",
149
- "algorithm": "incremental",
150
- "multiplier": -8,
151
- "divisor": 1024,
152
- "offset": 0
153
- }
154
- }
155
- }
156
- }
157
- }
158
- ]
159
-}
160
-```
161
-
162
-This is like the previous, but the option `multiply_range` given, will multiply the current chart from `1` to `24` inclusive, producing 24 charts in total for the 24 ports of the switch `10.11.12.8`.
163
-
164
-Each of the 24 new charts will have its id (1-24) appended at:
165
-
166
-1. its chart unique id, i.e. `snmp_switch.bandwidth_port1` to `snmp_switch.bandwidth_port24`
167
-2. its `title`, i.e. `Switch Bandwidth for port 1` to `Switch Bandwidth for port 24`
168
-3. its `oid` (for all dimensions), i.e. dimension `in` will be `1.3.6.1.2.1.2.2.1.10.1` to `1.3.6.1.2.1.2.2.1.10.24`
169
-4. its priority (which will be incremented for each chart so that the charts will appear on the dashboard in this order)
170
-
171
-The `options` given for each server, are:
172
-
173
-- `port` - UDP port to send requests too. Defaults to `161`.
174
-- `retries` - number of times to re-send a request. Defaults to `1`.
175
-- `sourceAddress` - IP address from which SNMP requests should originate, there is no default for this option, the operating system will select an appropriate source address when the SNMP request is sent.
176
-- `sourcePort` - UDP port from which SNMP requests should originate, defaults to an ephemeral port selected by the operation system.
177
-- `timeout` - number of milliseconds to wait for a response before re-trying or failing. Defaults to `5000`.
178
-- `transport` - specify the transport to use, can be either `udp4` or `udp6`. Defaults to `udp4`.
179
-- `version` - either `0` (v1) or `1` (v2) or `3` (v3). Defaults to `0`.
180
-- `idBitsSize` - either `16` or `32`. Defaults to `32`. Used to reduce the size of the generated id for compatibility with some older devices.
181
-
182
-## SNMPv3
183
-
184
-To use SNMPv3:
185
-
186
-- use `user` instead of `community`
187
-- set `version` to 3
188
-
189
-User syntax:
190
-
191
-```json
192
-{
193
- "enable_autodetect": false,
194
- "update_every": 10,
195
- "servers": [
196
- {
197
- "hostname": "10.11.12.8",
198
- "user": {
199
- "name": "userName",
200
- "level": 3,
201
- "authProtocol": "3",
202
- "authKey": "authKey",
203
- "privProtocol": "2",
204
- "privKey": "privKey"
205
- },
206
- "update_every": 10,
207
- "options": {
208
- "version": 3
209
- },
210
- "charts": {
211
- }
212
- }
213
- ]
214
-}
215
-```
216
-
217
-Security levels (`level`):
218
-
219
-- 1 is `noAuthNoPriv`
220
-- 2 is `authNoPriv`
221
-- 3 is `authPriv`
222
-
223
-Authentication protocols (`authProtocol`):
224
-
225
-- "1" is `none`
226
-- "2" is `md5`
227
-- "3" is `sha`
228
-
229
-Privacy protocols (`privProtocol`):
230
-
231
-- "1" is `none`
232
-- "2" is `des`
233
-
234
-For additional details please see [net-snmp module readme](https://github.com/markabrahams/node-net-snmp#snmpcreatev3session-target-user-options).
235
-
236
-## Retrieving names from snmp
237
-
238
-You can append a value retrieved from SNMP to the title, by adding `titleoid` to the chart.
239
-
240
-You can set a dimension name to a value retrieved from SNMP, by adding `oidname` to the dimension.
241
-
242
-Both of the above will participate in `multiply_range`.
243
-
244
-## Testing the configuration
245
-
246
-To test it, you can run:
247
-
248
-```sh
249
-/usr/libexec/netdata/plugins.d/node.d.plugin 1 snmp
250
-```
251
-
252
-The above will run it on your console and you will be able to see what Netdata sees, but also errors. You can get a very detailed output by appending `debug` to the command line.
253
-
254
-If it works, restart Netdata to activate the snmp collector and refresh the dashboard (if your SNMP device responds with a delay, you may need to refresh the dashboard in a few seconds).
255
-
256
-## Data collection speed
257
-
258
-Keep in mind that many SNMP switches and routers are very slow. They may not be able to report values per second. If you run `node.d.plugin` in `debug` mode, it will report the time it took for the SNMP device to respond. My switch, for example, needs 7-8 seconds to respond for the traffic on 24 ports (48 OIDs, in/out).
259
-
260
-Also, if you use many SNMP clients on the same SNMP device at the same time, values may be skipped. This is a problem of the SNMP device, not this collector.
261
-
262
-## Finding OIDs
263
-
264
-Use `snmpwalk`, like this:
265
-
266
-```sh
267
-snmpwalk -t 20 -v 1 -O fn -c public 10.11.12.8
268
-```
269
-
270
-- `-t 20` is the timeout in seconds
271
-- `-v 1` is the SNMP version
272
-- `-O fn` will display full OIDs in numeric format (you may want to run it also without this option to see human readable output of OIDs)
273
-- `-c public` is the SNMP community
274
-- `10.11.12.8` is the SNMP device
275
-
276
-Keep in mind that `snmpwalk` outputs the OIDs with a dot in front them. You should remove this dot when adding OIDs to the configuration file of this collector.
277
-
278
-## Example: Linksys SRW2024P
279
-
280
-This is what I use for my Linksys SRW2024P. It creates:
281
-
282
-1. A chart for power consumption (it is a PoE switch)
283
-2. Two charts for packets received (total packets received and packets received with errors)
284
-3. One chart for packets output
285
-4. 24 charts, one for each port of the switch. It also appends the port names, as defined at the switch, to the chart titles.
286
-
287
-This switch also reports various other metrics, like snmp, packets per port, etc. Unfortunately it does not report CPU utilization or backplane utilization.
288
-
289
-This switch has a very slow SNMP processors. To respond, it needs about 8 seconds, so I have set the refresh frequency (`update_every`) to 15 seconds.
290
-
291
-```json
292
-{
293
- "enable_autodetect": false,
294
- "update_every": 5,
295
- "servers": [
296
- {
297
- "hostname": "10.11.12.8",
298
- "community": "public",
299
- "update_every": 15,
300
- "options": {
301
- "timeout": 20000,
302
- "version": 1
303
- },
304
- "charts": {
305
- "snmp_switch.power": {
306
- "title": "Switch Power Supply",
307
- "units": "watts",
308
- "type": "line",
309
- "priority": 10,
310
- "family": "power",
311
- "dimensions": {
312
- "supply": {
313
- "oid": ".1.3.6.1.2.1.105.1.3.1.1.2.1",
314
- "algorithm": "absolute",
315
- "multiplier": 1,
316
- "divisor": 1,
317
- "offset": 0
318
- },
319
- "used": {
320
- "oid": ".1.3.6.1.2.1.105.1.3.1.1.4.1",
321
- "algorithm": "absolute",
322
- "multiplier": 1,
323
- "divisor": 1,
324
- "offset": 0
325
- }
326
- }
327
- },
328
- "snmp_switch.input": {
329
- "title": "Switch Packets Input",
330
- "units": "packets/s",
331
- "type": "area",
332
- "priority": 20,
333
- "family": "IP",
334
- "dimensions": {
335
- "receives": {
336
- "oid": ".1.3.6.1.2.1.4.3.0",
337
- "algorithm": "incremental",
338
- "multiplier": 1,
339
- "divisor": 1,
340
- "offset": 0
341
- },
342
- "discards": {
343
- "oid": ".1.3.6.1.2.1.4.8.0",
344
- "algorithm": "incremental",
345
- "multiplier": 1,
346
- "divisor": 1,
347
- "offset": 0
348
- }
349
- }
350
- },
351
- "snmp_switch.input_errors": {
352
- "title": "Switch Received Packets with Errors",
353
- "units": "packets/s",
354
- "type": "line",
355
- "priority": 30,
356
- "family": "IP",
357
- "dimensions": {
358
- "bad_header": {
359
- "oid": ".1.3.6.1.2.1.4.4.0",
360
- "algorithm": "incremental",
361
- "multiplier": 1,
362
- "divisor": 1,
363
- "offset": 0
364
- },
365
- "bad_address": {
366
- "oid": ".1.3.6.1.2.1.4.5.0",
367
- "algorithm": "incremental",
368
- "multiplier": 1,
369
- "divisor": 1,
370
- "offset": 0
371
- },
372
- "unknown_protocol": {
373
- "oid": ".1.3.6.1.2.1.4.7.0",
374
- "algorithm": "incremental",
375
- "multiplier": 1,
376
- "divisor": 1,
377
- "offset": 0
378
- }
379
- }
380
- },
381
- "snmp_switch.output": {
382
- "title": "Switch Output Packets",
383
- "units": "packets/s",
384
- "type": "line",
385
- "priority": 40,
386
- "family": "IP",
387
- "dimensions": {
388
- "requests": {
389
- "oid": ".1.3.6.1.2.1.4.10.0",
390
- "algorithm": "incremental",
391
- "multiplier": 1,
392
- "divisor": 1,
393
- "offset": 0
394
- },
395
- "discards": {
396
- "oid": ".1.3.6.1.2.1.4.11.0",
397
- "algorithm": "incremental",
398
- "multiplier": -1,
399
- "divisor": 1,
400
- "offset": 0
401
- },
402
- "no_route": {
403
- "oid": ".1.3.6.1.2.1.4.12.0",
404
- "algorithm": "incremental",
405
- "multiplier": -1,
406
- "divisor": 1,
407
- "offset": 0
408
- }
409
- }
410
- },
411
- "snmp_switch.bandwidth_port": {
412
- "title": "Switch Bandwidth for port ",
413
- "titleoid": ".1.3.6.1.2.1.31.1.1.1.18.",
414
- "units": "kilobits/s",
415
- "type": "area",
416
- "priority": 100,
417
- "family": "ports",
418
- "multiply_range": [
419
- 1,
420
- 24
421
- ],
422
- "dimensions": {
423
- "in": {
424
- "oid": ".1.3.6.1.2.1.2.2.1.10.",
425
- "algorithm": "incremental",
426
- "multiplier": 8,
427
- "divisor": 1024,
428
- "offset": 0
429
- },
430
- "out": {
431
- "oid": ".1.3.6.1.2.1.2.2.1.16.",
432
- "algorithm": "incremental",
433
- "multiplier": -8,
434
- "divisor": 1024,
435
- "offset": 0
436
- }
437
- }
438
- }
439
- }
440
- }
441
- ]
442
-}
443
-```
444
-
445
-
collectors/node.d.plugin/snmp/snmp.node.js
deleted
-527
@@ -1,527 +0,0 @@
1
-'use strict';
2
-// SPDX-License-Identifier: GPL-3.0-or-later
3
-// netdata snmp module
4
-// This program will connect to one or more SNMP Agents
5
-//
6
-
7
-// example configuration in /etc/netdata/node.d/snmp.conf
8
-/*
9
-{
10
- "enable_autodetect": false,
11
- "update_every": 5,
12
- "max_request_size": 50,
13
- "servers": [
14
- {
15
- "hostname": "10.11.12.8",
16
- "community": "public",
17
- "update_every": 10,
18
- "max_request_size": 50,
19
- "options": { "timeout": 10000 },
20
- "charts": {
21
- "snmp_switch.bandwidth_port1": {
22
- "title": "Switch Bandwidth for port 1",
23
- "units": "kilobits/s",
24
- "type": "area",
25
- "priority": 1,
26
- "dimensions": {
27
- "in": {
28
- "oid": ".1.3.6.1.2.1.2.2.1.10.1",
29
- "algorithm": "incremental",
30
- "multiplier": 8,
31
- "divisor": 1024,
32
- "offset": 0
33
- },
34
- "out": {
35
- "oid": ".1.3.6.1.2.1.2.2.1.16.1",
36
- "algorithm": "incremental",
37
- "multiplier": -8,
38
- "divisor": 1024,
39
- "offset": 0
40
- }
41
- }
42
- },
43
- "snmp_switch.bandwidth_port2": {
44
- "title": "Switch Bandwidth for port 2",
45
- "units": "kilobits/s",
46
- "type": "area",
47
- "priority": 1,
48
- "dimensions": {
49
- "in": {
50
- "oid": ".1.3.6.1.2.1.2.2.1.10.2",
51
- "algorithm": "incremental",
52
- "multiplier": 8,
53
- "divisor": 1024,
54
- "offset": 0
55
- },
56
- "out": {
57
- "oid": ".1.3.6.1.2.1.2.2.1.16.2",
58
- "algorithm": "incremental",
59
- "multiplier": -8,
60
- "divisor": 1024,
61
- "offset": 0
62
- }
63
- }
64
- }
65
- }
66
- }
67
- ]
68
-}
69
-*/
70
-
71
-// You can also give ranges of charts like the following.
72
-// This will append 1-24 to id, title, oid (on each dimension)
73
-// so that 24 charts will be created.
74
-/*
75
-{
76
- "enable_autodetect": false,
77
- "update_every": 10,
78
- "max_request_size": 50,
79
- "servers": [
80
- {
81
- "hostname": "10.11.12.8",
82
- "community": "public",
83
- "update_every": 10,
84
- "max_request_size": 50,
85
- "options": { "timeout": 20000 },
86
- "charts": {
87
- "snmp_switch.bandwidth_port": {
88
- "title": "Switch Bandwidth for port ",
89
- "units": "kilobits/s",
90
- "type": "area",
91
- "priority": 1,
92
- "multiply_range": [ 1, 24 ],
93
- "dimensions": {
94
- "in": {
95
- "oid": ".1.3.6.1.2.1.2.2.1.10.",
96
- "algorithm": "incremental",
97
- "multiplier": 8,
98
- "divisor": 1024,
99
- "offset": 0
100
- },
101
- "out": {
102
- "oid": ".1.3.6.1.2.1.2.2.1.16.",
103
- "algorithm": "incremental",
104
- "multiplier": -8,
105
- "divisor": 1024,
106
- "offset": 0
107
- }
108
- }
109
- }
110
- }
111
- }
112
- ]
113
-}
114
-*/
115
-
116
-var net_snmp = require('net-snmp');
117
-var extend = require('extend');
118
-var netdata = require('netdata');
119
-
120
-if (netdata.options.DEBUG === true) netdata.debug('loaded', __filename, ' plugin');
121
-
122
-netdata.processors.snmp = {
123
- name: 'snmp',
124
-
125
- fixoid: function (oid) {
126
- if (typeof oid !== 'string')
127
- return oid;
128
-
129
- if (oid.charAt(0) === '.')
130
- return oid.substring(1, oid.length);
131
-
132
- return oid;
133
- },
134
-
135
- prepare: function (service) {
136
- var __DEBUG = netdata.options.DEBUG;
137
-
138
- if (typeof service.snmp_oids === 'undefined' || service.snmp_oids === null || service.snmp_oids.length === 0) {
139
- // this is the first time we see this service
140
-
141
- if (__DEBUG === true)
142
- netdata.debug(service.module.name + ': ' + service.name + ': preparing ' + this.name + ' OIDs');
143
-
144
- // build an index of all OIDs
145
- service.snmp_oids_index = {};
146
- var chart_keys = Object.keys(service.request.charts);
147
- var chart_keys_len = chart_keys.length;
148
- while (chart_keys_len--) {
149
- var c = chart_keys[chart_keys_len];
150
- var chart = service.request.charts[c];
151
-
152
- // for each chart
153
-
154
- if (__DEBUG === true)
155
- netdata.debug(service.module.name + ': ' + service.name + ': indexing ' + this.name + ' chart: ' + c);
156
-
157
- if (typeof chart.titleoid !== 'undefined') {
158
- service.snmp_oids_index[this.fixoid(chart.titleoid)] = {
159
- type: 'title',
160
- link: chart
161
- };
162
- }
163
-
164
- var dim_keys = Object.keys(chart.dimensions);
165
- var dim_keys_len = dim_keys.length;
166
- while (dim_keys_len--) {
167
- var d = dim_keys[dim_keys_len];
168
- var dim = chart.dimensions[d];
169
-
170
- // for each dimension in the chart
171
-
172
- var oid = this.fixoid(dim.oid);
173
- var oidname = this.fixoid(dim.oidname);
174
-
175
- if (__DEBUG === true)
176
- netdata.debug(service.module.name + ': ' + service.name + ': indexing ' + this.name + ' chart: ' + c + ', dimension: ' + d + ', OID: ' + oid + ", OID name: " + oidname);
177
-
178
- // link it to the point we need to set the value to
179
- service.snmp_oids_index[oid] = {
180
- type: 'value',
181
- link: dim
182
- };
183
-
184
- if (typeof oidname !== 'undefined')
185
- service.snmp_oids_index[oidname] = {
186
- type: 'name',
187
- link: dim
188
- };
189
-
190
- // and set the value to null
191
- dim.value = null;
192
- }
193
- }
194
-
195
- if (__DEBUG === true)
196
- netdata.debug(service.module.name + ': ' + service.name + ': indexed ' + this.name + ' OIDs: ' + netdata.stringify(service.snmp_oids_index));
197
-
198
- // now create the array of OIDs needed by net-snmp
199
- service.snmp_oids = Object.keys(service.snmp_oids_index);
200
-
201
- if (__DEBUG === true)
202
- netdata.debug(service.module.name + ': ' + service.name + ': final list of ' + this.name + ' OIDs: ' + netdata.stringify(service.snmp_oids));
203
-
204
- service.snmp_oids_cleaned = 0;
205
- } else if (service.snmp_oids_cleaned === 0) {
206
- service.snmp_oids_cleaned = 1;
207
-
208
- // the second time, keep only values
209
-
210
- service.snmp_oids = new Array();
211
- var oid_keys = Object.keys(service.snmp_oids_index);
212
- var oid_keys_len = oid_keys.length;
213
- while (oid_keys_len--) {
214
- if (service.snmp_oids_index[oid_keys[oid_keys_len]].type === 'value')
215
- service.snmp_oids.push(oid_keys[oid_keys_len]);
216
- }
217
- }
218
- },
219
-
220
- getdata: function (service, index, ok, failed, callback) {
221
- var __DEBUG = netdata.options.DEBUG;
222
- var that = this;
223
-
224
- if (index >= service.snmp_oids.length) {
225
- callback((ok > 0) ? {ok: ok, failed: failed} : null);
226
- return;
227
- }
228
-
229
- var slice;
230
- if (service.snmp_oids.length <= service.request.max_request_size) {
231
- slice = service.snmp_oids;
232
- index = service.snmp_oids.length;
233
- } else if (service.snmp_oids.length - index <= service.request.max_request_size) {
234
- slice = service.snmp_oids.slice(index, service.snmp_oids.length);
235
- index = service.snmp_oids.length;
236
- } else {
237
- slice = service.snmp_oids.slice(index, index + service.request.max_request_size);
238
- index += service.request.max_request_size;
239
- }
240
-
241
- if (__DEBUG === true)
242
- netdata.debug(service.module.name + ': ' + service.name + ': making ' + slice.length + ' entries request, max is: ' + service.request.max_request_size);
243
-
244
- service.snmp_session.get(slice, function (error, varbinds) {
245
- if (error) {
246
- service.error('Received error = ' + netdata.stringify(error) + ' varbinds = ' + netdata.stringify(varbinds));
247
-
248
- // make all values null
249
- var len = slice.length;
250
- while (len--)
251
- service.snmp_oids_index[slice[len]].value = null;
252
- } else {
253
- if (__DEBUG === true)
254
- netdata.debug(service.module.name + ': ' + service.name + ': got valid ' + service.module.name + ' response: ' + netdata.stringify(varbinds));
255
-
256
- var varbinds_len = varbinds.length;
257
- for (var i = 0; i < varbinds_len; i++) {
258
- var value = null;
259
-
260
- if (net_snmp.isVarbindError(varbinds[i])) {
261
- if (__DEBUG === true)
262
- netdata.debug(service.module.name + ': ' + service.name + ': failed ' + service.module.name + ' get for OIDs ' + varbinds[i].oid);
263
-
264
- service.error('OID ' + varbinds[i].oid + ' gave error: ' + net_snmp.varbindError(varbinds[i]));
265
- value = null;
266
- failed++;
267
- } else {
268
- // test fom Counter64
269
- // varbinds[i].type = net_snmp.ObjectType.Counter64;
270
- // varbinds[i].value = new Buffer([0x34, 0x49, 0x2e, 0xdc, 0xd1]);
271
-
272
- switch (varbinds[i].type) {
273
- case net_snmp.ObjectType.OctetString:
274
- if (service.snmp_oids_index[varbinds[i].oid].type !== 'title' && service.snmp_oids_index[varbinds[i].oid].type !== 'name') {
275
- // parse floating point values, exposed as strings
276
- value = parseFloat(varbinds[i].value) * 1000;
277
- if (__DEBUG === true) netdata.debug(service.module.name + ': ' + service.name + ': found ' + service.module.name + ' value of OIDs ' + varbinds[i].oid + ", ObjectType " + net_snmp.ObjectType[varbinds[i].type] + " (" + netdata.stringify(varbinds[i].type) + "), typeof(" + typeof (varbinds[i].value) + "), in JSON: " + netdata.stringify(varbinds[i].value) + ", value = " + value.toString() + " (parsed as float in string)");
278
- } else {
279
- // just use the string
280
- value = varbinds[i].value;
281
- if (__DEBUG === true) netdata.debug(service.module.name + ': ' + service.name + ': found ' + service.module.name + ' value of OIDs ' + varbinds[i].oid + ", ObjectType " + net_snmp.ObjectType[varbinds[i].type] + " (" + netdata.stringify(varbinds[i].type) + "), typeof(" + typeof (varbinds[i].value) + "), in JSON: " + netdata.stringify(varbinds[i].value) + ", value = " + value.toString() + " (parsed as string)");
282
- }
283
- break;
284
-
285
- case net_snmp.ObjectType.Counter64:
286
- // copy the buffer
287
- value = '0x' + varbinds[i].value.toString('hex');
288
- if (__DEBUG === true) netdata.debug(service.module.name + ': ' + service.name + ': found ' + service.module.name + ' value of OIDs ' + varbinds[i].oid + ", ObjectType " + net_snmp.ObjectType[varbinds[i].type] + " (" + netdata.stringify(varbinds[i].type) + "), typeof(" + typeof (varbinds[i].value) + "), in JSON: " + netdata.stringify(varbinds[i].value) + ", value = " + value.toString() + " (parsed as buffer)");
289
- break;
290
-
291
- case net_snmp.ObjectType.Integer:
292
- case net_snmp.ObjectType.Counter:
293
- case net_snmp.ObjectType.Gauge:
294
- default:
295
- value = varbinds[i].value;
296
- if (__DEBUG === true) netdata.debug(service.module.name + ': ' + service.name + ': found ' + service.module.name + ' value of OIDs ' + varbinds[i].oid + ", ObjectType " + net_snmp.ObjectType[varbinds[i].type] + " (" + netdata.stringify(varbinds[i].type) + "), typeof(" + typeof (varbinds[i].value) + "), in JSON: " + netdata.stringify(varbinds[i].value) + ", value = " + value.toString() + " (parsed as number)");
297
- break;
298
- }
299
-
300
- ok++;
301
- }
302
-
303
- if (value !== null) {
304
- switch (service.snmp_oids_index[varbinds[i].oid].type) {
305
- case 'title':
306
- service.snmp_oids_index[varbinds[i].oid].link.title += ' ' + value;
307
- break;
308
- case 'name' :
309
- service.snmp_oids_index[varbinds[i].oid].link.name = value.toString().replace(/\W/g, '_');
310
- break;
311
- case 'value':
312
- service.snmp_oids_index[varbinds[i].oid].link.value = value;
313
- break;
314
- }
315
- }
316
- }
317
-
318
- if (__DEBUG === true)
319
- netdata.debug(service.module.name + ': ' + service.name + ': finished ' + service.module.name + ' with ' + ok + ' successful and ' + failed + ' failed values');
320
- }
321
- that.getdata(service, index, ok, failed, callback);
322
- });
323
- },
324
-
325
- process: function (service, callback) {
326
- var __DEBUG = netdata.options.DEBUG;
327
-
328
- this.prepare(service);
329
-
330
- if (service.snmp_oids.length === 0) {
331
- // no OIDs found for this service
332
-
333
- if (__DEBUG === true)
334
- service.error('no OIDs to process.');
335
-
336
- callback(null);
337
- return;
338
- }
339
-
340
- if (typeof service.snmp_session === 'undefined' || service.snmp_session === null) {
341
- // no SNMP session has been created for this service
342
- // the SNMP session is just the initialization of NET-SNMP
343
-
344
- var snmp_version = (service.request.options && service.request.options.version)
345
- ? service.request.options.version
346
- : net_snmp.Version1;
347
-
348
- if (snmp_version === net_snmp.Version3) {
349
- if (__DEBUG === true)
350
- netdata.debug(service.module.name + ': ' + service.name + ': opening ' + this.name + ' session on ' + service.request.hostname + ' user ' + service.request.user + ' options ' + netdata.stringify(service.request.options));
351
-
352
- // create the SNMP session
353
- service.snmp_session = net_snmp.createV3Session(service.request.hostname, service.request.user, service.request.options);
354
- } else {
355
- if (__DEBUG === true)
356
- netdata.debug(service.module.name + ': ' + service.name + ': opening ' + this.name + ' session on ' + service.request.hostname + ' community ' + service.request.community + ' options ' + netdata.stringify(service.request.options));
357
-
358
- // create the SNMP session
359
- service.snmp_session = net_snmp.createSession(service.request.hostname, service.request.community, service.request.options);
360
- }
361
-
362
- if (__DEBUG === true)
363
- netdata.debug(service.module.name + ': ' + service.name + ': got ' + this.name + ' session: ' + netdata.stringify(service.snmp_session));
364
-
365
- // if we later need traps, this is how to do it:
366
- //service.snmp_session.trap(net_snmp.TrapType.LinkDown, function(error) {
367
- // if(error) console.error('trap error: ' + netdata.stringify(error));
368
- //});
369
- }
370
-
371
- // do it, get the SNMP values for the sessions we need
372
- this.getdata(service, 0, 0, 0, callback);
373
- }
374
-};
375
-
376
-var snmp = {
377
- name: __filename,
378
- enable_autodetect: true,
379
- update_every: 1,
380
- base_priority: 50000,
381
-
382
- charts: {},
383
-
384
- processResponse: function (service, data) {
385
- if (data !== null) {
386
- if (service.added !== true)
387
- service.commit();
388
-
389
- var chart_keys = Object.keys(service.request.charts);
390
- var chart_keys_len = chart_keys.length;
391
- for (var i = 0; i < chart_keys_len; i++) {
392
- var c = chart_keys[i];
393
-
394
- var chart = snmp.charts[c];
395
- if (typeof chart === 'undefined') {
396
- chart = service.chart(c, service.request.charts[c]);
397
- snmp.charts[c] = chart;
398
- }
399
-
400
- service.begin(chart);
401
-
402
- var dimensions = service.request.charts[c].dimensions;
403
- var dim_keys = Object.keys(dimensions);
404
- var dim_keys_len = dim_keys.length;
405
- for (var j = 0; j < dim_keys_len; j++) {
406
- var d = dim_keys[j];
407
-
408
- if (dimensions[d].value !== null) {
409
- if (typeof dimensions[d].offset === 'number' && typeof dimensions[d].value === 'number')
410
- service.set(d, dimensions[d].value + dimensions[d].offset);
411
- else
412
- service.set(d, dimensions[d].value);
413
- }
414
- }
415
-
416
- service.end();
417
- }
418
- }
419
- },
420
-
421
- // module.serviceExecute()
422
- // this function is called only from this module
423
- // its purpose is to prepare the request and call
424
- // netdata.serviceExecute()
425
- serviceExecute: function (conf) {
426
- var __DEBUG = netdata.options.DEBUG;
427
-
428
- if (__DEBUG === true)
429
- netdata.debug(this.name + ': snmp hostname: ' + conf.hostname + ', update_every: ' + conf.update_every);
430
-
431
- var service = netdata.service({
432
- name: conf.hostname,
433
- request: conf,
434
- update_every: conf.update_every,
435
- module: this,
436
- processor: netdata.processors.snmp
437
- });
438
-
439
- // multiply the charts, if required
440
- var chart_keys = Object.keys(service.request.charts);
441
- var chart_keys_len = chart_keys.length;
442
- for (var i = 0; i < chart_keys_len; i++) {
443
- var c = chart_keys[i];
444
- var service_request_chart = service.request.charts[c];
445
-
446
- if (__DEBUG === true)
447
- netdata.debug(this.name + ': snmp hostname: ' + conf.hostname + ', examining chart: ' + c);
448
-
449
- if (typeof service_request_chart.update_every === 'undefined')
450
- service_request_chart.update_every = service.update_every;
451
-
452
- if (typeof service_request_chart.multiply_range !== 'undefined') {
453
- var from = service_request_chart.multiply_range[0];
454
- var to = service_request_chart.multiply_range[1];
455
- var prio = service_request_chart.priority || 1;
456
-
457
- if (prio < snmp.base_priority) prio += snmp.base_priority;
458
-
459
- while (from <= to) {
460
- var id = c + from.toString();
461
- var chart = extend(true, {}, service_request_chart);
462
- chart.title += from.toString();
463
-
464
- if (typeof chart.titleoid !== 'undefined')
465
- chart.titleoid += from.toString();
466
-
467
- chart.priority = prio++;
468
-
469
- var dim_keys = Object.keys(chart.dimensions);
470
- var dim_keys_len = dim_keys.length;
471
- for (var j = 0; j < dim_keys_len; j++) {
472
- var d = dim_keys[j];
473
-
474
- chart.dimensions[d].oid += from.toString();
475
-
476
- if (typeof chart.dimensions[d].oidname !== 'undefined')
477
- chart.dimensions[d].oidname += from.toString();
478
- }
479
- service.request.charts[id] = chart;
480
- from++;
481
- }
482
-
483
- delete service.request.charts[c];
484
- } else {
485
- if (service.request.charts[c].priority < snmp.base_priority)
486
- service.request.charts[c].priority += snmp.base_priority;
487
- }
488
- }
489
-
490
- service.execute(this.processResponse);
491
- },
492
-
493
- configure: function (config) {
494
- var added = 0;
495
-
496
- if (typeof config.max_request_size === 'undefined')
497
- config.max_request_size = 50;
498
-
499
- if (typeof (config.servers) !== 'undefined') {
500
- var len = config.servers.length;
501
- while (len--) {
502
- if (typeof config.servers[len].update_every === 'undefined')
503
- config.servers[len].update_every = this.update_every;
504
-
505
- if (typeof config.servers[len].max_request_size === 'undefined')
506
- config.servers[len].max_request_size = config.max_request_size;
507
-
508
- this.serviceExecute(config.servers[len]);
509
- added++;
510
- }
511
- }
512
-
513
- return added;
514
- },
515
-
516
- // module.update()
517
- // this is called repeatedly to collect data, by calling
518
- // service.execute()
519
- update: function (service, callback) {
520
- service.execute(function (serv, data) {
521
- service.module.processResponse(serv, data);
522
- callback();
523
- });
524
- }
525
-};
526
-
527
-module.exports = snmp;
collectors/plugins.d/README.md
+2
-9
@@ -21,7 +21,6 @@ from external processes, thus allowing Netdata to use **external plugins**.
21
|[nfacct.plugin](/collectors/nfacct.plugin/README.md)|`C`|linux|collects netfilter firewall, connection tracker and accounting metrics using `libmnl` and `libnetfilter_acct`.|
22
|[xenstat.plugin](/collectors/xenstat.plugin/README.md)|`C`|linux|collects XenServer and XCP-ng metrics using `lxenstat`.|
23
|[perf.plugin](/collectors/perf.plugin/README.md)|`C`|linux|collects CPU performance metrics using performance monitoring units (PMU).|
24
-|[node.d.plugin](/collectors/node.d.plugin/README.md)|`node.js`|all|a **plugin orchestrator** for data collection modules written in `node.js`.|
24
|[python.d.plugin](/collectors/python.d.plugin/README.md)|`python`|all|a **plugin orchestrator** for data collection modules written in `python` v2 or v3 (both are supported).|
25
|[slabinfo.plugin](/collectors/slabinfo.plugin/README.md)|`C`|linux|collects kernel internal cache objects (SLAB) metrics.|
26
@@ -74,7 +73,6 @@ Example:
73
# charts.d = yes
74
# fping = yes
75
# ioping = yes
77
- # node.d = yes
76
# python.d = yes
77
```
78
@@ -391,17 +389,12 @@ or do not output the line at all.
389
390
python is ideal for Netdata plugins. It is a simple, yet powerful way to collect data, it has a very small memory footprint, although it is not the most CPU efficient way to do it.
391
394
-2. **node.js**, use `node.d.plugin`, there are a few examples in the [node.d
395
- directory](/collectors/node.d.plugin/README.md)
396
-
397
- node.js is the fastest scripting language for collecting data. If your plugin needs to do a lot of work, compute values, etc, node.js is probably the best choice before moving to compiled code. Keep in mind though that node.js is not memory efficient; it will probably need more RAM compared to python.
398
-
399
-3. **BASH**, use `charts.d.plugin`, there are many examples in the [charts.d
392
+2. **BASH**, use `charts.d.plugin`, there are many examples in the [charts.d
393
directory](/collectors/charts.d.plugin/README.md)
394
395
BASH is the simplest scripting language for collecting values. It is the less efficient though in terms of CPU resources. You can use it to collect data quickly, but extensive use of it might use a lot of system resources.
396
404
-4. **C**
397
+3. **C**
398
399
Of course, C is the most efficient way of collecting data. This is why Netdata itself is written in C.
400
configure.ac
-3
@@ -1580,7 +1580,6 @@ varlibdir="${localstatedir}/lib/netdata"
1580
registrydir="${localstatedir}/lib/netdata/registry"
1581
cachedir="${localstatedir}/cache/netdata"
1582
chartsdir="${libexecdir}/netdata/charts.d"
1583
-nodedir="${libexecdir}/netdata/node.d"
1583
pythondir="${libexecdir}/netdata/python.d"
1584
configdir="${sysconfdir}/netdata"
1585
libconfigdir="${libdir}/netdata/conf.d"
@@ -1591,7 +1590,6 @@ AC_SUBST([varlibdir])
1590
AC_SUBST([registrydir])
1591
AC_SUBST([cachedir])
1592
AC_SUBST([chartsdir])
1594
-AC_SUBST([nodedir])
1593
AC_SUBST([pythondir])
1594
AC_SUBST([configdir])
1595
AC_SUBST([libconfigdir])
@@ -1716,7 +1714,6 @@ AC_CONFIG_FILES([
1714
collectors/idlejitter.plugin/Makefile
1715
collectors/macos.plugin/Makefile
1716
collectors/nfacct.plugin/Makefile
1719
- collectors/node.d.plugin/Makefile
1717
collectors/plugins.d/Makefile
1718
collectors/proc.plugin/Makefile
1719
collectors/python.d.plugin/Makefile
contrib/debian/control
-1
@@ -41,7 +41,6 @@ Depends: adduser,
41
Conflicts: netdata-core,
42
netdata-plugins-bash,
43
netdata-plugins-python,
44
- netdata-plugins-nodejs,
44
netdata-web
45
Pre-Depends: dpkg (>= 1.17.14)
46
Description: real-time charts for system monitoring
daemon/config/README.md
+1
-1
@@ -92,7 +92,7 @@ Refer to the [web server documentation](/web/server/README.md)
92
93
### [plugins] section options
94
95
-In this section you will see be a boolean (`yes`/`no`) option for each plugin (e.g. tc, cgroups, apps, proc etc.). Note that the configuration options in this section for the orchestrator plugins `python.d`, `charts.d` and `node.d` control **all the modules** written for that orchestrator. For instance, setting `python.d = no` means that all Python modules under `collectors/python.d.plugin` will be disabled.
95
+In this section you will see be a boolean (`yes`/`no`) option for each plugin (e.g. tc, cgroups, apps, proc etc.). Note that the configuration options in this section for the orchestrator plugins `python.d` and `charts.d` control **all the modules** written for that orchestrator. For instance, setting `python.d = no` means that all Python modules under `collectors/python.d.plugin` will be disabled.
96
97
Additionally, there will be the following options:
98
docs/collect/how-collectors-work.md
-2
@@ -62,8 +62,6 @@ terms related to collecting metrics.
62
`python` v2/v3.
63
- [charts.d.plugin](/collectors/charts.d.plugin/README.md): An orchestrator for data collection modules written in
64
`bash` v4+.
65
- - [node.d.plugin](/collectors/node.d.plugin/README.md): An orchestrator for data collection modules written in
66
- `node.js`.
65
- **External plugins** gather metrics from external processes, such as a webserver or database, and run as independent
66
processes that communicate with the Netdata daemon via pipes.
67
- **Internal plugins** gather metrics from `/proc`, `/sys`, and other Linux kernel sources. They are written in `C`,
docs/configure/common-changes.md
+2
-2
@@ -46,7 +46,7 @@ of 5 seconds.
46
```
47
48
Every collector and plugin has its own `update every` setting, which you can also change in the `go.d.conf`,
49
-`python.d.conf`, `node.d.conf`, or `charts.d.conf` files, or in individual collector configuration files. If the `update
49
+`python.d.conf` or `charts.d.conf` files, or in individual collector configuration files. If the `update
50
every` for an individual collector is less than the global, the Netdata Agent uses the global setting. See the [enable
51
or configure a collector](/docs/collect/enable-configure.md) doc for details.
52
@@ -55,7 +55,7 @@ or configure a collector](/docs/collect/enable-configure.md) doc for details.
55
Turn off entire plugins in the [`[plugins]` section](/daemon/config/README.md#plugins-section-options) of
56
`netdata.conf`.
57
58
-To disable specific collectors, open `go.d.conf`, `python.d.conf`, `node.d.conf`, or `charts.d.conf` and find the line
58
+To disable specific collectors, open `go.d.conf`, `python.d.conf` or `charts.d.conf` and find the line
59
for that specific module. Uncomment the line and change its value to `no`.
60
61
## Modify alarms and notifications
docs/guides/configure/performance.md
+2
-5
@@ -72,7 +72,7 @@ seconds, respectively.
72
### Specific plugin or collector
73
74
Every collector and plugin has its own `update every` setting, which you can also change in the `go.d.conf`,
75
-`python.d.conf`, `node.d.conf`, or `charts.d.conf` files, or in individual collector configuration files. If the `update
75
+`python.d.conf`, or `charts.d.conf` files, or in individual collector configuration files. If the `update
76
every` for an individual collector is less than the global, the Netdata Agent uses the global setting. See the [enable
77
or configure a collector](/docs/collect/enable-configure.md) doc for details.
78
@@ -103,15 +103,13 @@ Keep in mind that if a plugin/collector has nothing to do, it simply shuts down
103
You will only improve the Agent's performance by disabling plugins/collectors that are actively collecting metrics.
104
105
Open `netdata.conf` and scroll down to the `[plugins]` section. To disable any plugin, uncomment it and set the value to
106
-`no`. For example, to explicitly keep the `proc` and `go.d` plugins enabled while disabling `python.d`, `charts.d`, and
107
-`node.d`.
106
+`no`. For example, to explicitly keep the `proc` and `go.d` plugins enabled while disabling `python.d` and `charts.d`.
107
108
```conf
109
[plugins]
110
proc = yes
111
python.d = no
112
charts.d = no
114
- node.d = no
113
go.d = yes
114
```
115
@@ -121,7 +119,6 @@ collector, and setting its value to `no`.
119
```bash
120
sudo ./edit-config go.d.conf
121
sudo ./edit-config python.d.conf
124
-sudo ./edit-config node.d.conf
122
sudo ./edit-config charts.d.conf
123
```
124
docs/guides/step-by-step/step-06.md
+3
-3
@@ -39,7 +39,7 @@ they were built in.
39
40
These modules are primarily written in [Go](https://learn.netdata.cloud/docs/agent/collectors/go.d.plugin/) (`go.d`) and
41
[Python](/collectors/python.d.plugin/README.md), although some use [Bash](/collectors/charts.d.plugin/README.md)
42
-(`charts.d`) or [Node.js](/collectors/node.d.plugin/README.md) (`node.d`).
42
+(`charts.d`).
43
44
## Enable and disable plugins
45
@@ -58,14 +58,14 @@ Enabled:
58
59
```conf
60
[plugins]
61
- # node.d = yes
61
+ # python.d = yes
62
```
63
64
Disabled:
65
66
```conf
67
[plugins]
68
- node.d = no
68
+ python.d = no
69
```
70
71
When you explicitly disable a plugin this way, it won't auto-collect metrics using its collectors.
netdata-installer.sh
-26
@@ -1066,32 +1066,6 @@ fi
1066
# -----------------------------------------------------------------------------
1067
[ -n "${GITHUB_ACTIONS}" ] && echo "::group::Installing Netdata."
1068
1069
-progress "Migrate configuration files for node.d.plugin and charts.d.plugin"
1070
-
1071
-# migrate existing configuration files
1072
-# for node.d and charts.d
1073
-if [ -d "${NETDATA_PREFIX}/etc/netdata" ]; then
1074
- # the configuration directory exists
1075
-
1076
- if [ ! -d "${NETDATA_PREFIX}/etc/netdata/charts.d" ]; then
1077
- run mkdir "${NETDATA_PREFIX}/etc/netdata/charts.d"
1078
- fi
1079
-
1080
- # move the charts.d config files
1081
- for x in apache ap cpu_apps cpufreq example exim hddtemp load_average mem_apps mysql nginx nut opensips phpfpm postfix sensors squid tomcat; do
1082
- for y in "" ".old" ".orig"; do
1083
- if [ -f "${NETDATA_PREFIX}/etc/netdata/${x}.conf${y}" ] && [ ! -f "${NETDATA_PREFIX}/etc/netdata/charts.d/${x}.conf${y}" ]; then
1084
- run mv -f "${NETDATA_PREFIX}/etc/netdata/${x}.conf${y}" "${NETDATA_PREFIX}/etc/netdata/charts.d/${x}.conf${y}"
1085
- fi
1086
- done
1087
- done
1088
-
1089
- if [ ! -d "${NETDATA_PREFIX}/etc/netdata/node.d" ]; then
1090
- run mkdir "${NETDATA_PREFIX}/etc/netdata/node.d"
1091
- fi
1092
-
1093
-fi
1094
-
1069
# -----------------------------------------------------------------------------
1070
1071
# shellcheck disable=SC2230
netdata.spec.in
-2
@@ -489,11 +489,9 @@ rm -rf "${RPM_BUILD_ROOT}"
489
%dir %{_libexecdir}/%{name}/python.d
490
%dir %{_libexecdir}/%{name}/charts.d
491
%dir %{_libexecdir}/%{name}/plugins.d
492
-%dir %{_libexecdir}/%{name}/node.d
492
493
%{_libexecdir}/%{name}/python.d
494
%{_libexecdir}/%{name}/plugins.d
496
-%{_libexecdir}/%{name}/node.d
495
496
%caps(cap_dac_read_search,cap_sys_ptrace=ep) %attr(0750,root,netdata) %{_libexecdir}/%{name}/plugins.d/apps.plugin
497
packaging/installer/install-required-packages.sh
+2
-35
@@ -18,7 +18,6 @@ fi
18
# These options control which packages we are going to install
19
# They can be pre-set, but also can be controlled with command line options
20
PACKAGES_NETDATA=${PACKAGES_NETDATA-1}
21
-PACKAGES_NETDATA_NODEJS=${PACKAGES_NETDATA_NODEJS-0}
21
PACKAGES_NETDATA_PYTHON=${PACKAGES_NETDATA_PYTHON-0}
22
PACKAGES_NETDATA_PYTHON3=${PACKAGES_NETDATA_PYTHON3-1}
23
PACKAGES_NETDATA_PYTHON_MYSQL=${PACKAGES_NETDATA_PYTHON_MYSQL-0}
@@ -103,10 +102,7 @@ Supported packages (you can append many of them):
102
node.js, python, sensors, etc
103
104
- netdata minimum packages required to install netdata
106
- (no mysql client, no nodejs, includes python)
107
-
108
- - nodejs install nodejs
109
- (required for monitoring named and SNMP)
105
+ (no mysql client, includes python)
106
107
- python install python
108
@@ -930,20 +926,6 @@ declare -A pkg_nginx=(
926
['default']="nginx"
927
)
928
933
-declare -A pkg_nodejs=(
934
- ['gentoo']="net-libs/nodejs"
935
- ['clearlinux']="nodejs-basic"
936
- ['freebsd']="node"
937
- ['default']="nodejs"
938
-
939
- # exceptions
940
- ['rhel-6']="WARNING|To install nodejs check: https://nodejs.org/en/download/package-manager/"
941
- ['rhel-7']="WARNING|To install nodejs check: https://nodejs.org/en/download/package-manager/"
942
- ['centos-6']="WARNING|To install nodejs check: https://nodejs.org/en/download/package-manager/"
943
- ['debian-6']="WARNING|To install nodejs check: https://nodejs.org/en/download/package-manager/"
944
- ['debian-7']="WARNING|To install nodejs check: https://nodejs.org/en/download/package-manager/"
945
-)
946
-
929
declare -A pkg_postfix=(
930
['gentoo']="mail-mta/postfix"
931
['macos']="WARNING|"
@@ -1447,13 +1429,6 @@ packages() {
1429
suitable_package libelf
1430
fi
1431
1450
- # -------------------------------------------------------------------------
1451
- # scripting interpreters for netdata plugins
1452
-
1453
- if [ "${PACKAGES_NETDATA_NODEJS}" -ne 0 ]; then
1454
- require_cmd nodejs node js || suitable_package nodejs
1455
- fi
1456
-
1432
# -------------------------------------------------------------------------
1433
# python2
1434
@@ -2001,7 +1976,7 @@ EOF
1976
remote_log() {
1977
# log success or failure on our system
1978
# to help us solve installation issues
2004
- curl > /dev/null 2>&1 -Ss --max-time 3 "https://registry.my-netdata.io/log/installer?status=${1}&error=${2}&distribution=${distribution}&version=${version}&installer=${package_installer}&tree=${tree}&detection=${detection}&netdata=${PACKAGES_NETDATA}&nodejs=${PACKAGES_NETDATA_NODEJS}&python=${PACKAGES_NETDATA_PYTHON}&python3=${PACKAGES_NETDATA_PYTHON3}&mysql=${PACKAGES_NETDATA_PYTHON_MYSQL}&postgres=${PACKAGES_NETDATA_PYTHON_POSTGRES}&pymongo=${PACKAGES_NETDATA_PYTHON_MONGO}&sensors=${PACKAGES_NETDATA_SENSORS}&database=${PACKAGES_NETDATA_DATABASE}&ebpf=${PACKAGES_NETDATA_EBPF}&firehol=${PACKAGES_FIREHOL}&fireqos=${PACKAGES_FIREQOS}&iprange=${PACKAGES_IPRANGE}&update_ipsets=${PACKAGES_UPDATE_IPSETS}&demo=${PACKAGES_NETDATA_DEMO_SITE}"
1979
+ curl > /dev/null 2>&1 -Ss --max-time 3 "https://registry.my-netdata.io/log/installer?status=${1}&error=${2}&distribution=${distribution}&version=${version}&installer=${package_installer}&tree=${tree}&detection=${detection}&netdata=${PACKAGES_NETDATA}&python=${PACKAGES_NETDATA_PYTHON}&python3=${PACKAGES_NETDATA_PYTHON3}&mysql=${PACKAGES_NETDATA_PYTHON_MYSQL}&postgres=${PACKAGES_NETDATA_PYTHON_POSTGRES}&pymongo=${PACKAGES_NETDATA_PYTHON_MONGO}&sensors=${PACKAGES_NETDATA_SENSORS}&database=${PACKAGES_NETDATA_DATABASE}&ebpf=${PACKAGES_NETDATA_EBPF}&firehol=${PACKAGES_FIREHOL}&fireqos=${PACKAGES_FIREQOS}&iprange=${PACKAGES_IPRANGE}&update_ipsets=${PACKAGES_UPDATE_IPSETS}&demo=${PACKAGES_NETDATA_DEMO_SITE}"
1980
}
1981
1982
if [ -z "${1}" ]; then
@@ -2062,7 +2037,6 @@ while [ -n "${1}" ]; do
2037
2038
netdata-all)
2039
PACKAGES_NETDATA=1
2065
- PACKAGES_NETDATA_NODEJS=1
2040
if [ "${pv}" -eq 2 ]; then
2041
PACKAGES_NETDATA_PYTHON=1
2042
PACKAGES_NETDATA_PYTHON_MYSQL=1
@@ -2124,12 +2098,6 @@ while [ -n "${1}" ]; do
2098
fi
2099
;;
2100
2127
- nodejs | netdata-nodejs)
2128
- PACKAGES_NETDATA=1
2129
- PACKAGES_NETDATA_NODEJS=1
2130
- PACKAGES_NETDATA_DATABASE=1
2131
- ;;
2132
-
2101
sensors | netdata-sensors)
2102
PACKAGES_NETDATA=1
2103
PACKAGES_NETDATA_PYTHON3=1
@@ -2147,7 +2115,6 @@ while [ -n "${1}" ]; do
2115
2116
demo | all)
2117
PACKAGES_NETDATA=1
2150
- PACKAGES_NETDATA_NODEJS=1
2118
if [ "${pv}" -eq 2 ]; then
2119
PACKAGES_NETDATA_PYTHON=1
2120
PACKAGES_NETDATA_PYTHON_MYSQL=1
tests/alarm_repetition/netdata.conf_with_repetition
-1
@@ -34,7 +34,6 @@
34
enable running new plugins = no
35
check for new plugins every = 60
36
go.d = no
37
- node.d = no
37
charts.d = no
38
nfacct = no
39
python.d = no
tests/alarm_repetition/netdata.conf_without_repetition
-1
@@ -34,7 +34,6 @@
34
enable running new plugins = no
35
check for new plugins every = 60
36
go.d = no
37
- node.d = no
37
charts.d = no
38
nfacct = no
39
python.d = no
tests/lifecycle.bats
+1
-2
@@ -13,8 +13,7 @@ ENV="${INSTALLATION}/netdata/etc/netdata/.environment"
13
# list of files which need to be checked. Path cannot start from '/'
14
FILES="usr/libexec/netdata/plugins.d/go.d.plugin
15
usr/libexec/netdata/plugins.d/charts.d.plugin
16
- usr/libexec/netdata/plugins.d/python.d.plugin
17
- usr/libexec/netdata/plugins.d/node.d.plugin"
16
+ usr/libexec/netdata/plugins.d/python.d.plugin"
17
18
DIRS="usr/sbin/netdata
19
etc/netdata
tests/updater_checks.bats
+1
-2
@@ -13,8 +13,7 @@ ENV="${INSTALLATION}/netdata/etc/netdata/.environment"
13
# list of files which need to be checked. Path cannot start from '/'
14
FILES="usr/libexec/netdata/plugins.d/go.d.plugin
15
usr/libexec/netdata/plugins.d/charts.d.plugin
16
- usr/libexec/netdata/plugins.d/python.d.plugin
17
- usr/libexec/netdata/plugins.d/node.d.plugin"
16
+ usr/libexec/netdata/plugins.d/python.d.plugin"
17
18
DIRS="usr/sbin/netdata
19
etc/netdata