feat: 초기 프로젝트 설정 및 룰.md 파일 추가

This commit is contained in:
2025-07-28 09:53:31 +09:00
commit 09a4d38512
8165 changed files with 1021855 additions and 0 deletions

View File

@@ -0,0 +1,174 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.

8
api.hyungi.net/node_modules/pm2-sysmonit/README.md generated vendored Normal file
View File

@@ -0,0 +1,8 @@
## pm2-sysmonit
Module to retrieve system informations
```bash
$ pm2 install pm2-sysmonit
```

115
api.hyungi.net/node_modules/pm2-sysmonit/index.js generated vendored Normal file
View File

@@ -0,0 +1,115 @@
const tx2 = require('tx2')
const SystemInfos = require('./src/SystemInfos.js')
const PM2Infos = require('./src/pm2.js')
class SysMonit {
constructor() {
this.sysinfos = new SystemInfos()
this.report = {}
this.pass = 0
this.pm2infos = new PM2Infos()
this.pm2_report = {}
}
start() {
this.sysinfos.startCollection()
this.report = this.sysinfos.report()
this.pm2infos.startCollection()
this.pm2_report = this.pm2infos.report()
this.bindActions()
setInterval(() => {
if (this.pass++ < 4)
this.bindMetrics()
this.report = this.sysinfos.report()
this.pm2_report = this.pm2infos.report()
this.processContinuousMetrics()
if (process.env.VERBOSE) {
console.log(JSON.stringify(this.report, '', 2))
console.log(JSON.stringify(this.pm2_report, '', 2))
}
}, 1000)
}
bindActions() {
tx2.action('info', (cb) => {
cb(this.sysinfos.report())
})
}
processContinuousMetrics() {
let most_used_disk = this.report.storage.filesystems.reduce((p, v) => {
return (p.use < v.use ? p : v)
})
tx2.metric(`Disk Usage`, '%', () => most_used_disk.use)
tx2.metric(`Disk Size`, 'gb', () => (most_used_disk.size / 1024 / 1024 / 1024).toFixed(2))
let tx5 = 0, rx5 = 0
Object.keys(this.report.network).forEach(iface => {
tx5 += this.report.network[iface].tx_5
rx5 += this.report.network[iface].rx_5
})
tx2.metric(`Total TX`, 'mb/s', () => tx5)
tx2.metric(`Total RX`, 'mb/s', () => rx5)
}
bindMetrics() {
tx2.metric('PM2 CPU Usage', '%', () => this.pm2_report.pm2.cpu)
tx2.metric('PM2 Memory Usage', 'mb', () => this.pm2_report.pm2.mem)
tx2.metric('PM2 Agent CPU Usage', '%', () => this.pm2_report.agent.cpu)
tx2.metric('PM2 Agent Memory Usage', 'mb', () => this.pm2_report.agent.mem)
/**
* From Sysinfo
*/
tx2.metric('CPU Usage', '%', () => this.report.cpu.load)
tx2.metric('CPUs Usage', () => this.report.cpu.loads)
tx2.metric('CPU Temperature', '°C', () => this.report.cpu.temperature)
tx2.metric('RAM Total', 'gb', () => this.report.mem.total)
tx2.metric('RAM Free', 'gb', () => this.report.mem.free)
tx2.metric('RAM Active', 'gb', () => this.report.mem.active)
tx2.metric('RAM Available', 'gb', () => this.report.mem.available)
tx2.metric('RAM Usage', '%', () => this.report.mem.usage)
tx2.metric('FD Opened', () => this.report.fd.opened)
tx2.metric('Disk Writes', 'mb/s', () => this.report.storage.io.read)
tx2.metric('Disk Reads', 'mb/s', () => this.report.storage.io.write)
this.report.storage.filesystems.forEach((fss, i) => {
if (!fss.fs) return
tx2.metric(`fs:use:${fss.fs}`, '%', () => this.report.storage.filesystems[i].use)
tx2.metric(`fs:size:${fss.fs}`, 'gb', () => (this.report.storage.filesystems[i].size / 1024 / 1024 / 1024).toFixed(2))
})
Object.keys(this.report.network).forEach(iface => {
tx2.metric(`net:tx_5:${iface}`, 'mb/s', () => this.report.network[iface].tx_5)
tx2.metric(`net:rx_5:${iface}`, 'mb/s', () => this.report.network[iface].rx_5)
tx2.metric(`net:rx_errors_60:${iface}`, '/min', () => this.report.network[iface].rx_errors_60)
tx2.metric(`net:tx_errors_60:${iface}`, '/min', () => this.report.network[iface].tx_errors_60)
tx2.metric(`net:rx_dropped_60:${iface}`, '/min', () => this.report.network[iface].rx_dropped_60)
tx2.metric(`net:tx_dropped_60:${iface}`, '/min', () => this.report.network[iface].tx_dropped_60)
})
if (this.report.graphics.memTotal) {
tx2.metric('graphics:mem:total', 'mb', () => this.report.graphics.memTotal)
tx2.metric('graphics:mem:used', 'mb', () => this.report.graphics.memUsed)
tx2.metric('graphics:temp', '°C', () => this.report.graphics.temperature)
}
//tx2.transpose('report', () => this.report)
}
}
if (require.main === module) {
let sys = new SysMonit()
sys.start()
}

View File

@@ -0,0 +1,85 @@
### 2.0.17
- allow to manually clear the event loop when needed it'll clear itself after a given timeout (default to `60000ms` but you can specify it with the `maxage` option, [see this file](https://github.com/soyuka/pidusage/blob/master/test/fixtures/eventloop.js#L3)) [1740a4f](https://github.com/soyuka/pidusage/commit/2779e520d3414a8318c86279cf14bebae3264604)
- fix elapsed and timestamp calculations on linux [#80](https://github.com/soyuka/pidusage/issues/80) [e5e2b01](https://github.com/soyuka/pidusage/commit/081984a04bc97ad8abd82315f936861cce1df0d6)
### 2.0.16
- fix ps on darwin, centisenconds multiplier was wrong and was giving bad cpu usage values [bcda538](https://github.com/soyuka/pidusage/commit/bcda538b76498c6d4bcaa36520238990554929c5)
### 2.0.15
- Fix Buffer.alloc for node < 4.5
### 2.0.14
- Version unpublished because of a publish mistake from my part due to a npm error message that confused me. Explanation [in isse #71](https://github.com/soyuka/pidusage/issues/72#issuecomment-407572581)
### 2.0.12
- fix #69 with `ps` use elapsed instead of etime to avoid negative cpu values [0994268](https://github.com/soyuka/pidusage/commit/0994268c297e23efa3d9052f24cbacf2cbe31629)
- fix typo in aix `ps` command #68 [7d55518](https://github.com/soyuka/pidusage/commit/7d55518b7d5d5aae964e64ddd7b13ecec75463a1)
### 2.0.10
- aix is using ps (was changed by mistake), still no aix CI though
- add alpine to the test suite and make it use procfile
- Improve procfile performances by keeping the procfile open [da1c5fb](https://github.com/soyuka/pidusage/commit/da1c5fb2480bdf8f871476d79161dac7733b89f3)
### 2.0.8
- After further discussion cpu formula got reverted to the initial one [f990f72](https://github.com/soyuka/pidusage/commit/f990f72fd185e4ba0a87048e6e6c59f814a016cc)
### 2.0.7
- Cpu formula changed a bit because of multi thread issues see [issue #58](https://github.com/soyuka/pidusage/issues/58) [88972d8](https://github.com/soyuka/pidusage/commit/88972d8cd38d4137b70261a830af22283b69c57c)
### 2.0.6
- procfiles are back because of performance issues [85e20fa](https://github.com/soyuka/pidusage/commit/85e20fa30aa9ff01d87d3ba9be7fec7f805fc5fb)
### 2.0
- allow multiple pids
- remove `advanced` option
- don't use `/proc` (procfiles) anymore but use `ps` instead
- more tests
- API change no more `stat` method, module exports a single function
- no more `unmonitor` method, this is handed internally
- the default call now returns more data:
```
{
cpu: 10.0, // percentage (it may happen to be greater than 100%)
memory: 357306368, // bytes
ppid: 312, // PPID
pid: 727, // PID
ctime: 867000, // ms user + system time
elapsed: 6650000, // ms since the start of the process
timestamp: 864000000 // ms since epoch
}
```
### 1.2.0
Introduce `advanced` option to get time, and start
### 1.1.0
Windows: (wmic) goes back to the first version of wmic, naming `wmic process {pid} get workingsetsize,usermodetime,kernelmodetime`. CPU usage % is computed on the flight, per pid.
### 1.0.5
Windows: (wmic) Use raw data instead of formatted this should speed up wmic
### 0.1.0
API changes:
```
require('pidusage').stat(pid, fn)
```
instead of:
```
require('pidusage')(pid, fn)
```
Adds a `unmonitor` method to clear process history

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 soyuka
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,189 @@
# pidusage
[![Mac/Linux Build Status](https://img.shields.io/travis/soyuka/pidusage/master.svg?label=MacOS%20%26%20Linux)](https://travis-ci.org/soyuka/pidusage)
[![Windows Build status](https://img.shields.io/appveyor/ci/soyuka/pidusage/master.svg?label=Windows)](https://ci.appveyor.com/project/soyuka/pidusage)
[![Code coverage](https://img.shields.io/codecov/c/github/soyuka/pidusage/master.svg)](https://codecov.io/gh/soyuka/pidusage)
[![npm version](https://img.shields.io/npm/v/pidusage.svg)](https://www.npmjs.com/package/pidusage)
[![license](https://img.shields.io/github/license/soyuka/pidusage.svg)](https://github.com/soyuka/pidusage/tree/master/license)
Cross-platform process cpu % and memory usage of a PID.
## Synopsis
Ideas from https://github.com/arunoda/node-usage but with no C-bindings.
Please note that if you need to check a Node.JS script process cpu and memory usage, you can use [`process.cpuUsage`][node:cpuUsage] and [`process.memoryUsage`][node:memUsage] since node v6.1.0. This script remain useful when you have no control over the remote script, or if the process is not a Node.JS process.
## Usage
```js
var pidusage = require('pidusage')
pidusage(process.pid, function (err, stats) {
console.log(stats)
// => {
// cpu: 10.0, // percentage (from 0 to 100*vcore)
// memory: 357306368, // bytes
// ppid: 312, // PPID
// pid: 727, // PID
// ctime: 867000, // ms user + system time
// elapsed: 6650000, // ms since the start of the process
// timestamp: 864000000 // ms since epoch
// }
cb()
})
// It supports also multiple pids
pidusage([727, 1234], function (err, stats) {
console.log(stats)
// => {
// 727: {
// cpu: 10.0, // percentage (from 0 to 100*vcore)
// memory: 357306368, // bytes
// ppid: 312, // PPID
// pid: 727, // PID
// ctime: 867000, // ms user + system time
// elapsed: 6650000, // ms since the start of the process
// timestamp: 864000000 // ms since epoch
// },
// 1234: {
// cpu: 0.1, // percentage (from 0 to 100*vcore)
// memory: 3846144, // bytes
// ppid: 727, // PPID
// pid: 1234, // PID
// ctime: 0, // ms user + system time
// elapsed: 20000, // ms since the start of the process
// timestamp: 864000000 // ms since epoch
// }
// }
})
// If no callback is given it returns a promise instead
const stats = await pidusage(process.pid)
console.log(stats)
// => {
// cpu: 10.0, // percentage (from 0 to 100*vcore)
// memory: 357306368, // bytes
// ppid: 312, // PPID
// pid: 727, // PID
// ctime: 867000, // ms user + system time
// elapsed: 6650000, // ms since the start of the process
// timestamp: 864000000 // ms since epoch
// }
// Avoid using setInterval as they could overlap with asynchronous processing
function compute(cb) {
pidusage(process.pid, function (err, stats) {
console.log(stats)
// => {
// cpu: 10.0, // percentage (from 0 to 100*vcore)
// memory: 357306368, // bytes
// ppid: 312, // PPID
// pid: 727, // PID
// ctime: 867000, // ms user + system time
// elapsed: 6650000, // ms since the start of the process
// timestamp: 864000000 // ms since epoch
// }
cb()
})
}
function interval(time) {
setTimeout(function() {
compute(function() {
interval(time)
})
}, time)
}
// Compute statistics every second:
interval(1000)
// Above example using async/await
const compute = async () => {
const stats = await pidusage(process.pid)
// do something
}
// Compute statistics every second:
const interval = async (time) => {
setTimeout(async () => {
await compute()
interval(time)
}, time)
}
interval(1000)
```
## Compatibility
| Property | Linux | FreeBSD | NetBSD | SunOS | macOS | Win | AIX | Alpine
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| `cpu` | ✅ | ❓ | ❓ | ❓ | ✅ | | ❓ | ✅ |
| `memory` | ✅ | ❓ | ❓ | ❓ | ✅ | ✅ | ❓ | ✅ |
| `pid` | ✅ | ❓ | ❓ | ❓ | ✅ | ✅ | ❓ | ✅ |
| `ctime` | ✅ | ❓ | ❓ | ❓ | ✅ | ✅ | ❓ | ✅ |
| `elapsed` | ✅ | ❓ | ❓ | ❓ | ✅ | ✅ | ❓ | ✅ |
| `timestamp` | ✅ | ❓ | ❓ | ❓ | ✅ | ✅ | ❓ | ✅ |
✅ = Working
= Not Accurate
❓ = Should Work
❌ = Not Working
Please if your platform is not supported or if you have reported wrong readings
[file an issue][new issue].
By default, pidusage will use `procfile` parsing on most unix systems. If you want to use `ps` instead use the `usePs` option:
```
pidusage(pid, {usePs: true})
```
## API
<a name="pidusage"></a>
### pidusage(pids, [options = {}], [callback]) ⇒ <code>[Promise.&lt;Object&gt;]</code>
Get pid informations.
**Kind**: global function
**Returns**: <code>Promise.&lt;Object&gt;</code> - Only when the callback is not provided.
**Access**: public
| Param | Type | Description |
| --- | --- | --- |
| pids | <code>Number</code> \| <code>Array.&lt;Number&gt;</code> \| <code>String</code> \| <code>Array.&lt;String&gt;</code> | A pid or a list of pids. |
| [callback] | <code>function</code> | Called when the statistics are ready. If not provided a promise is returned instead. |
### pidusage.clear()
If needed this function can be used to delete all in-memory metrics and clear the event loop. This is not necessary before exiting as the interval we're registring does not hold up the event loop.
## Related
- [pidusage-tree][gh:pidusage-tree] -
Compute a pidusage tree
## Authors
- **Antoine Bluchet** - [soyuka][github:soyuka]
- **Simone Primarosa** - [simonepri][github:simonepri]
See also the list of [contributors][contributors] who participated in this project.
## License
This project is licensed under the MIT License - see the [LICENSE][license] file for details.
<!-- Links -->
[new issue]: https://github.com/soyuka/pidusage/issues/new
[license]: https://github.com/soyuka/pidusage/tree/master/LICENSE
[contributors]: https://github.com/soyuka/pidusage/contributors
[github:soyuka]: https://github.com/soyuka
[github:simonepri]: https://github.com/simonepri
[gh:pidusage-tree]: https://github.com/soyuka/pidusage-tree
[node:cpuUsage]: https://nodejs.org/api/process.html#process_process_cpuusage_previousvalue
[node:memUsage]: https://nodejs.org/api/process.html#process_process_memoryusage

View File

@@ -0,0 +1,38 @@
'use strict'
var stats = require('./lib/stats')
/**
* Get pid informations.
* @public
* @param {Number|Number[]|String|String[]} pids A pid or a list of pids.
* @param {Object} [options={}] Options object
* @param {Function} [callback=undefined] Called when the statistics are ready.
* If not provided a promise is returned instead.
* @returns {Promise.<Object>} Only when the callback is not provided.
*/
function pidusage (pids, options, callback) {
if (typeof options === 'function') {
callback = options
options = {}
}
if (options === undefined) {
options = {}
}
if (typeof callback === 'function') {
stats(pids, options, callback)
return
}
return new Promise(function (resolve, reject) {
stats(pids, options, function (err, data) {
if (err) return reject(err)
resolve(data)
})
})
}
module.exports = pidusage
module.exports.clear = require('./lib/history').clear

View File

@@ -0,0 +1,48 @@
'use strict'
var spawn = require('child_process').spawn
/**
* Spawn a binary and read its stdout.
* @param {String} cmd
* @param {String[]} args
* @param {Function} done(err, stdout)
*/
function run (cmd, args, options, done) {
if (typeof options === 'function') {
done = options
options = undefined
}
var executed = false
var ch = spawn(cmd, args, options)
var stdout = ''
var stderr = ''
ch.stdout.on('data', function (d) {
stdout += d.toString()
})
ch.stderr.on('data', function (d) {
stderr += d.toString()
})
ch.on('error', function (err) {
if (executed) return
executed = true
done(new Error(err))
})
ch.on('close', function (code, signal) {
if (executed) return
executed = true
if (stderr) {
return done(new Error(stderr))
}
done(null, stdout, code)
})
}
module.exports = run

View File

@@ -0,0 +1,87 @@
var os = require('os')
var fs = require('fs')
var exec = require('child_process').exec
var parallel = require('./parallel')
/**
* Gathers Clock, PageSize and system uptime through /proc/uptime
* This method is mocked in procfile tests
*/
function updateCpu (cpu, next) {
if (cpu !== null) {
getRealUptime(function (err, uptime) {
if (err) return next(err)
cpu.uptime = uptime
next(null, cpu)
})
return
}
parallel([
getClockAndPageSize,
getRealUptime
], function (err, data) {
if (err) return next(err)
cpu = {
clockTick: data[0].clockTick,
pageSize: data[0].pageSize,
uptime: data[1]
}
next(null, cpu)
})
}
module.exports = updateCpu
/**
* Fallback on os.uptime(), though /proc/uptime is more precise
*/
function getRealUptime (next) {
fs.readFile('/proc/uptime', 'utf8', function (err, uptime) {
if (err || uptime === undefined) {
console.warn("[pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value")
return next(null, os.uptime())
}
return next(null, parseFloat(uptime.split(' ')[0]))
})
}
function getClockAndPageSize (next) {
parallel([
function getClockTick (cb) {
getconf('CLK_TCK', { default: 100 }, cb)
},
function getPageSize (cb) {
getconf('PAGESIZE', { default: 4096 }, cb)
}
], function (err, data) {
if (err) return next(err)
next(null, { clockTick: data[0], pageSize: data[1] })
})
}
function getconf (keyword, options, next) {
if (typeof options === 'function') {
next = options
options = { default: '' }
}
exec('getconf ' + keyword, function (error, stdout, stderr) {
if (error !== null) {
console.error('Error while getting ' + keyword, error)
return next(null, options.default)
}
stdout = parseInt(stdout)
if (!isNaN(stdout)) {
return next(null, stdout)
}
return next(null, options.default)
})
}

View File

@@ -0,0 +1,44 @@
// execute an array of asynchronous functions in parallel
// @param {Array} fns - an array of functions
// @param {Function} done - callback(err, results)
function parallel (fns, options, done) {
if (typeof options === 'function') {
done = options
options = {}
}
var keys
if (!Array.isArray(fns)) { keys = Object.keys(fns) }
var length = keys ? keys.length : fns.length
var pending = length
var results = keys ? {} : []
function each (i, err, result) {
results[i] = result
if (--pending === 0 || (err && !options.graceful)) {
if (options.graceful && err && length > 1) {
err = null
}
done && done(err, results)
done = null
}
}
if (keys) {
keys.forEach(function (key) {
fns[key](function (err, res) {
each(key, err, res)
})
})
} else {
fns.forEach(function (fn, i) {
fn(function (err, res) {
each(i, err, res)
})
})
}
}
module.exports = parallel

View File

@@ -0,0 +1,92 @@
'use strict'
var DEFAULT_MAXAGE = 60000
var expiration = {}
var history = {}
var expireListeners = {}
var size = 0
var interval = null
function get (pid, maxage) {
if (maxage <= 0) {
return
}
if (history[pid] !== undefined) {
expiration[pid] = Date.now() + (maxage || DEFAULT_MAXAGE)
}
return history[pid]
}
function set (pid, object, maxage, onExpire) {
if (object === undefined || maxage <= 0) return
expiration[pid] = Date.now() + (maxage || DEFAULT_MAXAGE)
if (history[pid] === undefined) {
size++
sheduleInvalidator(maxage)
}
history[pid] = object
if (onExpire) {
expireListeners[pid] = onExpire
}
}
function sheduleInvalidator (maxage) {
if (size > 0) {
if (interval === null) {
interval = setInterval(runInvalidator, (maxage || DEFAULT_MAXAGE) / 2)
if (typeof interval.unref === 'function') {
interval.unref()
}
}
return
}
if (interval !== null) {
clearInterval(interval)
interval = null
}
}
function runInvalidator () {
var now = Date.now()
var pids = Object.keys(expiration)
for (var i = 0; i < pids.length; i++) {
var pid = pids[i]
if (expiration[pid] < now) {
size--
if (expireListeners[pid]) {
expireListeners[pid](history[pid])
}
delete history[pid]
delete expiration[pid]
delete expireListeners[pid]
}
}
sheduleInvalidator()
}
function deleteLoop (obj) { for (const i in obj) { delete obj[i] } }
function clear () {
if (interval !== null) {
clearInterval(interval)
interval = null
}
deleteLoop(history)
deleteLoop(expiration)
deleteLoop(expireListeners)
}
module.exports = {
get: get,
set: set,
clear: clear
}

View File

@@ -0,0 +1,141 @@
var fs = require('fs')
var path = require('path')
var updateCpu = require('./helpers/cpu')
var parallel = require('./helpers/parallel')
var history = require('./history')
var cpuInfo = null
var Buffer = require('safe-buffer').Buffer
var SIZE = 1024 // if the stat file is bigger then this I'll buy you a drink
function noop () {}
function open (path, history, cb) {
if (history.fd) { return cb(null, history.fd) }
fs.open(path, 'r', cb)
}
function close (history) {
if (history.fd) {
fs.close(history.fd, noop)
}
}
function readUntilEnd (fd, buf, cb) {
var firstRead = false
if (typeof buf === 'function') {
cb = buf
buf = Buffer.alloc(SIZE)
firstRead = true
}
fs.read(fd, buf, 0, SIZE, 0, function (err, bytesRead, buffer) {
if (err) {
cb(err)
return
}
var data = Buffer.concat([buf, buffer], firstRead ? bytesRead : buf.length + bytesRead)
if (bytesRead === SIZE) {
readUntilEnd(fd, data, cb)
return
}
cb(null, buf)
})
}
function readProcFile (pid, options, done) {
var hst = history.get(pid, options.maxage)
var again = false
if (hst === undefined) {
again = true
hst = {}
}
// Arguments to path.join must be strings
open(path.join('/proc', '' + pid, 'stat'), hst, function (err, fd) {
if (err) {
if (err.code === 'ENOENT') {
err.message = 'No matching pid found'
}
return done(err, null)
}
if (err) {
return done(err)
}
readUntilEnd(fd, function (err, buffer) {
if (err) {
return done(err)
}
var infos = buffer.toString('utf8')
var date = Date.now()
// https://github.com/arunoda/node-usage/commit/a6ca74ecb8dd452c3c00ed2bde93294d7bb75aa8
// preventing process space in name by removing values before last ) (pid (name) ...)
var index = infos.lastIndexOf(')')
infos = infos.substr(index + 2).split(' ')
// according to http://man7.org/linux/man-pages/man5/proc.5.html (index 0 based - 2)
// In kernels before Linux 2.6, start was expressed in jiffies. Since Linux 2.6, the value is expressed in clock ticks
var stat = {
ppid: parseInt(infos[1]),
utime: parseFloat(infos[11]) * 1000 / cpuInfo.clockTick,
stime: parseFloat(infos[12]) * 1000 / cpuInfo.clockTick,
cutime: parseFloat(infos[13]) * 1000 / cpuInfo.clockTick,
cstime: parseFloat(infos[14]) * 1000 / cpuInfo.clockTick,
start: parseFloat(infos[19]) * 1000 / cpuInfo.clockTick,
rss: parseFloat(infos[21]),
uptime: cpuInfo.uptime * 1000,
fd: fd
}
var memory = stat.rss * cpuInfo.pageSize
// https://stackoverflow.com/a/16736599/3921589
var childrens = options.childrens ? stat.cutime + stat.cstime : 0
// process usage since last call in seconds
var total = (stat.stime - (hst.stime || 0) + stat.utime - (hst.utime || 0) + childrens)
// time elapsed between calls in seconds
var seconds = Math.abs(hst.uptime !== undefined ? stat.uptime - hst.uptime : stat.start - stat.uptime)
var cpu = seconds > 0 ? (total / seconds) * 100 : 0
history.set(pid, stat, options.maxage, close)
if (again) {
return readProcFile(pid, options, done)
}
return done(null, {
cpu: cpu,
memory: memory,
ctime: stat.utime + stat.stime,
elapsed: stat.uptime - stat.start,
timestamp: date,
pid: pid,
ppid: stat.ppid
})
})
})
}
function procfile (pids, options, done) {
updateCpu(cpuInfo, function (err, result) {
if (err) return done(err)
cpuInfo = result
var fns = {}
pids.forEach(function (pid, i) {
fns[pid] = function (cb) {
readProcFile(pid, options, cb)
}
})
parallel(fns, { graceful: true }, done)
})
}
module.exports = procfile

View File

@@ -0,0 +1,128 @@
'use strict'
var os = require('os')
var bin = require('./bin')
var history = require('./history')
var PLATFORM = os.platform()
function parseTime (timestr, centisec) {
var time = 0
var tpart = timestr.split(/-|:|\./)
var i = tpart.length - 1
if (i >= 0 && centisec && PLATFORM === 'darwin') {
time += parseInt(tpart[i--], 10) * 10
}
if (i >= 0) { // Seconds
time += parseInt(tpart[i--], 10) * 1000
}
if (i >= 0) { // Minutes
time += parseInt(tpart[i--], 10) * 60000
}
if (i >= 0) { // Hours
time += parseInt(tpart[i--], 10) * 3600000
}
if (i >= 0) { // Days
time += parseInt(tpart[i--], 10) * 86400000
}
return time
}
/**
* Get pid informations through ps command.
* @param {Number[]} pids
* @param {Object} options
* @param {Function} done(err, stat)
*/
function ps (pids, options, done) {
var pArg = pids.join(',')
var args = ['-o', 'etime,pid,ppid,pcpu,rss,time', '-p', pArg]
if (PLATFORM === 'aix') {
args = ['-o', 'etime,pid,ppid,pcpu,rssize,time', '-p', pArg]
}
bin('ps', args, function (err, stdout, code) {
if (err) return done(err)
if (code === 1) {
const error = new Error('No matching pid found')
error.code = 'ENOENT'
return done(error)
}
if (code !== 0) {
return done(new Error('pidusage ps command exited with code ' + code))
}
var date = Date.now()
// Example of stdout on *nix.
// ELAPSED: format is [[dd-]hh:]mm:ss
// RSS: is counted as blocks of 1024 bytes
// TIME: format is [[dd-]hh:]mm:ss
// %CPU: goes from 0 to vcore * 100
//
// Refs: http://www.manpages.info/linux/ps.1.html
// NB: The columns are returned in the order given inside the -o option
//
// ELAPSED PID PPID %CPU RSS TIME
// 2-40:50:53 430 1 3.0 5145 1-02:03:04
// 40:50:53 432 430 0.0 2364 1-01:02:03
// 01:50:50 727 1 10.0 348932 14:27
// 00:20 7166 1 0.1 3756 0:00
// Example of stdout on Darwin
// ELAPSED: format is [[dd-]hh:]mm:ss
// RSS: is counted as blocks of 1024 bytes
// TIME: format is [[dd-]hh:]mm:ss.cc (cc are centiseconds)
// %CPU: goes from 0 to vcore * 100
//
// Refs: https://ss64.com/osx/ps.html
// NB: The columns are returned in the order given inside the -o option
//
// ELAPSED PID PPID %CPU RSS TIME
// 2-40:50:53 430 1 3.0 5145 1-02:03:04.07
// 40:50:53 432 430 0.0 2364 1-01:02:03.10
// 01:50:50 727 1 10.0 348932 14:27.26
// 00:20 7166 1 0.1 3756 0:00.02
stdout = stdout.split(os.EOL)
var statistics = {}
for (var i = 1; i < stdout.length; i++) {
var line = stdout[i].trim().split(/\s+/)
if (!line || line.length !== 6) {
continue
}
var pid = parseInt(line[1], 10)
var hst = history.get(pid, options.maxage)
if (hst === undefined) hst = {}
var ppid = parseInt(line[2], 10)
var memory = parseInt(line[4], 10) * 1024
var etime = parseTime(line[0])
var ctime = parseTime(line[5], true)
var total = (ctime - (hst.ctime || 0))
// time elapsed between calls in seconds
var seconds = Math.abs(hst.elapsed !== undefined ? etime - hst.elapsed : etime)
var cpu = seconds > 0 ? (total / seconds) * 100 : 0
statistics[pid] = {
cpu: cpu,
memory: memory,
ppid: ppid,
pid: pid,
ctime: ctime,
elapsed: etime,
timestamp: date
}
history.set(pid, statistics[pid], options.maxage)
}
done(null, statistics)
})
}
module.exports = ps

View File

@@ -0,0 +1,87 @@
'use strict'
var fs = require('fs')
var os = require('os')
var platformToMethod = {
aix: 'ps',
android: 'procfile',
alpine: 'procfile',
darwin: 'ps',
freebsd: 'ps',
linux: 'procfile',
netbsd: 'procfile',
sunos: 'ps',
win: 'wmic'
}
var ps = require('./ps')
var platform = os.platform()
if (fs.existsSync('/etc/alpine-release')) {
platform = 'alpine'
}
if (platform.match(/^win/)) {
platform = 'win'
}
var stat
try {
stat = require('./' + platformToMethod[platform])
} catch (err) {}
/**
* @callback pidCallback
* @param {Error} err A possible error.
* @param {Object} statistics The object containing the statistics.
*/
/**
* Get pid informations.
* @public
* @param {Number|Number[]|String|String[]} pids A pid or a list of pids.
* @param {Object} [options={}] Options object
* @param {pidCallback} callback Called when the statistics are ready.
*/
function get (pids, options, callback) {
var fn = stat
if (platform !== 'win' && options.usePs === true) {
fn = ps
}
if (stat === undefined) {
return callback(new Error(os.platform() + ' is not supported yet, please open an issue (https://github.com/soyuka/pidusage)'))
}
var single = false
if (!Array.isArray(pids)) {
single = true
pids = [pids]
}
if (pids.length === 0) {
return callback(new TypeError('You must provide at least one pid'))
}
for (var i = 0; i < pids.length; i++) {
pids[i] = parseInt(pids[i], 10)
if (isNaN(pids[i]) || pids[i] < 0) {
return callback(new TypeError('One of the pids provided is invalid'))
}
}
fn(pids, options, function (err, stats) {
if (err) {
return callback(err)
}
if (single) {
callback(null, stats[pids[0]])
} else {
callback(null, stats)
}
})
}
module.exports = get

View File

@@ -0,0 +1,132 @@
'use strict'
var os = require('os')
var bin = require('./bin')
var history = require('./history')
function parseDate (datestr) {
var year = datestr.substring(0, 4)
var month = datestr.substring(4, 6)
var day = datestr.substring(6, 8)
var hour = datestr.substring(8, 10)
var minutes = datestr.substring(10, 12)
var seconds = datestr.substring(12, 14)
var useconds = datestr.substring(15, 21)
var sign = datestr.substring(21, 22)
var tmz = parseInt(datestr.substring(22, 25), 10)
var tmzh = Math.floor(tmz / 60)
var tmzm = tmz % 60
return new Date(
year + '-' + month + '-' + day + 'T' + hour +
':' + minutes + ':' + seconds +
'.' + useconds +
sign + (tmzh > 9 ? tmzh : '0' + tmzh) + '' + (tmzm > 9 ? tmzm : '0' + tmzm)
)
}
/**
* Get pid informations through wmic command.
* @param {Number[]} pids
* @param {Object} options
* @param {Function} done(err, stat)
*/
function wmic (pids, options, done) {
var whereClause = 'ProcessId=' + pids[0]
for (var i = 1; i < pids.length; i++) {
whereClause += ' or ' + 'ProcessId=' + pids[i]
}
var args = [
'PROCESS',
'where',
'"' + whereClause + '"',
'get',
'CreationDate,KernelModeTime,ParentProcessId,ProcessId,UserModeTime,WorkingSetSize'
]
bin('wmic', args, { windowsHide: true, windowsVerbatimArguments: true }, function (err, stdout, code) {
if (err) {
if (err.message.indexOf('No Instance(s) Available.') !== -1) {
const error = new Error('No matching pid found')
error.code = 'ENOENT'
return done(error)
}
return done(err)
}
if (code !== 0) {
return done(new Error('pidusage wmic command exited with code ' + code))
}
var date = Date.now()
// Note: On Windows the returned value includes fractions of a second.
// Use Math.floor() to get whole seconds.
var uptime = Math.floor(os.uptime())
// Example of stdout on Windows 10
// CreationDate: is in the format yyyymmddHHMMSS.mmmmmmsUUU
// KernelModeTime: is in units of 100 ns
// UserModeTime: is in units of 100 ns
// WorkingSetSize: is in bytes
//
// Refs: https://superuser.com/a/937401/470946
// Refs: https://msdn.microsoft.com/en-us/library/aa394372(v=vs.85).aspx
// NB: The columns are returned in lexicographical order
//
// CreationDate KernelModeTime ParentProcessId ProcessId UserModeTime WorkingSetSize
// 20150329221650.080654+060 153750000 0 777 8556250000 110821376
stdout = stdout.split(os.EOL)
var again = false
var statistics = {}
for (var i = 1; i < stdout.length; i++) {
var line = stdout[i].trim().split(/\s+/)
if (!line || line.length !== 6) {
continue
}
var creation = parseDate(line[0])
var ppid = parseInt(line[2], 10)
var pid = parseInt(line[3], 10)
var kerneltime = Math.round(parseInt(line[1], 10) / 10000)
var usertime = Math.round(parseInt(line[4], 10) / 10000)
var memory = parseInt(line[5], 10)
var hst = history.get(pid, options.maxage)
if (hst === undefined) {
again = true
hst = { ctime: kerneltime + usertime, uptime: uptime }
}
// process usage since last call
var total = (kerneltime + usertime - hst.ctime) / 1000
// time elapsed between calls in seconds
var seconds = uptime - hst.uptime
var cpu = seconds > 0 ? (total / seconds) * 100 : 0
history.set(pid, { ctime: usertime + kerneltime, uptime: uptime }, options.maxage)
statistics[pid] = {
cpu: cpu,
memory: memory,
ppid: ppid,
pid: pid,
ctime: usertime + kerneltime,
elapsed: date - creation.getTime(),
timestamp: date
}
}
if (again) {
return wmic(pids, options, function (err, stats) {
if (err) return done(err)
done(null, Object.assign(statistics, stats))
})
}
done(null, statistics)
})
}
module.exports = wmic

View File

@@ -0,0 +1,62 @@
{
"name": "pidusage",
"version": "2.0.21",
"description": "Cross-platform process cpu % and memory usage of a PID",
"license": "MIT",
"homepage": "https://github.com/soyuka/pidusage",
"repository": "github:soyuka/pidusage",
"bugs": {
"url": "https://github.com/soyuka/pidusage/issues"
},
"author": "soyuka",
"contributors": [
"Simone Primarosa <simonepri@outlook.com> (https://simoneprimarosa.com)"
],
"main": "index.js",
"files": [
"lib",
"index.js"
],
"engines": {
"node": ">=8"
},
"scripts": {
"lint": "standard",
"test": "nyc ava -m \"!*benchmark*\"",
"alpine": "docker run -v $(pwd):/var/pidusage pidusage:latest npm test",
"coverage": "codecov",
"bench": "ava -m \"*benchmark*\""
},
"dependencies": {
"safe-buffer": "^5.2.1"
},
"devDependencies": {
"ava": "^3.10.1",
"codecov": "^3.7.0",
"mockdate": "^2.0.5",
"mockery": "^2.1.0",
"nyc": "^15.1.0",
"pify": "^3.0.0",
"standard": "^14.3.4",
"string-to-stream": "^1.1.1",
"through": "^2.3.8",
"time-span": "^2.0.0"
},
"keywords": [
"pid",
"usage",
"ps",
"cpu",
"memory",
"proc"
],
"ava": {
"verbose": true
},
"nyc": {
"reporter": [
"lcovonly",
"text"
]
}
}

23
api.hyungi.net/node_modules/pm2-sysmonit/package.json generated vendored Normal file
View File

@@ -0,0 +1,23 @@
{
"name": "pm2-sysmonit",
"version": "1.2.8",
"description": "PM2.io System Monitoring",
"main": "index.js",
"scripts": {},
"author": "",
"license": "Apache",
"apps": [
{
"name": "pm2-sysmonit",
"script": "./index.js",
"max_memory_restart": "150M"
}
],
"dependencies": {
"async": "^3.2.0",
"debug": "^4.3.1",
"pidusage": "^2.0.21",
"systeminformation": "^5.7",
"tx2": "~1.0.4"
}
}

View File

@@ -0,0 +1,26 @@
class MeanCalc {
constructor(count) {
this.metrics = []
this.count = count
}
inspect() {
return this.val()
}
add(value) {
if (this.metrics.length >= this.count) {
this.metrics.shift()
}
this.metrics.push(value)
}
val() {
if (this.metrics.length == 0) return 0
let sum = this.metrics.reduce((prev, curr) => curr += prev)
return Math.floor((sum / this.metrics.length) * 1000) / 1000
}
}
module.exports = MeanCalc

View File

@@ -0,0 +1,604 @@
const sysinfo = require('systeminformation')
const psList = require('./psList.js')
const async = require('async')
const MeanCalc = require('./MeanCalc.js')
const DEFAULT_CONVERSION = 1024 * 1024
const os = require('os')
const fs = require('fs')
const debug = require('debug')('pm2:sysinfos')
class SystemInfo {
constructor() {
this.infos = {
baseboard: {
model: null,
version: null
},
cpu: {
manufacturer: null,
brand: null,
speedmax: null,
cores: null,
physicalCores: null,
processors: null,
temperature: null,
load: null,
loads: null
},
graphics: {
model: null,
driverVersion: null,
memTotal: null,
memUsed: null,
temperature: null
},
mem: {
total: null,
free: null,
active: null,
usage: null
},
os: {
platform: null,
distro: null,
release: null,
codename: null,
kernel: null,
arch: null,
},
fd: {
opened: null,
max: null
},
storage: {
io: {
read: new MeanCalc(15),
write: new MeanCalc(15)
},
physical_disks: [{
device: null,
type: null,
name: null,
interfaceType: null,
vendor: null
}],
filesystems: [{
}]
},
connections: ['source_ip:source_port-dest_ip:dest_port-proc_name'],
default_interface: null,
network: {},
// Procs
containers: [],
processes: {
cpu_sorted: null,
mem_sorted: null
},
services: {
running: null,
stopped: null
}
}
}
// Cast MeanCalc and other object to real value
// This method retrieve the machine snapshot well formated
report() {
var report = JSON.parse(JSON.stringify(this.infos))
Object.keys(report.network).forEach(iname => {
report.network[iname] = {
ip4: this.infos.network[iname].ip4,
ip6: this.infos.network[iname].ip6,
tx_5: this.infos.network[iname].tx_5.val(),
rx_5: this.infos.network[iname].rx_5.val(),
rx_errors_60: this.infos.network[iname].rx_errors_60.val(),
tx_errors_60: this.infos.network[iname].tx_errors_60.val(),
rx_dropped_60: this.infos.network[iname].rx_dropped_60.val(),
tx_dropped_60: this.infos.network[iname].tx_dropped_60.val()
}
})
report.storage.io.read = this.infos.storage.io.read.val()
report.storage.io.write = this.infos.storage.io.write.val()
return report
}
query(cb) {
if (this.process.connected == true) {
try {
this.process.send('query')
} catch(e) {
return cb(new Error('not ready yet'), null)
}
}
else
return cb(new Error('not ready yet'), null)
var res = (msg) => {
try {
msg = JSON.parse(msg)
}
catch (e) {
}
if (msg.cmd == 'query:res') {
listener.removeListener('message', res)
return cb(null, msg.data)
}
}
var listener = this.process.on('message', res)
}
startCollection() {
this.staticInformations()
var dockerCollection, processCollection, memCollection,
servicesCollection, graphicsCollection
(dockerCollection = () => {
this.dockerSummary(() => {
setTimeout(dockerCollection.bind(this), 5000)
})
})();
(processCollection = () => {
this.processesSummary(() => {
setTimeout(processCollection.bind(this), 5000)
})
})();
(graphicsCollection = () => {
this.graphicsInformations(() => {
setTimeout(graphicsCollection.bind(this), 20000)
})
})();
(servicesCollection = () => {
this.servicesSummary(() => {
setTimeout(servicesCollection.bind(this), 60000)
})
})();
(memCollection = () => {
this.memStats(() => {
setTimeout(memCollection.bind(this), 1000)
})
})();
//this.networkConnectionsWorker()
this.disksStatsWorker()
this.networkStatsWorker()
this.cpuStatsWorker()
this.fdStatsWorker()
// Systeminfo receive command
process.on('message', (cmd) => {
if (cmd == 'query') {
try {
var res = JSON.stringify({
cmd: 'query:res',
data: this.report()
})
process.send(res)
} catch (e) {
console.error('Could not retrieve system informations', e)
}
}
else if (cmd == 'pong') {
clearTimeout(this.ping_timeout)
}
})
}
staticInformations() {
var getCPU = () => {
return sysinfo.cpu()
.then(data => {
this.infos.cpu = {
brand: data.manufacturer,
model: data.brand,
speed: data.speedmax,
cores: data.cores,
physicalCores: data.physicalCores
}
})
}
var getBaseboard = () => {
return sysinfo.system()
.then(data => {
this.infos.baseboard = {
manufacturer: data.manufacturer,
model: data.model,
version: data.version
}
})
}
var getDefaultNetInterface = () => {
return sysinfo.networkInterfaceDefault()
.then(iface => {
this.infos.default_interface = iface
})
}
var getOsInfo = () => {
return sysinfo.osInfo()
.then(data => {
this.infos.os = {
platform: data.platform,
distro: data.distro,
release: data.release,
codename: data.codename,
kernel: data.kernel,
arch: data.arch
}
})
}
var diskLayout = () => {
this.infos.storage.physical_disks = []
return sysinfo.diskLayout()
.then(disks => {
disks.forEach((disk) => {
this.infos.storage.physical_disks.push({
device: disk.device,
type: disk.type,
name: disk.name,
interfaceType: disk.interfaceType,
vendor: disk.vendor
})
})
})
}
getBaseboard()
.then(getCPU)
.then(getOsInfo)
.then(diskLayout)
.then(getDefaultNetInterface)
.catch(e => {
debug(`Error when trying to retrieve static informations`, e)
})
}
dockerSummary(cb = () => {}) {
sysinfo.dockerContainers('all')
.then(containers => {
var non_exited_containers = containers.filter(container => container.state != 'exited')
var new_containers = []
async.forEach(non_exited_containers, (container, next) => {
sysinfo.dockerContainerStats(container.id)
.then(stats => {
var meta = container
stats[0].cpu_percent = (stats[0].cpu_percent).toFixed(1)
stats[0].mem_percent = (stats[0].mem_percent).toFixed(1)
stats[0].netIO.tx = (stats[0].netIO.tx / DEFAULT_CONVERSION).toFixed(1)
stats[0].netIO.rx = (stats[0].netIO.rx / DEFAULT_CONVERSION).toFixed(1)
stats[0].blockIO.w = (stats[0].blockIO.w / DEFAULT_CONVERSION).toFixed(1)
stats[0].blockIO.r = (stats[0].blockIO.r / DEFAULT_CONVERSION).toFixed(1)
meta.stats = Array.isArray(stats) == true ? stats[0] : null
new_containers.push(meta)
next()
})
.catch(e => {
debug(e)
next()
})
}, (err) => {
if (err)
debug(err)
this.infos.containers = new_containers.sort((a, b) => {
var textA = a.name.toUpperCase();
var textB = b.name.toUpperCase();
return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
})
return cb()
})
})
.catch(e => {
debug(e)
return cb()
})
}
servicesSummary() {
sysinfo.services('*')
.then(services => {
this.infos.services.running = services.filter(service => service.running === true)
this.infos.services.stopped = services.filter(service => service.running === false)
})
.catch(e => {
debug(e)
})
}
processesSummary(cb) {
psList()
.then(processes => {
this.infos.processes.cpu_sorted = processes
.filter(a => !(a.cmd.includes('SystemInfo') && a.cmd.includes('PM2')))
.sort((a, b) => b.cpu - a.cpu).slice(0, 5)
this.infos.processes.mem_sorted = processes
.filter(a => !(a.cmd.includes('SystemInfo') && a.cmd.includes('PM2')))
.sort((a, b) => b.memory - a.memory).slice(0, 5)
return cb()
})
.catch(e => {
console.error(`Error when retrieving process list`, e)
return cb()
})
}
graphicsInformations(cb) {
sysinfo.graphics()
.then(data => {
if (!data) return cb()
let cg1 = data.controllers[0]
if (!cg1) return cb()
this.infos.graphics = {
model: cg1.model,
driverVersion: cg1.driverVersion,
memTotal: cg1.memoryTotal,
memUsed: cg1.memoryUsed,
temperature: cg1.temperatureGpu
}
return cb()
})
.catch(e => {
console.error(`Error while retrieving graphics informations`)
console.error(e)
return cb()
})
}
cpuStatsWorker() {
var cpuTempCollection, cpuLoad
(cpuTempCollection = () => {
sysinfo.cpuTemperature()
.then(data => {
this.infos.cpu.temperature = (data.main).toFixed(1)
setTimeout(cpuTempCollection.bind(this), 5000)
})
.catch(e => {
setTimeout(cpuTempCollection.bind(this), 5000)
})
})();
(cpuLoad = () => {
sysinfo.currentLoad()
.then(data => {
this.infos.cpu.load = data.currentLoad.toFixed(1)
this.infos.cpu.loads = data.cpus.map(cpu => Math.floor(cpu.load)).join('|')
setTimeout(cpuLoad.bind(this), 1000)
})
.catch(e => {
setTimeout(cpuLoad.bind(this), 1000)
})
})();
}
memStats(cb) {
sysinfo.mem()
.then(data => {
this.infos.mem.total = (data.total / DEFAULT_CONVERSION / 1024).toFixed(2)
this.infos.mem.free = (data.free / DEFAULT_CONVERSION / 1024).toFixed(2)
this.infos.mem.active = (data.active / DEFAULT_CONVERSION / 1024).toFixed(2)
this.infos.mem.available = (data.available / DEFAULT_CONVERSION / 1024).toFixed(2)
this.infos.mem.usage = ((data.active / data.total) * 100).toFixed(1)
return cb()
})
.catch(e => {
console.error(`Error while retrieving memory info`)
console.error(e)
return cb()
})
}
networkConnectionsWorker() {
var retrieveConn
(retrieveConn = () => {
sysinfo.networkConnections()
.then(conns => {
this.infos.connections = conns
.filter(conn => conn.localport != '443' && conn.peerport != '443')
.map(conn => `${conn.localaddress}:${conn.localport}-${conn.peeraddress}:${conn.peerport}-${conn.proc ? conn.proc : 'unknown'}`)
setTimeout(retrieveConn.bind(this), 10 * 1000)
})
.catch(e => {
console.error(`Error while retrieving filesystems info`)
console.error(e)
setTimeout(retrieveConn.bind(this), 10 * 1000)
})
})();
}
disksStatsWorker() {
var rx = 0
var wx = 0
var started = false
var fsSizeCollection, ioCollection
(fsSizeCollection = () => {
sysinfo.fsSize()
.then(fss => {
// Get only partition of > 800 and not /boot
var fse = fss.filter(fs => ((fs.size / (1024 * 1024)) > 800) && fs.mount != '/boot' && !fs.mount.includes('efi'))
this.infos.storage.filesystems = fse
setTimeout(fsSizeCollection.bind(this), 30 * 1000)
})
.catch(e => {
console.error(`Error while retrieving filesystem infos (FSSIZE)`, e)
setTimeout(fsSizeCollection.bind(this), 10 * 1000)
})
})();
(ioCollection = () => {
sysinfo.fsStats()
.then(fs_stats => {
var new_rx = fs_stats.rx
var new_wx = fs_stats.wx
var read = ((new_rx - rx) / DEFAULT_CONVERSION).toFixed(3)
var write = ((new_wx - wx) / DEFAULT_CONVERSION).toFixed(3)
if (started == true) {
this.infos.storage.io.read.add(parseFloat(read))
this.infos.storage.io.write.add(parseFloat(write))
}
rx = new_rx
wx = new_wx
started = true
setTimeout(ioCollection.bind(this), 1000)
})
.catch(e => {
console.error(`Error while getting network statistics`, e)
setTimeout(ioCollection.bind(this), 1000)
})
})();
}
fdStatsWorker() {
var getFDOpened = () => {
sysinfo.fsOpenFiles()
.then(open_files => {
this.infos.fd.opened = open_files.allocated
this.infos.fd.max = open_files.max
})
.catch(e => {
console.error(`Could not retrieve fds`)
console.error(e)
})
}
setInterval(() => {
getFDOpened()
}, 5000)
getFDOpened()
}
networkStatsWorker() {
var latencyCollection, networkStatsCollection
var self = this
function grabStats(inter) {
let started = false
let rx = 0
let tx = 0
let rx_e = 0
let tx_e = 0
let rx_d = 0
let tx_d = 0
let net_interface = inter.iface;
function networkStatsCollection(net_interface) {
self.infos.network[net_interface] = {
ip4: inter.ip4,
ip6: inter.ip6,
latency: new MeanCalc(5),
tx_5: new MeanCalc(5),
rx_5: new MeanCalc(5),
rx_errors_60: new MeanCalc(60),
tx_errors_60: new MeanCalc(60),
tx_dropped_60: new MeanCalc(60),
rx_dropped_60: new MeanCalc(60)
}
sysinfo.networkStats(net_interface)
.then((net) => {
let new_rx = (net[0].rx_bytes - rx) / DEFAULT_CONVERSION
let new_tx = (net[0].tx_bytes - tx) / DEFAULT_CONVERSION
rx = net[0].rx_bytes
tx = net[0].tx_bytes
let new_rx_e = (net[0].rx_errors - rx_e) / DEFAULT_CONVERSION
let new_tx_e = (net[0].tx_errors - tx_e) / DEFAULT_CONVERSION
rx_e = net[0].rx_errors
tx_e = net[0].tx_errors
let new_rx_d = (net[0].rx_dropped - rx_d) / DEFAULT_CONVERSION
let new_tx_d = (net[0].tx_dropped - tx_d) / DEFAULT_CONVERSION
rx_d = net[0].rx_dropped
tx_d = net[0].tx_dropped
if (started == true) {
self.infos.network[net_interface].rx_5.add(new_rx)
self.infos.network[net_interface].tx_5.add(new_tx)
self.infos.network[net_interface].rx_errors_60.add(new_rx_e)
self.infos.network[net_interface].tx_errors_60.add(new_tx_e)
self.infos.network[net_interface].rx_dropped_60.add(new_rx_d)
self.infos.network[net_interface].tx_dropped_60.add(new_tx_d)
}
started = true
setTimeout(() => {
networkStatsCollection(net_interface)
}, 1000)
})
.catch(e => {
console.error(`Error on retrieving network stats`, e)
setTimeout(() => {
networkStatsCollection(net_interface)
}, 1000)
})
}
networkStatsCollection(net_interface)
}
sysinfo.networkInterfaces()
.then(interfaces => {
interfaces.forEach(inter => {
if (inter.ip4 == '127.0.0.1') return
grabStats(inter)
})
})
.catch(e => {
console.error(`Cannot retrieve interfaces`)
console.error(e)
})
// (latencyCollection = () => {
// sysinfo.inetLatency()
// .then(latency => {
// this.infos.network.latency.add(latency)
// setTimeout(latencyCollection.bind(this), 2000)
// })
// .catch(e => {
// debug(e)
// setTimeout(latencyCollection.bind(this), 2000)
// })
// })()
}
}
module.exports = SystemInfo
if (require.main === module) {
var sys = new SystemInfo()
sys.startCollection()
setInterval(() => {
console.log(JSON.stringify(sys.report(), null, 2))
}, 5000)
}

Binary file not shown.

83
api.hyungi.net/node_modules/pm2-sysmonit/src/pm2.js generated vendored Normal file
View File

@@ -0,0 +1,83 @@
const fs = require('fs')
const path = require('path')
const pidusage = require('pidusage')
class PM2Monitoring {
constructor() {
this.pm2_monitoring = { cpu: 0, mem: 0 }
this.pm2_agent_monitoring = { cpu: 0, mem: 0 }
}
startCollection() {
setInterval(() => {
this.monitorPM2Agent()
this.monitorPM2()
}, 900)
}
getDefaultPM2Home() {
var PM2_ROOT_PATH;
if (process.env.PM2_HOME)
PM2_ROOT_PATH = process.env.PM2_HOME;
else if (process.env.HOME && !process.env.HOMEPATH)
PM2_ROOT_PATH = path.resolve(process.env.HOME, '.pm2');
else if (process.env.HOME || process.env.HOMEPATH)
PM2_ROOT_PATH = path.resolve(process.env.HOMEDRIVE, process.env.HOME || process.env.HOMEPATH, '.pm2');
else {
console.error('[PM2][Initialization] Environment variable HOME (Linux) or HOMEPATH (Windows) are not set!');
console.error('[PM2][Initialization] Defaulting to /etc/.pm2');
PM2_ROOT_PATH = path.resolve('/etc', '.pm2');
}
return PM2_ROOT_PATH;
}
report() {
return {
pm2: this.pm2_monitoring,
agent: this.pm2_agent_monitoring
}
}
monitorPM2() {
let pm2_pid_file = path.join(this.getDefaultPM2Home(), 'pm2.pid')
fs.readFile(pm2_pid_file, (err, pm2_pid) => {
if (err) return console.error(`Could not read ${pm2_pid_file}`)
if (!pm2_pid) return console.error(`PID is null`)
pm2_pid = parseInt(pm2_pid)
pidusage(pm2_pid, (err, stats) => {
if (err) return console.error(err)
this.pm2_monitoring = {
cpu: stats.cpu.toFixed(1),
mem: (stats.memory / 1024 / 1024).toFixed(1)
}
})
})
}
monitorPM2Agent() {
let pm2_agent_pid_file = path.join(this.getDefaultPM2Home(), 'agent.pid')
fs.readFile(pm2_agent_pid_file, (err, pm2_agent_pid) => {
if (err) return
if (!pm2_agent_pid) return
pidusage(pm2_agent_pid, (err, stats) => {
if (err) return
this.pm2_agent_monitoring = {
cpu: stats.cpu.toFixed(1),
mem: (stats.memory / 1024 / 1024).toFixed(1)
}
})
})
}
}
module.exports = PM2Monitoring

63
api.hyungi.net/node_modules/pm2-sysmonit/src/psList.js generated vendored Normal file
View File

@@ -0,0 +1,63 @@
'use strict';
const util = require('util');
const path = require('path');
const childProcess = require('child_process');
const TEN_MEGABYTES = 1000 * 1000 * 10;
const execFile = util.promisify(childProcess.execFile);
const windows = async () => {
// Source: https://github.com/MarkTiedemann/fastlist
const bin = path.join(__dirname, 'fastlist.exe');
const {stdout} = await execFile(bin, {maxBuffer: TEN_MEGABYTES});
return stdout
.trim()
.split('\r\n')
.map(line => line.split('\t'))
.map(([name, pid, ppid]) => ({
name,
pid: Number.parseInt(pid, 10),
ppid: Number.parseInt(ppid, 10)
}));
};
const main = async (options = {}) => {
const flags = (options.all === false ? '' : 'a') + 'wwxo';
const ret = {};
await Promise.all(['comm', 'args', 'ppid', 'uid', '%cpu', '%mem'].map(async cmd => {
const {stdout} = await execFile('ps', [flags, `pid,${cmd}`], {maxBuffer: TEN_MEGABYTES});
for (let line of stdout.trim().split('\n').slice(1)) {
line = line.trim();
const [pid] = line.split(' ', 1);
const val = line.slice(pid.length + 1).trim();
if (ret[pid] === undefined) {
ret[pid] = {};
}
ret[pid][cmd] = val;
}
}));
// Filter out inconsistencies as there might be race
// issues due to differences in `ps` between the spawns
return Object.entries(ret)
.filter(([, value]) => value.comm && value.args && value.ppid && value.uid && value['%cpu'] && value['%mem'])
.map(([key, value]) => ({
pid: Number.parseInt(key, 10),
name: path.basename(value.comm),
cmd: value.args,
ppid: Number.parseInt(value.ppid, 10),
uid: Number.parseInt(value.uid, 10),
cpu: Number.parseFloat(value['%cpu']),
memory: Number.parseFloat(value['%mem'])
}));
};
module.exports = process.platform === 'win32' ? windows : main;
// TODO: remove this in the next major version
module.exports.default = module.exports;