-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuptime.js
130 lines (116 loc) · 2.89 KB
/
uptime.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
var mongoose = require('mongoose'),
Current = mongoose.model('Current'),
Session = mongoose.model('Session');
/*
* Creates a new users array
*/
function nextUsers (oldInfo, newInfo) {
var users = [];
function add (user) {
users.push({
'name': user.USER,
'tty': user.TTY,
'from': user.FROM,
'loginTime': new Date()
});
}
if (!oldInfo) {
// Everyone is new
newInfo.users.forEach(function (user) {
if (!users.some(function (u) { return u.name === user.USER; })) {
add(user);
}
});
} else {
// Retain old users that are still here
oldInfo.users.forEach(function (user) {
if (newInfo.users.some(function (u) { return u.USER === user.name; })) {
users.push(user);
}
});
// Introduce a single copy of any next people
newInfo.users.forEach(function (user) {
if (!users.some(function (u) { return u.name === user.USER; })) {
add(user);
}
});
}
return users;
}
/*
* Store sessions for people who left
*/
function saveSessions (oldInfo, newInfo) {
if (!oldInfo) {
// First time to check this machine
return;
}
oldInfo.users.forEach(function (user) {
if (!newInfo.users.some(function (u) { return u.USER === user.name; })) {
var session = new Session({
'name': user.name,
'hostname': oldInfo.hostname,
'from': user.from,
'loginTime': user.loginTime,
'logoutTime': new Date(),
'physical': user.tty === ':0'
});
session.save(function(err) {
if (err) {
console.log(err);
return false;
}
});
}
});
}
/*
* Replaces the current collection's info on a server
* and stores session data for people who left
*/
function update (server, w, callback) {
console.log('Updating ' + server);
Current.findOne({ 'hostname': server }, function(err, oldInfo) {
if (err) {
console.log(err);
return false;
}
var nextUserInfo = nextUsers(oldInfo, w);
// Info to be stored in the current collection
var nextInfo = {
'hostname': server,
'userCount': nextUserInfo.length,
'physical': w.users.some(function (user) { return user.TTY === ':0'; }),
'loadAverage': w.loadAverage,
'updated': new Date(),
'users': nextUserInfo
};
if (!oldInfo) {
// Insert if there wasn't already a record
var current = new Current(nextInfo);
current.save(function(err) {
if (err) {
console.log(err);
return false;
}
callback();
});
} else {
saveSessions(oldInfo, w);
Current.update(
{ 'hostname': server },
{ $set: nextInfo },
function(err) {
if (err) {
console.log(err);
return false;
}
callback();
}
);
}
});
}
module.exports = {
update: update
};