1 Commits

Author SHA1 Message Date
97bda2c8a8 working python 2023-04-07 01:40:42 -07:00
54 changed files with 598 additions and 2520 deletions

2
.gitignore vendored
View File

@@ -9,5 +9,3 @@ extension/RangerMetrics.h
extension/RangerMetrics_x64.h
\@RangerMetrics/settings.json
*.log

View File

@@ -10,69 +10,15 @@ class CfgPatches {
};
class CfgFunctions {
class RangerMetrics_event {
class functions {
file = "\RangerMetrics\functions\capture\EHOnly";
class ace_unconscious {};
class EntityKilled {};
class Explosion {};
class FiredMan {};
class HandleChatMessage {};
class MarkerCreated {};
class MarkerDeleted {};
class MarkerUpdated {};
class milsim_serverEfficiency {};
};
}
class RangerMetrics_cDefinitions {
class functions {
file = "\RangerMetrics\functions\captureDefinitions";
class server_poll {};
class server_missionEH {};
class client_poll {};
// class clientEvent {};
class server_CBA {};
class unit_handlers {};
};
};
class RangerMetrics_capture {
// these names represent measurement names send to InfluxDB - snake case
class functions {
file = "\RangerMetrics\functions\capture";
class entity_count {};
class mission_config_file {};
class player_identity {};
class player_performance {};
class player_status {};
class running_mission {};
class running_scripts {};
class server_performance {};
class server_time {};
class unit_inventory {};
class unit_state {};
class view_distance {};
class weather {};
};
};
class RangerMetrics {
class core {
file = "\RangerMetrics\functions\core";
class postInit { postInit = 1; };
class captureLoop {};
class log {};
class Common {
file = "\RangerMetrics\functions";
class postInit { postInit = 1;};
class gather {};
class queue {};
class send {};
class callbackHandler {};
class sendClientPoll {};
class startServerPoll {};
class classHandlers {};
};
class helpers {
file = "\RangerMetrics\functions\helpers";
class toLineProtocol {};
class encodeJSON {};
class stringReplace {};
class unixTimestamp {};
class checkResults {};
class log {};
};
};
};

View File

@@ -1,43 +0,0 @@
if (!RangerMetrics_run) exitWith {};
params ["_killed", "_killer", "_instigator"];
if (!isPlayer _killed) exitWith {}; // only track player deaths
// check in case ACE is active and lastDamageSource has been broadcast via addLocalSoldierEH
_instigator = _unit getVariable [
"ace_medical_lastDamageSource",
_instigator
];
if (isNull _instigator) then { _instigator = UAVControl vehicle _killer select 0 }; // UAV/UGV player operated road kill
if (isNull _instigator) then { _instigator = _killer }; // player driven vehicle road kill
if (isNull _instigator) then { _instigator = _killed };
// hint format ["Killed By %1", name _instigator];
if (!isPlayer _killed && !isPlayer _instigator) exitWith {}; // only track player kills
private _tags = [];
private _fields = [];
if (getPlayerUID _instigator != "") then {
_tags pushBack ["string", "killerPlayerUID", getPlayerUID _instigator];
};
if (name _instigator != "") then {
_fields pushBack ["string", "killerName", name _instigator];
};
if (getPlayerUID _killed != "") then {
_tags pushBack ["string", "killedPlayerUID", getPlayerUID _killed];
};
if (name _killed != "") then {
_fields pushBack ["string", "killedName", name _killed];
};
[
"server_events",
"EntityKilled",
_tags,
_fields,
["server"]
] call RangerMetrics_fnc_queue;

View File

@@ -1,33 +0,0 @@
params ["_vehicle", "_damage", "_source"];
if (isNull _vehicle) exitWith {};
private _sourceClass = "";
private _sourceDisplayName = "";
private _sourcePlayerUID = "";
if !(isNull _source) then {
private _sourceClass = typeOf _source;
private _sourceDisplayName = [configOf _source] call BIS_fnc_displayName;
if (isPlayer _source) then {
private _sourcePlayerId = getPlayerId _source;
private _sourceUserInfo = getUserInfo _sourcePlayerId;
private _sourcePlayerUID = _sourceUserInfo select 2;
} else {
private _sourcePlayerUID = "";
};
};
private _unitPlayerId = getPlayerId _vehicle;
private _userInfo = getUserInfo _unitPlayerId;
private _unitPlayerUID = _userInfo select 2;
[
"player_events",
"Explosion",
[["string", "playerUID", _unitPlayerUID]],
[
["string", "sourceClass", _sourceClass],
["string", "sourceDisplayName", _sourceDisplayName],
["string", "sourcePlayerUID", _sourcePlayerUID],
["float", "damage", _damage]
],
["server"]
] call RangerMetrics_fnc_queue;

View File

@@ -1,27 +0,0 @@
params [
["_unit", objNull],
"_weapon", "_muzzle", "_mode", "_ammo", "_magazine", "_projectile", "_vehicle"
];
if (isNull _unit) exitWith {};
private _unitPlayerId = getPlayerId _unit;
private _userInfo = getUserInfo _unitPlayerId;
[
"player_events",
"FiredMan",
[
["string", "playerUID", _userInfo select 2]
],
[
["string", "weapon", _weapon],
["string", "muzzle", _muzzle],
["string", "mode", _mode],
["string", "ammo", _ammo],
["string", "magazine", _magazine],
// ["object", "projectile", _projectile],
["string", "vehicle", [configOf _vehicle] call displayName],
["string", "vehicleClass", typeOf _vehicle]
],
["server"]
] call RangerMetrics_fnc_queue;

View File

@@ -1,40 +0,0 @@
if (!RangerMetrics_run) exitWith {};
params ["_channel", "_owner", "_from", "_text", "_person", "_name", "_strID", "_forcedDisplay", "_isPlayerMessage", "_sentenceType", "_chatMessageType"];
// if (!_isPlayerMessage) exitWith {};
private _fields = [
["int", "channel", _channel],
["int", "owner", _owner],
["string", "from", _from],
["string", "text", _text],
// ["object", "person", _person],
["string", "name", _name],
["string", "strID", _strID],
["bool", "forcedDisplay", _forcedDisplay],
["bool", "isPlayerMessage", _isPlayerMessage],
["int", "sentenceType", _sentenceType],
["int", "chatMessageType", _chatMessageType]
];
// we need special processing to ensure the object is valid and we have a playerUid. Line protocol doesn't support empty string
private "_playerUID";
if (parseNumber _strID > 1) then {
_playerUID = (getUserInfo _strID)#2;
} else {
_playerUID = "";
};
if (_playerUID isNotEqualTo "") then {
_fields pushBack ["string", "playerUID", _playerUid];
};
[
"server_events",
"HandleChatMessage",
nil,
_fields,
["server"]
] call RangerMetrics_fnc_queue;

View File

@@ -1,30 +0,0 @@
if (!RangerMetrics_run) exitWith {};
params ["_marker", "_channelNumber", "_owner", "_local"];
// Log marker
if (_marker isEqualTo "") exitWith {};
if (_channelNumber isEqualTo "") exitWith {};
if (_owner isEqualTo "") exitWith {};
// Get marker
private _markerData = _marker call BIS_fnc_markerToString;
if (_markerData isEqualTo "") exitWith {};
// Get owner playerUID
private _ownerUID = getPlayerUID _owner;
if (_ownerUID isEqualTo "") exitWith {};
[
"server_events",
"MarkerCreated",
[
["string", "actorPlayerUID", _ownerUID]
],
[
["string", "marker", _markerData],
["number", "channelNumber", _channelNumber],
["string", "owner", _ownerUID]
],
["server"]
] call RangerMetrics_fnc_queue;

View File

@@ -1,31 +0,0 @@
if (!RangerMetrics_run) exitWith {};
params ["_marker", "_channelNumber", "_owner", "_local"];
// Log marker
if (_marker isEqualTo "") exitWith {};
if (_channelNumber isEqualTo "") exitWith {};
if (_owner isEqualTo "") exitWith {};
// Get marker
private _markerData = _marker call BIS_fnc_markerToString;
// Get owner playerUID
private _ownerUID = getPlayerUID _owner;
if (_ownerUID isEqualTo "") then {
_ownerUID = "-1";
};
[
"server_events",
"MarkerDeleted",
[
["string", "actorPlayerUID", _ownerUID]
],
[
["string", "marker", _markerData],
["number", "channelNumber", _channelNumber],
["string", "owner", _ownerUID]
],
["server"]
] call RangerMetrics_fnc_queue;

View File

@@ -1,20 +0,0 @@
if (!RangerMetrics_run) exitWith {};
params ["_marker", "_local"];
// Log marker
if (_marker isEqualTo "") exitWith {};
// Get marker
private _markerData = _marker call BIS_fnc_markerToString;
[
"server_events",
"MarkerUpdated",
nil,
[
["string", "marker", _markerData]
],
["server"]
] call RangerMetrics_fnc_queue;

View File

@@ -1,22 +0,0 @@
if (!RangerMetrics_run) exitWith {};
params [["_unit", objNull], "_unconscious"];
if (isNull _unit) exitWith {};
if (!isPlayer _unit) exitWith {};
// Get owner playerUID
private _unitUID = getPlayerUID _unitUID;
if (_unitUID isEqualTo "") exitWith {false};
[
"player_state",
"player_health",
[
["string", "playerUID", _unitUID]
],
[
["float", "health", 1 - (damage _unit)],
["bool", "state", _unconscious]
]
] call RangerMetrics_fnc_queue;
true;

View File

@@ -1,15 +0,0 @@
params ["_fields", []];
// Example:
// [
// ["float", "milsim_raw_cps", "3207.98"],
// ["float", "milsim_cps", "1"]
// ]
[
"server_state",
"server_efficiency",
nil,
_fields,
["server"]
] call RangerMetrics_fnc_queue;

View File

@@ -1,100 +0,0 @@
if (!RangerMetrics_run) exitWith {};
private _allUnits = allUnits;
private _allDeadMen = allDeadMen;
private _allGroups = allGroups;
private _vehicles = vehicles;
private _allPlayers = call BIS_fnc_listPlayers;
{
private _thisSide = _x;
private _thisSideStr = _thisSide call BIS_fnc_sideNameUnlocalized;
// Number of remote units
["server_state", "entities_remote", [
["string", "side", _thisSideStr]
], [
["int", "units_alive", {
side _x isEqualTo _thisSide &&
not (local _x)
} count _allUnits],
["int", "units_dead", {
side _x isEqualTo _thisSide &&
not (local _x)
} count _allDeadMen],
["int", "groups_total", {
side _x isEqualTo _thisSide &&
not (local _x)
} count _allGroups],
["int", "vehicles_total", {
side _x isEqualTo _thisSide &&
not (local _x) &&
!(_x isKindOf "WeaponHolderSimulated")
} count _vehicles],
["int", "vehicles_weaponholder", {
side _x isEqualTo _thisSide &&
not (local _x) &&
(_x isKindOf "WeaponHolderSimulated")
} count _vehicles]
]] call RangerMetrics_fnc_queue;
// Number of local units
["server_state", "entities_local", [
["string", "side", _thisSideStr]
], [
["int", "units_alive", {
side _x isEqualTo _thisSide &&
local _x
} count _allUnits],
["int", "units_dead", {
side _x isEqualTo _thisSide &&
local _x
} count _allDeadMen],
["int", "groups_total", {
side _x isEqualTo _thisSide &&
local _x
} count _allGroups],
["int", "vehicles_total", {
side _x isEqualTo _thisSide &&
local _x &&
!(_x isKindOf "WeaponHolderSimulated")
} count _vehicles],
["int", "vehicles_weaponholder", {
side _x isEqualTo _thisSide &&
local _x &&
(_x isKindOf "WeaponHolderSimulated")
} count _vehicles]
]] call RangerMetrics_fnc_queue;
// Number of global units - only track on server
if (isServer) then {
["server_state", "entities_global", [
["string", "side", _thisSideStr]
], [
["int", "units_alive", {
side _x isEqualTo _thisSide
} count _allUnits],
["int", "units_dead", {
side _x isEqualTo _thisSide
} count _allDeadMen],
["int", "groups_total", {
side _x isEqualTo _thisSide
} count _allGroups],
["int", "vehicles_total", {
side _x isEqualTo _thisSide &&
!(_x isKindOf "WeaponHolderSimulated")
} count _vehicles],
["int", "vehicles_weaponholder", {
side _x isEqualTo _thisSide &&
(_x isKindOf "WeaponHolderSimulated")
} count _vehicles],
["int", "players_alive", {
side _x isEqualTo _thisSide &&
alive _x
} count _allPlayers],
["int", "players_dead", {
side _x isEqualTo _thisSide &&
!alive _x
} count _allPlayers]
]] call RangerMetrics_fnc_queue;
};
} forEach [east, west, independent, civilian];

View File

@@ -1,82 +0,0 @@
if (!RangerMetrics_run) exitWith {};
params ["_playerID", "_ownerId", "_playerUID", "_profileName", "_displayName", "_steamName", "_clientState", "_isHC", "_adminState", "_networkInfo", "_unit", ["_jip", false]];
// _networkInfo params ["_avgPing", "_avgBandwidth", "_desync"];
private _fields = [
["string", "playerID", _playerID],
["string", "ownerId", _ownerId],
["string", "playerUID", _playerUID],
["string", "profileName", _profileName],
["string", "displayName", _displayName],
["string", "steamName", _steamName],
["bool", "isHC", _isHC],
["bool", "isJip", _jip]
];
try {
// Get Squad Info of Player
(squadParams _unit) params [
"_squadInfo",
"_unitInfo",
"_squadId",
"_a3unitsId"
];
// For each section, we'll define the format and save to fields
_squadInfoDataFormat = [
"squadNick",
"squadName",
"squadEmail",
"squadWeb",
"squadLogo",
"squadTitle"
];
{
_fields pushBack [
"string",
_squadInfoDataFormat select _forEachIndex,
_squadInfo select _forEachIndex
];
} forEach _squadInfoDataFormat;
_unitInfoDataFormat =[
"unitUid",
"unitName",
"unitFullName",
"unitICQ",
"unitRemark"
];
{
_fields pushBack [
"string",
_unitInfoDataFormat select _forEachIndex,
_unitInfo select _forEachIndex
];
} forEach _unitInfoDataFormat;
} catch {
// If we fail to get squad info, we'll just skip it
[format["Failed to get squad info for %1", _playerUID]] call RangerMetrics_fnc_log;
};
// Role description
private _roleDescription = roleDescription _unit;
if (_roleDescription isNotEqualTo "") then {
_fields pushBack ["string", "roleDescription", _roleDescription];
};
[
"player_state",
"player_identity",
[
["string", "playerUID", _playerUID]
],
_fields,
["server"]
] call RangerMetrics_fnc_queue;

View File

@@ -1,19 +0,0 @@
if (!RangerMetrics_run) exitWith {};
{
_x params ["_playerID", "_ownerId", "_playerUID", "_profileName", "_displayName", "_steamName", "_clientState", "_isHC", "_adminState", "_networkInfo", "_unit"];
_networkInfo params ["_avgPing", "_avgBandwidth", "_desync"];
[
"player_state",
"player_performance",
[["string", "playerUID", _playerUID]],
[
["float", "avgPing", _avgPing],
["float", "avgBandwidth", _avgBandwidth],
["float", "desync", _desync]
],
["server"]
] call RangerMetrics_fnc_queue;
} forEach (allUsers apply {getUserInfo _x});

View File

@@ -1,14 +0,0 @@
if (!RangerMetrics_run) exitWith {};
params ["_playerID", "_ownerId", "_playerUID", "_profileName", "_displayName", "_steamName", "_clientState", "_isHC", "_adminState", "_networkInfo", "_unit"];
// _networkInfo params ["_avgPing", "_avgBandwidth", "_desync"];
["player_state", "player_status",
[["string", "playerUID", _playerUID]],
[
["int", "clientStateNumber", _clientState],
["int", "adminState", _adminState],
["string", "profileName", _profileName]
],
["server"]
] call RangerMetrics_fnc_queue;

View File

@@ -1,19 +0,0 @@
if (!RangerMetrics_run) exitWith {};
// Mission name
[
"server_state", // bucket to store the data
"running_mission", // measurement classifier inside of bucket
nil, // tags
[ // fields
[
"string",
"onLoadName",
getMissionConfigValue ["onLoadName", ""]
],
["string","briefingName", briefingName],
["string","missionName", missionName],
["string","missionNameSource", missionNameSource]
],
["profile", "server", "world"] // context
] call RangerMetrics_fnc_queue;

View File

@@ -1,9 +0,0 @@
if (!RangerMetrics_run) exitWith {};
["server_state", "running_scripts", nil, [
["int", "spawn", diag_activeScripts select 0],
["int", "execVM", diag_activeScripts select 1],
["int", "exec", diag_activeScripts select 2],
["int", "execFSM", diag_activeScripts select 3],
["int", "pfh", if (RangerMetrics_cbaPresent) then {count CBA_common_perFrameHandlerArray} else {0}]
]] call RangerMetrics_fnc_queue;

View File

@@ -1,6 +0,0 @@
if (!RangerMetrics_run) exitWith {};
["server_state", "server_performance", nil, [
["float", "fps_avg", diag_fps toFixed 2],
["float", "fps_min", diag_fpsMin toFixed 2]
]] call RangerMetrics_fnc_queue;

View File

@@ -1,8 +0,0 @@
if (!RangerMetrics_run) exitWith {};
["server_state", "server_time", nil, [
["float", "diag_tickTime", diag_tickTime toFixed 2],
["float", "serverTime", time toFixed 2],
["float", "timeMultiplier", timeMultiplier toFixed 2],
["float", "accTime", accTime toFixed 2]
]] call RangerMetrics_fnc_queue;

View File

@@ -1,200 +0,0 @@
if (!RangerMetrics_run) exitWith {};
params [
["_unit", objNull, [objNull]]
];
if (isNull _unit) exitWith {false};
if (!isPlayer _unit) exitWith {};
// do not check more than once every 15 seconds
_checkDelay = 15;
_lastCheck = _unit getVariable [
"RangerMetrics_lastInventoryCheck",
0
];
if (
(_lastCheck + _checkDelay) > diag_tickTime
) exitWith {false};
_unit setVariable ["RangerMetrics_lastInventoryCheck", diag_tickTime];
private _lastLoadout = _unit getVariable "RangerMetrics_unitLoadout";
if (isNil "_lastLoadout") then {
_lastLoadout = [];
};
private _uniqueUnitItems = uniqueUnitItems [_unit, 2, 2, 2, 2, true];
// if (_lastLoadout isEqualTo _uniqueUnitItems) exitWith {false};
// _unit setVariable ["RangerMetrics_unitLoadout", _uniqueUnitItems];
private _uniqueUnitItems = _uniqueUnitItems toArray false;
_classItemCounts = [];
{
_x params ["_item", "_count"];
if (_item isEqualTo "") exitWith {};
_classItemCounts pushBack ["int", _item, _count];
} forEach _uniqueUnitItems;
_playerUID = getPlayerUID _unit;
_unitId = _unit getVariable ["RangerMetrics_Id", -1];
if (_unitId isEqualTo -1) exitWith {false};
// this section uses uniqueUnitItems to get a list of all items and their counts
[
"player_state",
"unit_loadout",
[
["string", "playerUID", _playerUID],
["string", "format", "className"]
],
_classItemCounts,
["server"]
] call RangerMetrics_fnc_queue;
// prep displayName by fetching from configs
_displayItemCounts = [];
{
_x params ["_valueType", "_item", "_count"];
// from CBA_fnc_getItemConfig, author: commy2
private "_itemConfig";
{
private _config = configFile >> _x >> _item;
if (isClass _config) exitWith {
_itemConfig = _config;
};
} forEach ["CfgWeapons", "CfgMagazines", "CfgGlasses"];
if (isNil "_itemConfig") then {
private _config = configFile >> "CfgVehicles" >> _item;
if (getNumber (_config >> "isBackpack") isEqualTo 1) then {
_itemConfig = _config;
};
};
_itemDisplayName = getText(_itemConfig >> "displayName");
_displayItemCounts pushBack ["int", _itemDisplayName, _count];
} forEach _classItemCounts;
[
"player_state",
"unit_loadout",
[
["string", "playerUID", _playerUID],
["string", "unitId", str _unitId],
["string", "format", "displayName"]
],
_displayItemCounts,
["server"]
] call RangerMetrics_fnc_queue;
true;
// get current loadout
// ! this section breaks everything down individually, see above for uniqueUnitItems implementation
// private _primaryWeapon = primaryWeapon _unit;
// (primaryWeaponItems _unit) params [
// "_primaryWeaponSilencer",
// "_primaryWeaponLaser",
// "_primaryWeaponOptics",
// "_primaryWeaponBipod"
// ];
// _primaryWeapon = [
// ["string", "weapon", _primaryWeapon],
// ["string", "silencer", _primaryWeaponSilencer],
// ["string", "laser", _primaryWeaponLaser],
// ["string", "optic", _primaryWeaponOptics],
// ["string", "bipod", _primaryWeaponBipod]
// ];
// private _secondaryWeapon = secondaryWeapon _unit;
// (secondaryWeaponItems _unit) params [
// "_secondaryWeaponSilencer",
// "_secondaryWeaponLaser",
// "_secondaryWeaponOptics",
// "_secondaryWeaponBipod"
// ];
// _secondaryWeapon = [
// ["string", "weapon", _secondaryWeapon],
// ["string", "silencer", _secondaryWeaponSilencer],
// ["string", "laser", _secondaryWeaponLaser],
// ["string", "optic", _secondaryWeaponOptics],
// ["string", "bipod", _secondaryWeaponBipod]
// ];
// private _handgun = handgunWeapon _unit;
// (handgunItems _unit) params [
// "_handgunSilencer",
// "_handgunLaser",
// "_handgunOptics",
// "_handgunBipod"
// ];
// _handgun = [
// ["string", "weapon", _handgun],
// ["string", "silencer", _handgunSilencer],
// ["string", "laser", _handgunLaser],
// ["string", "optic", _handgunOptics],
// ["string", "bipod", _handgunBipod]
// ];
// private _magazinesFields = [];
// private _magazines = (magazines _unit) call BIS_fnc_consolidateArray;
// _magazines = _magazines apply {
// _x params ["_magazine", "_count"];
// _magazinesFields pushBack ["int", _magazine, _count];
// _magazinesFields pushBack ["int", getText(configFile >> "CfgMagazines" >> _magazine >> "displayName"), _count];
// };
// private _itemsFields = [];
// private _items = (items _unit) call BIS_fnc_consolidateArray;
// _items = _items apply {
// _x params ["_item", "_count"];
// _itemsFields pushBack ["int", _item, _count];
// _itemsFields pushBack ["int", getText(configFile >> "CfgWeapons" >> _item >> "displayName"), _count];
// };
// private _slotItems = [
// ["string", "goggles", goggles _unit],
// ["string", "gogglesClass", getText(configFile >> "CfgWeapons" >> (goggles _unit) >> "displayName")],
// ["string", "headgear", headgear _unit],
// ["string", "headgearClass", getText(configFile >> "CfgWeapons" >> (headgear _unit) >> "displayName")],
// ["string", "binocular", binocular _unit],
// ["string", "binocularClass", getText(configFile >> "CfgWeapons" >> (binocular _unit) >> "displayName")],
// ["string", "uniform", uniform _unit],
// ["string", "uniformClass", getText(configFile >> "CfgWeapons" >> (uniform _unit) >> "displayName")],
// ["string", "vest", vest _unit],
// ["string", "vestClass", getText(configFile >> "CfgWeapons" >> (vest _unit) >> "displayName")],
// ["string", "backpack", backpack _unit],
// ["string", "backpackClass", getText(configFile >> "CfgWeapons" >> (backpack _unit) >> "displayName")]
// ];
// send loadout data
// {
// [
// "player_state",
// "unit_loadout",
// [
// ["string", "playerUID", _playerUID]
// ],
// _x,
// ["server"]
// ] call RangerMetrics_fnc_queue;
// } forEach [
// _primaryWeapon,
// _secondaryWeapon,
// _handgun,
// _magazinesFields,
// _itemsFields,
// _slotItems
// ];
// true;

View File

@@ -1,81 +0,0 @@
if (!RangerMetrics_run) exitWith {};
params [[
"_unit", objNull, [objNull]
]];
if (isNull _unit || !(isPlayer _unit)) exitWith {};
// Used in Dammaged EH, so add a 1s delay to prevent spamming
_checkDelay = 1;
_lastCheck = _unit getVariable [
"RangerMetrics_lastUnitStateCheck",
diag_tickTime
];
if (
(_lastCheck + _checkDelay) > diag_tickTime
) exitWith {};
_unit setVariable ["RangerMetrics_lastUnitStateCheck", diag_tickTime];
// Get owner playerUID
private _unitUID = getPlayerUID _unit;
if (_unitUID isEqualTo "") exitWith {};
// Medical info
private _isUnconscious = false;
private _isInCardiacArrest = false;
if (RangerMetrics_aceMedicalPresent) then {
_isUnconscious = _unit getVariable ["ace_medical_isUnconscious", false];
_isInCardiacArrest = _unit getVariable ["ace_medical_isInCardiacArrest", false];
} else {
_isUnconscious = (lifeState _unit) isEqualTo "INCAPACITATED";
};
// Vehicle info
private _inVehicle = !isNull (objectParent _unit);
if (_inVehicle) then {
_crew = fullCrew (objectParent _unit);
_pos = _crew find {(_x select 0) isEqualTo _unit};
_vehicleRole = toLower _crew select _pos select 1;
} else {
_vehicleRole = "";
};
// Declare fields
private _fields = [
["float", "health", 1 - (damage _unit)],
["bool", "is_unconscious", _isUnconscious],
["bool", "is_cardiac_arrest", _isInCardiacArrest],
["bool", "is_captive", captive _unit],
["bool", "in_vehicle", _inVehicle],
["string", "vehicle_role", _vehicleRole],
["float", "speed_kmh", speed _unit]
];
// Traits
private _playerTraits = getAllUnitTraits _unit;
{
private _valueType = typeNAME (_x select 1);
switch (_valueType) do {
case "BOOL": {
_fields pushBack ["bool", (_x select 0), (_x select 1)];
};
case "SCALAR": {
_fields pushBack ["float", (_x select 0), (_x select 1)];
};
case "STRING": {
_fields pushBack ["string", (_x select 0), (_x select 1)];
};
};
} forEach _playerTraits;
[
"player_state",
"unit_status",
[
["string", "playerUID", _unitUID]
],
_fields,
["server"]
] call RangerMetrics_fnc_queue;

View File

@@ -1,11 +0,0 @@
if (!RangerMetrics_run) exitWith {};
[
"server_state",
"view_distance",
nil,
[
["float", "objectViewDistance", getObjectViewDistance # 0],
["float", "viewDistance", viewDistance]
]
] call RangerMetrics_fnc_queue;

View File

@@ -1,21 +0,0 @@
if (!RangerMetrics_run) exitWith {};
[
"server_state", // bucket to store the data
"weather", // measurement classifier inside of bucket
nil, // tags
[ // fields
["float", "fog", fog],
["float", "overcast", overcast],
["float", "rain", rain],
["float", "humidity", humidity],
["float", "waves", waves],
["float", "windDir", windDir],
["float", "windStr", windStr],
["float", "gusts", gusts],
["float", "lightnings", lightnings],
["float", "moonIntensity", moonIntensity],
["float", "moonPhase", moonPhase date],
["float", "sunOrMoon", sunOrMoon]
]
] call RangerMetrics_fnc_queue;

View File

@@ -1,11 +0,0 @@
[
// [
// 5, // Poll interval in seconds
// [ // Array of things to poll on clients
// [
// "RangerMetrics_poll_loadout", // Name of localNamespace variable to save the handler as on clients
// RangerMetrics_capture_fnc_player_loadout // Function to call
// ]
// ]
// ]
]

View File

@@ -1,4 +0,0 @@
[
["ace_unconscious", RangerMetrics_event_fnc_ace_unconscious],
["milsim_serverEfficiency", RangerMetrics_event_fnc_milsim_serverEfficiency]
]

View File

@@ -1,194 +0,0 @@
[
["OnUserConnected", {
params ["_networkId", "_clientStateNumber", "_clientState"];
private _userInfo = (getUserInfo _networkId);
_userInfo call RangerMetrics_capture_fnc_player_identity;
_userInfo call RangerMetrics_capture_fnc_player_status;
["server_events", "OnUserConnected", [
["string", "playerUID", _userInfo#2]
], [
["string", "networkId", _networkId],
["int", "clientStateNumber", _clientStateNumber],
["string", "clientState", _clientState]
]] call RangerMetrics_fnc_queue;
[format ["(EventHandler) OnUserConnected fired: %1", _this], "DEBUG"] call RangerMetrics_fnc_log;
}],
["OnUserDisconnected", {
params ["_networkId", "_clientStateNumber", "_clientState"];
private _userInfo = (getUserInfo _networkId);
_userInfo call RangerMetrics_capture_fnc_player_identity;
_userInfo call RangerMetrics_capture_fnc_player_status;
["server_events", "OnUserDisconnected", [
["string", "playerUID", _userInfo#2]
], [
["string", "networkId", _networkId],
["int", "clientStateNumber", _clientStateNumber],
["string", "clientState", _clientState]
]] call RangerMetrics_fnc_queue;
[format ["(EventHandler) OnUserDisconnected fired: %1", _this], "DEBUG"] call RangerMetrics_fnc_log;
}],
["PlayerConnected", {
params ["_id", "_uid", "_name", "_jip", "_owner", "_idstr"];
private _userInfo = (getUserInfo _networkId);
_userInfo call RangerMetrics_capture_fnc_player_identity;
_userInfo call RangerMetrics_capture_fnc_player_status;
[_entity] call RangerMetrics_capture_fnc_unit_inventory;
["server_events", "PlayerConnected", [
["string", "playerUID", _userInfo#2]
], [
["int", "id", _id],
["string", "uid", _uid],
["string", "name", _name],
["bool", "jip", _jip],
["int", "owner", _owner],
["string", "idstr", _idstr]
]] call RangerMetrics_fnc_queue;
[format ["(EventHandler) PlayerConnected fired: %1", _this], "DEBUG"] call RangerMetrics_fnc_log;
}],
["PlayerDisconnected", {
params ["_id", "_uid", "_name", "_jip", "_owner", "_idstr"];
private _userInfo = (getUserInfo _networkId);
_userInfo call RangerMetrics_capture_fnc_player_identity;
_userInfo call RangerMetrics_capture_fnc_player_status;
["server_events", "PlayerDisconnected", [
["string", "playerUID", _userInfo#2]
], [
["int", "id", _id],
["string", "uid", _uid],
["string", "name", _name],
["bool", "jip", _jip],
["int", "owner", _owner],
["string", "idstr", _idstr]
]] call RangerMetrics_fnc_queue;
[format ["(EventHandler) PlayerDisconnected fired: %1", _this], "DEBUG"] call RangerMetrics_fnc_log;
}],
["OnUserClientStateChanged", {
params ["_networkId", "_clientStateNumber", "_clientState"];
private _userInfo = (getUserInfo _networkId);
_userInfo call RangerMetrics_capture_fnc_player_status;
["server_events", "OnUserClientStateChanged", [
["string", "playerUID", _userInfo#2]
], [
["string", "networkId", _networkId],
["int", "clientStateNumber", _clientStateNumber],
["string", "clientState", _clientState]
]] call RangerMetrics_fnc_queue;
[format ["(EventHandler) OnUserClientStateChanged fired: %1", _this], "DEBUG"] call RangerMetrics_fnc_log;
}],
["OnUserAdminStateChanged", {
params ["_networkId", "_loggedIn", "_votedIn"];
private _userInfo = (getUserInfo _networkId);
_userInfo call RangerMetrics_capture_fnc_player_status;
["server_events", "OnUserAdminStateChanged", [
["string", "playerUID", _userInfo#2]
], [
["string", "networkId", _networkId],
["bool", "loggedIn", _loggedIn],
["bool", "votedIn", _votedIn]
]] call RangerMetrics_fnc_queue;
[format ["(EventHandler) OnUserAdminStateChanged fired: %1", _this], "DEBUG"] call RangerMetrics_fnc_log;
}],
["OnUserKicked", {
params ["_networkId", "_kickTypeNumber", "_kickType", "_kickReason", "_kickMessageIncReason"];
private _userInfo = (getUserInfo _networkId);
_userInfo call RangerMetrics_capture_fnc_player_identity;
_userInfo call RangerMetrics_capture_fnc_player_status;
["server_events", "OnUserKicked", [
["string", "playerUID", _userInfo#2]
], [
["string", "networkId", _networkId],
["int", "kickTypeNumber", _kickTypeNumber],
["string", "kickType", _kickType],
["string", "kickReason", _kickReason],
["string", "kickMessageIncReason", _kickMessageIncReason]
]] call RangerMetrics_fnc_queue;
[format ["(EventHandler) OnUserKicked fired: %1", _this], "DEBUG"] call RangerMetrics_fnc_log;
}],
["HandleChatMessage", {
_this call RangerMetrics_event_fnc_HandleChatMessage;
// don't interfaere with the chat message
false;
}],
["MPEnded", {
private ["_winner", "_reason"];
_winner = "Unknown";
_reason = "Mission Complete";
["server_events", "MPEnded", nil, [
["string", "winner", _winner],
["string", "reason", _reason]
]] call RangerMetrics_fnc_queue;
call RangerMetrics_capture_fnc_running_mission;
[format ["(EventHandler) MPEnded fired: %1", _this], "DEBUG"] call RangerMetrics_fnc_log;
}],
["EntityCreated", {
params ["_entity"];
if (
!(_entity isKindOf "AllVehicles")
) exitWith {};
call RangerMetrics_capture_fnc_entity_count;
[format["(EventHandler) EntityCreated fired: %1", _this], "DEBUG"] call RangerMetrics_fnc_log;
}],
["EntityKilled", {
params ["_entity"];
if (
!(_entity isKindOf "AllVehicles")
) exitWith {};
_this call RangerMetrics_event_fnc_EntityKilled;
call RangerMetrics_capture_fnc_entity_count;
[_entity] call RangerMetrics_capture_fnc_unit_inventory;
[_entity] call RangerMetrics_capture_fnc_unit_state;
[format["(EventHandler) EntityKilled fired: %1", _this], "DEBUG"] call RangerMetrics_fnc_log;
}],
["EntityRespawned", {
params ["_newEntity", "_oldEntity"];
call RangerMetrics_capture_fnc_entity_count;
[_entity] call RangerMetrics_capture_fnc_unit_inventory;
[_entity] call RangerMetrics_capture_fnc_unit_state;
[format["(EventHandler) EntityRespawned fired: %1", _this], "DEBUG"] call RangerMetrics_fnc_log;
}],
["GroupCreated", {
params ["_group"];
call RangerMetrics_capture_fnc_entity_count;
[format["(EventHandler) GroupCreated fired: %1", _this], "DEBUG"] call RangerMetrics_fnc_log;
}],
["GroupDeleted", {
params ["_group"];
call RangerMetrics_capture_fnc_entity_count;
[format["(EventHandler) GroupDeleted fired: %1", _this], "DEBUG"] call RangerMetrics_fnc_log;
}],
["MarkerCreated", {
params ["_marker", "_channelNumber", "_owner", "_local"];
if (markerType _marker isEqualTo "") exitWith {};
_this call RangerMetrics_event_fnc_MarkerCreated;
[format["(EventHandler) MarkerCreated fired: %1", _this], "DEBUG"] call RangerMetrics_fnc_log;
}],
["MarkerDeleted", {
params ["_marker", "_channelNumber", "_owner", "_local"];
if (markerType _marker isEqualTo "") exitWith {};
_this call RangerMetrics_event_fnc_MarkerDeleted;
[format["(EventHandler) MarkerDeleted fired: %1", _this], "DEBUG"] call RangerMetrics_fnc_log;
}],
// ["MarkerUpdated", {
// params ["_marker", "_local"];
// if (markerType _marker isEqualTo "") exitWith {};
// _this call RangerMetrics_event_fnc_MarkerUpdated;
// }],
["Service", {
params ["_serviceVehicle", "_servicedVehicle", "_serviceType", "_needsService", "_autoSupply"];
[
"server_events",
"Service",
[
["string", "serviceVehicle", typeOf _serviceVehicle],
["string", "servicedVehicle", typeOf _servicedVehicle],
["int", "serviceType", _serviceType],
["bool", "needsService", _needsService],
["bool", "autoSupply", _autoSupply]
],
nil
] call RangerMetrics_fnc_queue;
[format["(EventHandler) Service fired: %1", _this], "DEBUG"] call RangerMetrics_fnc_log;
}]
]

View File

@@ -1,67 +0,0 @@
[
[
1, // interval
[ // functions to run
[
["server", "hc"],
RangerMetrics_capture_fnc_server_performance
]
]
],
[
3,
[
[
["server", "hc"],
RangerMetrics_capture_fnc_running_scripts
],
[
["server", "hc"],
RangerMetrics_capture_fnc_player_performance
]
]
],
[
15,
[
[
["server", "hc"],
RangerMetrics_capture_fnc_server_time
],
[
["hc"],
RangerMetrics_capture_fnc_entity_count
]
]
],
[
120,
[
[
["server"],
{
{
[_x] call RangerMetrics_capture_fnc_unit_inventory;
} count (call BIS_fnc_listPlayers);
}
]
]
],
[
300,
[
[
["server"],
RangerMetrics_capture_fnc_weather
],
[
["server"],
RangerMetrics_capture_fnc_view_distance
],
[
["server"],
RangerMetrics_capture_fnc_running_mission
]
]
]
]

View File

@@ -1,205 +0,0 @@
params [
["_unit", objNull, [objNull]]
];
if (isNull _unit) exitWith {};
if (!isPlayer _unit) exitWith {};
// if ACE medical is running, remoteExec a Dammaged EH for the player's machine to send lastDamageSource from ACE to the server. this is used for EntityKilled EH and others.
if (RangerMetrics_aceMedicalPresent) then {
[_unit, {
params ["_unit"];
private _handle = _unit addEventHandler ["Dammaged", {
params ["_unit", "_killer", "_instigator", "_useEffects"];
private _aceLastDamage = _unit getVariable "ace_medical_lastDamageSource";
if (!isNil "_aceLastDamage") then {
_unit setVariable ["ace_medical_lastDamageSource", _aceLastDamage, 2];
};
}];
_unit setVariable [
"RangerMetrics_UNITEH_Dammaged",
_handle
];
}] remoteExec ["call", owner _unit];
};
// explosion damage handler
[_unit, {
params ["_unit"];
private _handle = _unit addEventHandler ["Explosion", {
// params ["_vehicle", "_damage", "_source"];
_this remoteExec [
"RangerMetrics_event_fnc_Explosion", 2
];
}];
_unit setVariable [
"RangerMetrics_UNITEH_Explosion",
_handle
];
}] remoteExec ["call", 0, _unit];
// TODO
// server HitPart EH
// https://community.bistudio.com/wiki/Arma_3:_Event_Handlers#HitPart
// _handle = _unit addEventHandler ["HitPart", {
// (_this select 0) params ["_target", "_shooter", "_projectile", "_position", "_velocity", "_selection", "_ammo", "_vector", "_radius", "_surfaceType", "_isDirect"];
// private _unitPlayerId = getPlayerId _unit;
// private _userInfo = getUserInfo _unitPlayerId;
// // workaround from wiki to get shooter playerUID
// if (isNull _projectile) exitWith {};
// private _shooterPlayerId = (getPlayerId (getShotParents _projectile select 1));
// private _shooterInfo = getUserInfo _shooterPlayerId;
// [
// "player_events",
// "HandleDamage",
// [
// ["string", "playerUID", _userInfo select 2]
// ],
// [
// ["string", "selection", _selection],
// ["number", "damage", _damage],
// ["number", "hitIndex", _hitIndex],
// ["string", "hitPoint", _hitPoint],
// ["string", "shooter", _shooterInfo select 2],
// ["string", "projectile", _projectile]
// ],
// ["server"]
// ] call RangerMetrics_fnc_queue;
// [_unit] call RangerMetrics_capture_fnc_unit_state;
// }];
_handle = _unit addEventHandler [
"FiredMan", RangerMetrics_event_fnc_FiredMan
];
_unit setVariable [
"RangerMetrics_UNITEH_FiredMan",
_handle
];
_handle = _unit addEventHandler ["GetInMan", {
params ["_unit", "_role", "_vehicle", "_turret"];
private _unitPlayerId = getPlayerId _unit;
private _userInfo = getUserInfo _unitPlayerId;
private _playerUID = "-1";
if (!isNil "_userInfo") then {
_playerUID = _userInfo select 2;
};
[
"player_events",
"GetInMan",
[
["string", "playerUID", _playerUID]
],
[
["string", "role", _role],
["string", "vehicle", _vehicle],
["string", "turret", _turret]
],
["server"]
] call RangerMetrics_fnc_queue;
[_unit] call RangerMetrics_capture_fnc_unit_state;
}];
_unit setVariable [
"RangerMetrics_UNITEH_GetInMan",
_handle
];
_handle = _unit addEventHandler ["GetOutMan", {
params ["_unit", "_role", "_vehicle", "_turret"];
private _unitPlayerId = getPlayerId _unit;
private _userInfo = getUserInfo _unitPlayerId;
private _playerUID = "-1";
if (!isNil "_userInfo") then {
_playerUID = _userInfo select 2;
};
[
"player_events",
"GetOutMan",
[
["string", "playerUID", _playerUID]
],
[
["string", "role", _role],
["string", "vehicle", _vehicle],
["string", "turret", _turret]
],
["server"]
] call RangerMetrics_fnc_queue;
[_unit] call RangerMetrics_capture_fnc_unit_state;
}];
_unit setVariable [
"RangerMetrics_UNITEH_GetOutMan",
_handle
];
_handle = _unit addEventHandler ["HandleScore", {
params ["_unit", "_object", "_score"];
private _unitPlayerId = getPlayerId _unit;
private _userInfo = getUserInfo _unitPlayerId;
private _playerUID = "-1";
if (!isNil "_userInfo") then {
_playerUID = _userInfo select 2;
};
[
"player_events",
"HandleScore",
[
["string", "playerUID", _playerUID]
],
[
["int", "score", _score],
["string", "objectClass", typeOf _object],
["string", "object", [configOf _object] call BIS_fnc_displayName]
],
["server"]
] call RangerMetrics_fnc_queue;
nil;
}];
_unit setVariable [
"RangerMetrics_UNITEH_HandleScore",
_handle
];
_handle = _unit addEventHandler ["InventoryClosed", {
params ["_unit", "_container"];
private _unitPlayerId = getPlayerId _unit;
private _userInfo = getUserInfo _unitPlayerId;
private _playerUID = "-1";
if (!isNil "_userInfo") then {
_playerUID = _userInfo select 2;
};
[
"player_events",
"InventoryClosed",
[
["string", "playerUID", _playerUID]
],
[
["string", "container", _container]
],
["server"]
] call RangerMetrics_fnc_queue;
[_unit] call RangerMetrics_capture_fnc_unit_inventory;
nil;
}];
_unit setVariable [
"RangerMetrics_UNITEH_InventoryClosed",
_handle
];
true;

View File

@@ -1,14 +0,0 @@
params ["_name", "_function", "_data"];
if (_name == "RangerMetrics") then {
if (isNil "_data") then {_data = ""};
try {
if (_data isEqualType "") exitWith {
_data = parseSimpleArray _data;
_data call RangerMetrics_fnc_log;
};
diag_log format ["Callback unsupported type: %1: %2", _function, _data];
} catch {
_data = format ["%1", _data];
};
};

View File

@@ -1,24 +0,0 @@
if (!RangerMetrics_run) exitWith {};
private _startTime = diag_tickTime;
call RangerMetrics_capture_fnc_server_performance;
call RangerMetrics_capture_fnc_running_scripts;
call RangerMetrics_capture_fnc_server_time;
call RangerMetrics_capture_fnc_weather;
call RangerMetrics_capture_fnc_entities_local;
call RangerMetrics_capture_fnc_entities_global;
private _allUsers = allUsers apply {getUserInfo _x};
{
_x call RangerMetrics_capture_fnc_player_performance;
} forEach _allUsers;
// log the runtime and switch off debug so it doesn't flood the log
if (
missionNamespace getVariable ["RangerMetrics_debug",false]
) then {
[format ["Run time: %1", diag_tickTime - _startTime], "DEBUG"] call RangerMetrics_fnc_log;
// missionNamespace setVariable ["RangerMetrics_debug",false];
};

View File

@@ -1,38 +0,0 @@
if (!isServer) exitWith {};
if (!RangerMetrics_cbaPresent) exitWith {
[
format["RangerMetrics: CBA not present, aborting class EHs."],
"WARN"
] call RangerMetrics_fnc_log;
false;
// TODO: Add non-CBA compatibility for unit handler & id application
// addMissionEventHandler ["EntityCreated", {
};
///////////////////////////////////////////////////////////////////////
// Initialize all units
///////////////////////////////////////////////////////////////////////
["Man", "InitPost", {
params ["_unit"];
[_unit] call RangerMetrics_cDefinitions_fnc_unit_handlers;
_unit setVariable [
"RangerMetrics_id",
RangerMetrics_nextID,
true
];
[_unit] call RangerMetrics_capture_fnc_unit_inventory;
[_unit] call RangerMetrics_capture_fnc_unit_state;
if (RangerMetrics_debug) then {
[
format["ID %1, Object %2 (%3)", RangerMetrics_nextID, _unit, [configOf _unit] call BIS_fnc_displayName],
"DEBUG"
] call RangerMetrics_fnc_log;
};
RangerMetrics_nextID = RangerMetrics_nextID + 1;
}, nil, nil, true] call CBA_fnc_addClassEventHandler;

View File

@@ -1,198 +0,0 @@
// if (!isServer) exitWith {};
if (is3DEN || !isMultiplayer) exitWith {};
if (!isServer && hasInterface) exitWith {};
RangerMetrics_cbaPresent = isClass(configFile >> "CfgPatches" >> "cba_main");
RangerMetrics_aceMedicalPresent = isClass(configFile >> "CfgPatches" >> "ace_medical_status");
RangerMetrics_logPrefix = "RangerMetrics";
RangerMetrics_debug = true;
RangerMetrics_initialized = false;
RangerMetrics_run = false;
RangerMetrics_nextID = 0;
RangerMetrics_messageQueue = createHashMap;
// for debug, view messages in queue
// RangerMetrics_messageQueue apply {[_x, count _y]};
RangerMetrics_sendBatchHandle = scriptNull;
[format ["Instance name: %1", profileName]] call RangerMetrics_fnc_log;
[format ["CBA detected: %1", RangerMetrics_cbaPresent]] call RangerMetrics_fnc_log;
["Initializing v0.1"] call RangerMetrics_fnc_log;
// load settings from extension / settings.json
private _settingsLoaded = "RangerMetrics" callExtension "loadSettings";
// if (isNil "_settingsLoaded") exitWith {
// ["Extension not found, disabling"] call RangerMetrics_fnc_log;
// RangerMetrics_run = false;
// };
if (_settingsLoaded isEqualTo [] || _settingsLoaded isEqualTo "") exitWith {
["Failed to load settings, exiting", "ERROR"] call RangerMetrics_fnc_log;
};
_settingsLoaded = parseSimpleArray (_settingsLoaded);
[format["Settings loaded: %1", _settingsLoaded]] call RangerMetrics_fnc_log;
RangerMetrics_settings = createHashMap;
RangerMetrics_settings set [
"influxDB",
createHashMapFromArray [
["host", _settingsLoaded#1],
["org", _settingsLoaded#2]
]
];
RangerMetrics_settings set [
"arma3",
createHashMapFromArray [
["refreshRateMs", _settingsLoaded#3]
]
];
// connect to DB, extension is now ready
private _dbConnection = "RangerMetrics" callExtension "connectToInflux";
if (_dbConnection isEqualTo "") exitWith {
["Failed to connect to InfluxDB, disabling"] call RangerMetrics_fnc_log;
};
_response = parseSimpleArray _dbConnection;
(_response) call RangerMetrics_fnc_log;
systemChat str _response;
// send server profile name to all clients with JIP, so HC or player reporting knows what server it's connected to
if (isServer) then {
["RangerMetrics_serverProfileName", profileName] remoteExecCall ["setVariable", 0, true];
RangerMetrics_serverProfileName = profileName;
};
// define the metrics to capture by sideloading definition files
// this keeps the main file clean and easy to read
// the definition files are in the format of a hashmap, where the key is the category and the value is an array of arrays, where each sub-array is a capture definition
RangerMetrics_captureDefinitions = createHashMapFromArray [
[
"ServerEvent",
createHashMapFromArray [
[
"MissionEventHandlers",
call RangerMetrics_cDefinitions_fnc_server_missionEH
]
]],
["ClientEvent", []],
[
"ServerPoll",
call RangerMetrics_cDefinitions_fnc_server_poll
],
[
"ClientPoll",
call RangerMetrics_cDefinitions_fnc_client_poll
],
[
"CBAEvent",
call RangerMetrics_cDefinitions_fnc_server_CBA
]
];
// add missionEventHandlers on server only
{_x params ["_handleName", "_code"];
if (!isServer) exitWith {};
// try {
_handle = (addMissionEventHandler [_handleName, _code]);
// } catch {
// _handle = nil;
// };
if (isNil "_handle") then {
[format["Failed to add Mission event handler: %1", [_handleName]], "ERROR"] call RangerMetrics_fnc_log;
} else {
missionNamespace setVariable [
("RangerMetrics" + "_MEH_" + _handleName),
_handle
];
true;
};
} forEach ((RangerMetrics_captureDefinitions get "ServerEvent") get "MissionEventHandlers");
// begin server polling
{
_x call RangerMetrics_fnc_startServerPoll;
} forEach (RangerMetrics_captureDefinitions get "ServerPoll");
// remoteExec client polling - send data to start handles
{
_x call RangerMetrics_fnc_sendClientPoll;
} forEach (RangerMetrics_captureDefinitions get "ClientPoll");
// {
// } forEach (call RangerMetrics_captureDefinitions_fnc_clientEvent);
// begin client polling
// set up CBA event listeners
{_x params ["_handleName", "_code"];
private "_handle";
// try {
_handle = ([_handleName, _code] call CBA_fnc_addEventHandlerArgs);
// } catch {
// _handle = nil;
// };
if (isNil "_handle") then {
[format["Failed to add CBA event handler: %1", [_handleName, _code]], "ERROR"] call RangerMetrics_fnc_log;
} else {
missionNamespace setVariable [
("RangerMetrics" + "_CBAEH_" + _handleName),
_handle
];
true;
};
} forEach (RangerMetrics_captureDefinitions get "CBAEvent");
[] spawn {
sleep 1;
isNil {
addMissionEventHandler [
"ExtensionCallback",
RangerMetrics_fnc_callbackHandler
];
// set up CBA class inits if CBA loaded
call RangerMetrics_fnc_classHandlers;
private _meh = allVariables missionNamespace select {
_x find (toLower "RangerMetrics_MEH_") == 0
};
private _cba = allVariables missionNamespace select {
_x find (toLower "RangerMetrics_CBAEH_") == 0
};
private _serverPoll = allVariables missionNamespace select {
_x find (toLower "RangerMetrics_captureBatchHandle_") == 0
};
[format ["Mission event handlers: %1", _meh]] call RangerMetrics_fnc_log;
[format ["CBA event handlers: %1", _cba]] call RangerMetrics_fnc_log;
[format ["Server poll handles: %1", _serverPoll]] call RangerMetrics_fnc_log;
RangerMetrics_initialized = true;
RangerMetrics_run = true;
["RangerMetrics_run", true] remoteExecCall ["setVariable", 0];
// start sending
[{
params ["_args", "_idPFH"];
if (scriptDone RangerMetrics_sendBatchHandle) then {
RangerMetrics_sendBatchHandle = [] spawn RangerMetrics_fnc_send;
};
// call RangerMetrics_fnc_send;
}, 2, []] call CBA_fnc_addPerFrameHandler;
};
};

View File

@@ -1,55 +0,0 @@
params [
["_bucket", "default", [""]],
"_measurement",
["_tags", [], [[], nil]],
["_fields", [], [[], nil]],
["_tagContext", ["profile", "server"], [[]]]
];
// format[
// "profile=%1,world=%2,%3",
// profileName,
// toLower worldName,
// (_tags apply {format['%1=%2', _x#0, _x#1]}) joinString ","
// ],
if (_tagContext find "profile" > -1) then {
_tags pushBack ["string", "profileName", profileName];
};
if (_tagContext find "world" > -1) then {
_tags pushBack ["string", "world", toLower worldName];
};
if (_tagContext find "server" > -1) then {
_tags pushBack ["string", "connectedServer", RangerMetrics_serverProfileName];
};
private _outTags = _tags apply {
[_x, "tag"] call RangerMetrics_fnc_toLineProtocol
} select {!isNil "_x"};
// having no tags is OK
_outTags = _outTags joinString ",";
private _outFields = _fields apply {
[_x, "field"] call RangerMetrics_fnc_toLineProtocol
} select {!isNil "_x"};
// having no fields will cause an error
if (count _outFields isEqualTo 0) exitWith {};
_outFields = _outFields joinString ",";
private _extSend = format [
"%1,%2 %3 %4",
_measurement, // metric name
_outTags,
_outFields,
call RangerMetrics_fnc_unixTimestamp
];
// add to queue
(RangerMetrics_messageQueue getOrDefault [_bucket, [], true]) pushBack _extSend;
true

View File

@@ -1,66 +0,0 @@
// send the data
// duplicate the message queue so we can clear it before sending the data
private "_extSend";
// isNil {
// _extSend = + RangerMetrics_messageQueue;
// RangerMetrics_messageQueue = createHashMap;
// };
// debug
if (
missionNamespace getVariable ["RangerMetrics_debug",false]
) then {
["Sending a3influx data", "DEBUG"] call RangerMetrics_fnc_log;
};
{
// run in direct unscheduled call
// prevents race condition accessing hashmap
isNil {
private _bucket = _x;
private _batchSize = 2000;
// get the records for this bucket
private "_records";
private _records = RangerMetrics_messageQueue get _bucket;
// send the data in chunks
private _processing = _records select [0, (count _records -1) min _batchSize];
RangerMetrics_messageQueue set [
_bucket,
(RangerMetrics_messageQueue get _bucket) - _processing
];
// send the data
if (
missionNamespace getVariable ["RangerMetrics_debug",false]
) then {
[format ["Bucket: %1, RecordsCount: %2", _bucket, count _processing], "DEBUG"] call RangerMetrics_fnc_log;
// get unique measurement IDs
private _measurements = [];
{
_thisMeasurement = _x splitString "," select 0;
_measurements pushBackUnique _thisMeasurement;
} forEach _processing;
// get counts of each measurement
private _measurementCounts = [];
{
private _measurement = _x;
_measurementCounts pushBack [
_measurement,
count (_measurements select {_x == _measurement})
];
} forEach _measurements;
[format ["Measurements: %1", _measurementCounts], "DEBUG"] call RangerMetrics_fnc_log;
};
"RangerMetrics" callExtension ["sendToInflux", flatten [_bucket, _processing]];
};
} forEach (keys RangerMetrics_messageQueue);

View File

@@ -1,36 +0,0 @@
// format [interval, [[handleName, code], [handleName, code], ...]]
[_this, {
if (!hasInterface || isDedicated) exitWith {};
params [
["_interval", 5, [5]],
["_pollItems", []]
];
{
_x params [
"_handleName",
["_code", {}, [{}]]
];
private _runningCBA = (isClass(configFile >> "CfgPatches" >> "cba_main"));
if (_runningCBA) then {
missionNamespace setVariable [
_handleName,
[_code, _interval, _handleName] call CBA_fnc_addPerFrameHandler
];
} else {
missionNamespace setVariable [
_handleName,
[_handleName, _interval] spawn {
params [
"_handleName",
"_interval"
];
while {true} do {
[_handleName] call _code;
sleep _interval;
};
}
];
};
} forEach _pollItems;
}] remoteExec ["call", [0, -2] select isDedicated, true];

View File

@@ -1,84 +0,0 @@
params [
["_interval", 5, [0]],
["_functions", [], [[]]]
];
private _captureHandleName = format ["RangerMetrics_captureBatchHandle_%1", _interval];
if (RangerMetrics_cbaPresent) then { // CBA is running, use PFH
/*
This capture method is dynamic.
Every 5 seconds, two script handles are checked. One is for capturing, one is for sending.
The capturing script will go through and capture data, getting nanosecond precision timestamps from the extension to go alongside each data point, then saving it to a queue. It will go through all assigned interval-based checks then exit, and on the next interval of this parent PFH, the capturing script will be spawned again.
The queue is a hashmap where keys are buckets and values are arrays of data points in [string] line protocol format.
The sending script will go through and send data, sending it in batches per bucket and per 2000 data points, as the max extension call with args is 2048 elements.
The sending script will also check if the queue is empty, and if it is, it will exit. This means scriptDone will be true, and on the next interval of this parent PFH, the sending script will be spawned again.
This system means that capture and sending are occurring in the scheduled environment, not blocking the server, while maintaining the timestamps of when each point was captured. The cycles of each will only occur at most once per 2 seconds, leaving plenty of time, and there will never be more than one call for each at a time.
*/
private _handle = [{
params ["_args", "_idPFH"];
_args params ["_captureHandleName", "_functions"];
if (!RangerMetrics_run) exitWith {};
// use spawn
// if (scriptDone _captureHandleName) then {
// missionNamespace setVariable [
// _captureHandleName,
// [_functions] spawn {
// {
// call _x;
// } forEach _this;
// }
// ];
// };
// call direct
[format["Running %1 functions for %2", count _functions, _captureHandleName], "DEBUG"] call RangerMetrics_fnc_log;
{
_x params ["_whereToRun", "_scriptBlock"];
if (
_whereToRun find "server" == -1 &&
!isServer
) exitWith {false};
if (
_whereToRun find "hc" == -1 &&
(!hasInterface && !isDedicated)
) exitWith {false};
[] spawn _scriptBlock;
} forEach _functions;
}, _interval, [_captureHandleName, _functions]] call CBA_fnc_addPerFrameHandler;
missionNamespace setVariable [_captureHandleName, _handle];
} else { // CBA isn't running, use sleep
[_interval, _functions] spawn {
params ["_interval", "_functions"];
while {true} do {
if (!RangerMetrics_run) exitWith {};
{
_x params ["_whereToRun", "_scriptBlock"];
if (
_whereToRun find "server" == -1 &&
!isServer
) exitWith {false};
if (
_whereToRun find "hc" == -1 &&
(!hasInterface && !isDedicated)
) exitWith {false};
[] spawn _scriptBlock;
} forEach _functions;
sleep (_interval * 2);
};
};
};

View File

@@ -0,0 +1,22 @@
{
private _threadId = _x;
private _finished = ["RangerMetrics.influx.has_call_finished", [_threadId]] call py3_fnc_callExtension;
// systemChat str _finished;
if (isNil "_finished") exitWith {
RangerMetrics_activeThreads = RangerMetrics_activeThreads - [_threadId];
[format ["[%1]: Thread %2 not found", RangerMetrics_logPrefix, _threadId], "WARN"] call RangerMetrics_fnc_log;
};
if (_finished isEqualTo []) exitWith {
RangerMetrics_activeThreads = RangerMetrics_activeThreads - [_threadId];
[format ["[%1]: Thread %2 not found", RangerMetrics_logPrefix, _threadId], "WARN"] call RangerMetrics_fnc_log;
};
if (_finished isEqualTo true) then {
RangerMetrics_activeThreads = RangerMetrics_activeThreads - [_threadId];
if (missionNamespace getVariable ["RangerMetrics_debug",false]) then {
private _return = ["RangerMetrics.influx.get_call_value", [_threadId]] call py3_fnc_callExtension;
[format ["%1", _return], "DEBUG"] call RangerMetrics_fnc_log;
};
};
} forEach RangerMetrics_activeThreads;

View File

@@ -0,0 +1,83 @@
// function adapted from YAINA by MartinCo at http://yaina.eu
params [["_cba",false,[true]]];
if(missionNamespace getVariable ["RangerMetrics_run",false]) then {
private _startTime = diag_tickTime;
// Mission name
["server", "mission_name", [["source", "onLoadName"]], nil, "string", getMissionConfigValue ["onLoadName", ""]] call RangerMetrics_fnc_queue;
["server", "mission_name", [["source", "missionName"]], nil, "string", missionName] call RangerMetrics_fnc_queue;
["server", "mission_name", [["source", "missionNameSource"]], nil, "string", missionNameSource] call RangerMetrics_fnc_queue;
["server", "mission_name", [["source", "briefingName"]], nil, "string", briefingName] call RangerMetrics_fnc_queue;
["server", "server_uptime", nil, nil, "float", diag_tickTime toFixed 2] call RangerMetrics_fnc_queue;
// Number of local units
["simulation", "entity_count", [["entity_type", "unit"], ["only_local", true]], nil, "int", { local _x } count allUnits] call RangerMetrics_fnc_queue;
["simulation", "entity_count", [["entity_type", "group"], ["only_local", true]], nil, "int", { local _x } count allGroups] call RangerMetrics_fnc_queue;
["simulation", "entity_count", [["entity_type", "vehicles"], ["only_local", true]], nil, "int", { local _x} count vehicles] call RangerMetrics_fnc_queue;
// Server Stats
["simulation", "fps", [["metric", "avg"]], nil, "float", diag_fps toFixed 2] call RangerMetrics_fnc_queue;
["simulation", "fps", [["metric", "avg_min"]], nil, "float", diag_fpsMin toFixed 2] call RangerMetrics_fnc_queue;
["simulation", "mission_time", nil, nil, "float", time toFixed 2] call RangerMetrics_fnc_queue;
// Scripts
private _activeScripts = diag_activeScripts;
["simulation", "script_count", [["execution", "spawn"]], nil, "int", _activeScripts select 0] call RangerMetrics_fnc_queue;
["simulation", "script_count", [["execution", "execVM"]], nil, "int", _activeScripts select 1] call RangerMetrics_fnc_queue;
["simulation", "script_count", [["execution", "exec"]], nil, "int", _activeScripts select 2] call RangerMetrics_fnc_queue;
["simulation", "script_count", [["execution", "execFSM"]], nil, "int", _activeScripts select 3] call RangerMetrics_fnc_queue;
private _pfhCount = if(_cba) then {count CBA_common_perFrameHandlerArray} else {0};
["simulation", "script_count", [["execution", "pfh"]], nil, "int", _pfhCount] call RangerMetrics_fnc_queue;
// Globals if server
if (isServer) then {
// Number of global units
["simulation", "entity_count", [["entity_type", "unit"], ["only_local", false]], nil, "int", count allUnits] call RangerMetrics_fnc_queue;
["simulation", "entity_count", [["entity_type", "group"], ["only_local", false]], nil, "int", count allGroups] call RangerMetrics_fnc_queue;
["simulation", "entity_count", [["entity_type", "vehicle"], ["only_local", false]], nil, "int", count vehicles] call RangerMetrics_fnc_queue;
["simulation", "entity_count", [["entity_type", "player"], ["only_local", false]], nil, "int", count allPlayers] call RangerMetrics_fnc_queue;
};
private _headlessClients = entities "HeadlessClient_F";
{
{
private _stats_fps = diag_fps toFixed 2;
private _stats_fps_min = diag_fpsMin toFixed 2;
["simulation", "fps_hc", [["metric", "avg"]], nil, "float", _stats_fps] remoteExec ["RangerMetrics_fnc_queue", 2];
["simulation", "fps_hc", [["metric", "avg_min"]], nil, "float", _stats_fps_min] remoteExec ["RangerMetrics_fnc_queue", 2];
} remoteExecCall ["bis_fnc_call", owner _x];
} foreach _headlessClients;
/** WORKING HEADLESS CODE COMMENTED OUT TO TRY SOMETHING DIFFERNT
// Headless Clients FPS
// Thanks to CPL.Brostrom.A
private _headlessClients = entities "HeadlessClient_F";
{
{
private _stats_fps = round diag_fps;
["stats.HCfps", _stats_fps] remoteExec ["RangerMetrics_fnc_queue", 2];
} remoteExecCall ["bis_fnc_call", owner _x];
} foreach _headlessClients;
*/
// log the runtime and switch off debug so it doesn't flood the log
if(missionNamespace getVariable ["RangerMetrics_debug",false]) then {
[format ["Run time: %1", diag_tickTime - _startTime], "DEBUG"] call RangerMetrics_fnc_log;
// missionNamespace setVariable ["RangerMetrics_debug",false];
};
};

View File

@@ -1,19 +1,4 @@
params [["_text","Log text invalid"], ["_type","INFO"]];
if (typeName _this != "ARRAY") exitWith {
diag_log format ["RangerMetrics: Invalid log params: %1", _this];
};
if (typeName _text != "STRING") exitWith {
diag_log format ["RangerMetrics: Invalid log text: %1", _this];
};
if (typeName _type != "STRING") exitWith {
diag_log format ["RangerMetrics: Invalid log type: %1", _this];
};
if (_type isEqualTo "DEBUG") then {
if (!RangerMetrics_debug) exitWith {};
};
params [["_text","Log text invalid",[""]], ["_type","INFO",[""]]];
private _textFormatted = format [
"[%1] %2: %3",
RangerMetrics_logPrefix,

View File

@@ -0,0 +1,74 @@
// if (!isServer) exitWith {};
_cba = (isClass(configFile >> "CfgPatches" >> "cba_main"));
RangerMetrics_logPrefix = "RangerMetrics";
RangerMetrics_debug = true;
RangerMetrics_activeThreads = [];
RangerMetrics_messageQueue = createHashMap;
[format ["Instance name: %1", profileName]] call RangerMetrics_fnc_log;
[format ["CBA detected: %1", _cba]] call RangerMetrics_fnc_log;
["Initializing v1.1"] call RangerMetrics_fnc_log;
private _settingsLoaded = ["RangerMetrics.influx.load_settings", []] call py3_fnc_callExtension;
if (isNil "_settingsLoaded") exitWith {
["Extension not found, disabling"] call RangerMetrics_fnc_log;
RangerMetrics_run = false;
};
if (_settingsLoaded isEqualTo []) then {
if (count _settingsLoaded == 0) exitWith {
["Settings not loaded, disabling"] call RangerMetrics_fnc_log;
RangerMetrics_run = false;
};
if (_settingsLoaded#0 isEqualTo 1) exitWith {
[
format["Settings not loaded, disabling. %1", _settingsLoaded#1],
"ERROR"
] call RangerMetrics_fnc_log;
RangerMetrics_run = false;
};
};
format["Settings loaded: %1", _settingsLoaded#2] call RangerMetrics_fnc_log;
RangerMetrics_settings = _settingsLoaded#2;
// RangerMetrics_settings = createHashMap;
// private _top = createHashMapFromArray _settingsLoaded#2;
// RangerMetrics_settings set [
// "influxDB",
// createHashMapFromArray (_top get "influxDB")
// ];
// RangerMetrics_settings set [
// "arma3",
// createHashMapFromArray (_top get "refreshRateMs")
// ];
["RangerMetrics.influx.connect_to_influx", []] call py3_fnc_callExtension;
RangerMetrics_run = true;
// addMissionEventHandler ["ExtensionCallback", {
// params ["_name", "_function", "_data"];
// if (_name == "RangerMetrics") then {
// [parseSimpleArray _data] call RangerMetrics_fnc_log;
// };
// }];
if(_cba) then { // CBA is running, use PFH
[{
params ["_args", "_idPFH"];
_args params [["_cba", false]];
[_cba] call RangerMetrics_fnc_gather;
call RangerMetrics_fnc_checkResults;
call RangerMetrics_fnc_send;
// }, (RangerMetrics_settings get "arma3" get "refreshRateMs"), [_cba]] call CBA_fnc_addPerFrameHandler;
}, 1, [_cba]] call CBA_fnc_addPerFrameHandler;
} else { // CBA isn't running, use sleep
[_cba] spawn {
params ["_cba"];
while {true} do {
[_cba] call RangerMetrics_fnc_gather; // nested to match CBA PFH signature
call RangerMetrics_fnc_checkResults;
call RangerMetrics_fnc_send;
// sleep (RangerMetrics_settings get "arma3" get "refreshRateMs");
sleep 1;
};
};
};

View File

@@ -0,0 +1,42 @@
params [
["_bucket", "default", [""]],
"_measurement",
["_tags", nil, [[], nil]],
["_fields", nil, [[], nil]],
"_valueType",
"_value"
];
private _profileName = profileName;
private _prefix = "Arma3";
private _extSend = [
_measurement, // metric name
_valueType, // float or int
[ // tags
["profile", _profileName],
["world", toLower worldName]
],
[ // fields
["server", serverName],
["mission", missionName],
["value", _value]
]
];
if (!isNil "_tags") then {
{
(_extSend select 2) pushBack [_x#0, _x#1];
} forEach _tags;
};
if (!isNil "_fields") then {
{
(_extSend select 3) pushBack [_x#0, _x#1];
} forEach _fields;
};
// add to queue
(RangerMetrics_messageQueue getOrDefault [_bucket, [], true]) pushBack _extSend;
true

View File

@@ -0,0 +1,50 @@
// send the data
[{
if(missionNamespace getVariable ["RangerMetrics_debug",false]) then {
[format ["Sending a3influx data: %1", RangerMetrics_messageQueue], "DEBUG"] call RangerMetrics_fnc_log;
};
// duplicate the message queue so we can clear it before sending the data
private _extSend = + RangerMetrics_messageQueue;
RangerMetrics_messageQueue = createHashMap;
{
// for each bucket, send data to extension
private _bucketName = _x;
private _bucketData = _y;
// if (true) exitWith {
[format ["bucketName: %1", _bucketName], "DEBUG"] call RangerMetrics_fnc_log;
[format ["bucketData: %1", _bucketData], "DEBUG"] call RangerMetrics_fnc_log;
// };
private _return = ["RangerMetrics.influx.write_influx", [[_bucketName, _bucketData]]] call py3_fnc_callExtension;
// shouldn't be possible, the extension should always return even if error
if(isNil "_return") exitWith {
[format ["return was nil (%1)", _extSend], "ERROR"] call RangerMetrics_fnc_log;
false
};
if (typeName _return != "ARRAY") exitWith {
[format ["return was not an array (%1)", _extSend], "ERROR"] call RangerMetrics_fnc_log;
false
};
if (count _return == 0) exitWith {
[format ["return was empty (%1)", _extSend], "ERROR"] call RangerMetrics_fnc_log;
false
};
if (count _return == 2) exitWith {
[format ["return was error (%1)", _extSend], "ERROR"] call RangerMetrics_fnc_log;
false
};
// success, add to list of active threads
RangerMetrics_activeThreads pushBack (_return select 0);
// success, only show if debug is set
if (missionNamespace getVariable ["RangerMetrics_debug",false]) then {
[format ["a3influx threadId: %1", _return], "DEBUG"] call RangerMetrics_fnc_log;
};
} forEach _extSend;
}] call CBA_fnc_execNextFrame;

View File

@@ -1,12 +0,0 @@
params [[
"_unit", objNull, [objNull]
]];
if (isNull _unit) exitWith {};
private _playerID = getPlayerID _unit;
private _userInfo = (getUserInfo _playerID);
_userInfo call RangerMetrics_capture_fnc_player_identity;
_userInfo call RangerMetrics_capture_fnc_player_status;
[_unit] call RangerMetrics_capture_fnc_unit_state;
[_unit] call RangerMetrics_capture_fnc_unit_inventory;

View File

@@ -1,39 +0,0 @@
//
// PX_fnc_stringReplace :: Replace substrings
// Author: Colin J.D. Stewart
// Usage: ["xxx is awesome, I love xxx!", "xxx" || [], "Arma"] call PX_fnc_stringReplace;
//
params["_str", "_find", "_replace"];
private["_return", "_len", "_pos"];
if !(_str isEqualType "") exitWith {
[
format[
"RangerMetrics_fnc_stringReplace: _str is not a string. %1",
_str
],
"ERROR"
] call RangerMetrics_fnc_log;
"";
};
if (!(_find isEqualType [])) then {
_find = [_find];
};
{
_return = "";
_len = count _x;
_pos = _str find _x;
while {(_pos != -1) && (count _str > 0)} do {
_return = _return + (_str select [0, _pos]) + _replace;
_str = (_str select [_pos+_len]);
_pos = _str find _x;
};
_str = _return + _str;
} forEach _find;
_str;

View File

@@ -1,67 +0,0 @@
params ["_line", ["_section", "field", [""]]];
_line params [
["_valueType", "string", [""]],
["_key", "", [""]],
"_value"
];
// debug
// diag_log format["%1=%2", _key, _value];
if (isNil "_value") exitWith {
nil;
};
if (_value isEqualTo "") exitWith {
nil
};
if (_value isEqualType []) then {
_value = _value joinString ",";
// replace double quotes with single quotes
_value = [_value, '""', "'"] call RangerMetrics_fnc_stringReplace;
};
_key = [_key, ',', "\,"] call RangerMetrics_fnc_stringReplace;
_key = [_key, '=', "\="] call RangerMetrics_fnc_stringReplace;
_key = [_key, ' ', "\ "] call RangerMetrics_fnc_stringReplace;
if (_section isEqualTo "tag") exitWith {
switch (_valueType) do {
case "string": {
_value = [_value, ',', "\,"] call RangerMetrics_fnc_stringReplace;
_value = [_value, '=', "\="] call RangerMetrics_fnc_stringReplace;
_value = [_value, ' ', "\ "] call RangerMetrics_fnc_stringReplace;
_value = format['%1=%2', _key, _value];
};
case "int": {
_value = format['%1=%2i', _key, _value];
};
case "bool": {
_value = format['%1=%2', _key, ['true', 'false'] select _value];
};
case "float": {
_value = format['%1=%2', _key, _value];
};
};
_value;
};
if (_section isEqualTo "field") exitWith {
switch (_valueType) do {
case "string": {
_value = [_value, '\', "\\"] call RangerMetrics_fnc_stringReplace;
_value = [_value, '"', '\"'] call RangerMetrics_fnc_stringReplace;
_value = format['%1="%2"', _key, _value];
};
case "int": {
_value = format['%1=%2i', _key, _value];
};
case "bool": {
_value = format['%1=%2', _key, ['true', 'false'] select _value];
};
case "float": {
_value = format['%1=%2', _key, _value];
};
};
_value;
};

View File

@@ -1 +0,0 @@
(parseSimpleArray ("RangerMetrics" callExtension "getUnixTimeNano")) select 0;

View File

@@ -1,25 +1,23 @@
if (!RangerMetrics_run) exitWith {};
// get basic config properties
private _properties = [
["mission_info", [
["settings_mission_info", [
"author",
"onLoadName",
"onLoadMission",
"loadScreen",
// "header",
"gameType",
"minPlayers",
"maxPlayers",
"header",
"onLoadIntro",
"onLoadMissionTime",
"onLoadIntroTime",
"briefingName",
"overviewPicture",
"overviewText",
"overviewTextLocked"
"overviewTextLocked",
"onBriefingGear",
"onBriefingGroup",
"onBriefingPlan"
]],
["respawn", [
["settings_respawn", [
"respawn",
"respawnButton",
"respawnDelay",
@@ -27,10 +25,6 @@ private _properties = [
"respawnDialog",
"respawnOnStart",
"respawnTemplates",
"respawnTemplatesWest",
"respawnTemplatesEast",
"respawnTemplatesGuer",
"respawnTemplatesCiv",
"respawnWeapons",
"respawnMagazines",
"reviveMode",
@@ -44,20 +38,20 @@ private _properties = [
"reviveBleedOutDelay",
"enablePlayerAddRespawn"
]],
["player_ui", [
"overrideFeedback",
"showHUD",
"showCompass",
"showGPS",
"showGroupIndicator",
"showMap",
"showNotePad",
"showPad",
"showWatch",
"showUAVFeed",
"showSquadRadar"
["settings_player_ui", [
"overrideFeedback",
"showHUD",
"showCompass",
"showGPS",
"showGroupIndicator",
"showMap",
"showNotePad",
"showPad",
"showWatch",
"showUAVFeed",
"showSquadRadar"
]],
["corpse_and_wreck", [
["settings_corpse_and_wreck", [
"corpseManagerMode",
"corpseLimit",
"corpseRemovalMinTime",
@@ -68,43 +62,40 @@ private _properties = [
"wreckRemovalMaxTime",
"minPlayerDistance"
]],
["mission_settings", [
"aiKills",
"briefing",
"debriefing",
"disableChannels",
"disabledAI",
"disableRandomization",
"enableDebugConsole",
"enableItemsDropping",
"enableTeamSwitch",
"forceRotorLibSimulation",
"joinUnassigned",
"minScore",
"avgScore",
"maxScore",
"onCheat",
"onPauseScript",
"saving",
"scriptedPlayer",
"skipLobby",
"HostDoesNotSkipLobby",
"missionGroup"
["settings_mission_general", [
"aiKills",
"briefing",
"debriefing",
"disableChannels",
"disabledAI",
"disableRandomization",
"enableDebugConsole",
"enableItemsDropping",
"enableTeamSwitch",
"forceRotorLibSimulation",
"joinUnassigned",
"minScore",
"avgScore",
"maxScore",
"onCheat",
"onPauseScript",
"saving",
"scriptedPlayer",
"skipLobby",
"HostDoesNotSkipLobby",
"missionGroup"
]
]
];
private _propertyValues = createHashMap;
// recursively walk through missionConfigFile and get all properties into a single hashmap
// iterate through list of categories with desired property names
// if the property exists in the extracted missionConfigFile property hash, save it with the category into _propertyValues
{
private _category = _x#0;
private _values = _x#1;
{
private _property = _x;
private _value = (missionConfigFile >> _property) call BIS_fnc_getCfgData;
// hint str [_category, _property, _value];
hint str [_category, _property, _value];
if (!isNil "_value") then {
if (typeName _value == "ARRAY") then {
_value = _value joinString ",";
@@ -118,50 +109,11 @@ private _propertyValues = createHashMap;
} forEach _properties;
// Take the generated hashmap of custom-categorized configuration properties and queue them for metrics
// Take the generated hashmap and queue metrics
{
private _measurementCategory = _x;
private _fields = _y;
private _fieldsWithType = [];
// InfluxDB lookup hash
_types = createHashMapFromArray [
["STRING", "string"],
["ARRAY", "string"],
["SCALAR", "float"],
["BOOL", "bool"]
];
// Preprocess the fields to clean the raw data
{
private _fieldName = _x;
private _fieldValue = _y;
private _fieldType = _types get (typeName _fieldValue);
// turn ARRAY into string since Influx can't take them
if (typeName _fieldValue == "ARRAY") then {
_fieldValue = _fieldValue joinString "|";
};
// convert 0 or 1 (from config) to BOOL
if (typeName _fieldValue == "SCALAR" && _fieldValue in [0, 1]) then {
_fieldType = "bool";
if (_fieldValue == 0) then {
_fieldValue = "false";
} else {
_fieldValue = "true";
};
};
_fieldsWithType pushBack [_fieldType, _fieldName, _fieldValue];
} forEach _fields;
// finally, send the data
[
"config_state",
"mission_config_file",
[
["category", _measurementCategory]
],
_fieldsWithType
] call RangerMetrics_fnc_queue;
["config", _measurementCategory, nil, _fields, "int", 0] call RangerMetrics_fnc_queue;
} forEach _propertyValues;

View File

@@ -1,403 +0,0 @@
classDiagram
class server_state {
BUCKET
}
class server_events {
Measurement OnUserConnected
Measurement OnUserDisconnected
Measurement PlayerConnected
Measurement PlayerDisconnected
Measurement OnUserClientStateChanged
Measurement OnUserAdminStateChanged
Meausrement HandleChatMessage
Measurement MPEnded
Measurement EntityCreated
Measurement EntityKilled
Measurement GroupCreated
Measurement GroupDeleted
Measurement MarkerCreated
Measurement MarkerDeleted
Measurement MarkerUpdated
}
server_state --> running_mission
class running_mission {
capture: ServerPoll, 60s
tag string profileName
tag string connectedServer
field string onLoadName
field string missionName
field string missionNameSource
field string briefingName
}
server_state --> view_distance
class view_distance {
capture: ServerPoll, 60s
tag string profileName
tag string connectedServer
field string viewDistance
field string objectViewDistance
}
server_state --> server_time
class server_time {
tag string profileName
tag string connectedServer
field float diag_tickTime
field int serverTime
field float timeMultiplier
field int accTime
}
server_state --> running_scripts
class running_scripts {
tag string profileName
tag string connectedServer
field int spawn_total
field int execVM_total
field int exec_total
field int execFSM_total
field int pfh_total
}
server_state --> entities_local
class entities_local {
capture: ServerPoll, 1s (customizable)
tag string profileName
tag string connectedServer
field int units_alive
field int units_dead
field int vehicles_total
field int groups_total
}
server_state --> entities_global
class entities_global {
capture: ServerPoll, 1s (customizable)
tag string profileName
tag string connectedServer
field int units_alive
field int units_dead
field int vehicles_total
field int groups_total
}
server_state --> entities_remote
class entities_remote {
capture: ServerPoll, 1s (customizable)
tag string profileName
tag string connectedServer
field int units_alive
field int units_dead
field int vehicles_total
field int groups_total
}
server_state --> server_performance
class server_performance {
capture: ServerPoll, 1s (customizable)
tag string profileName
tag string connectedServer
field string fps_avg
field string fps_min
}
server_state --> weather
class weather {
capture: ServerPoll, 60s
tag string profileName
tag string connectedServer
field string fog
field string overcast
field string rain
field string humidity
field string waves
field string windDir
field string windStr
field string gusts
field string lightnings
field string moonIntensity
field string moonPhase
field string sunOrMoon
}
class config_state {
tag string profileName
tag string connectedServer
Measurement mission_config_file
Measurement addon_options
Measurement mission_parameters
Measurement visual_settings
}
config_state --> mission_config_file
class mission_config_file {
tag string profileName
tag string connectedServer
tag string category [
mission_info
respawn
player_ui
corpse_and_wreck
mission_settings
]
}
%% ' link fields in each category
mission_config_file --> mission_info
class mission_info {
tag string profileName
tag string connectedServer
field string author
field string onLoadName
field string onLoadMission
field string loadScreen
%% field string header
field string gameType
field int minPlayers
field int maxPlayers
field int onLoadIntro
field int onLoadMissionTime
field int onLoadIntroTime
field string briefingName
field string overviewPicture
field string overviewText
field string overviewTextLocked
}
mission_config_file --> respawn
class respawn {
tag string profileName
tag string connectedServer
field string respawn
field string respawnButton
field string respawnDelay
field string respawnVehicleDelay
field string respawnDialog
field string respawnOnStart
field string respawnTemplates
field string respawnTemplatesWest
field string respawnTemplatesEast
field string respawnTemplatesGuer
field string respawnTemplatesCiv
field string respawnWeapons
field string respawnMagazines
field int reviveMode
field int reviveUnconsciousStateMode
field int reviveRequiredTrait
field int reviveRequiredItems
field int reviveRequiredItemsFakConsumed
field int reviveMedicSpeedMultiplier
field int reviveDelay
field int reviveForceRespawnDelay
field int reviveBleedOutDelay
field int enablePlayerAddRespawn
}
mission_config_file --> player_ui
class player_ui {
tag string profileName
tag string connectedServer
field int overrideFeedback
field int showHUD
field int showCompass
field int showGPS
field int showGroupIndicator
field int showMap
field int showNotePad
field int showPad
field int showWatch
field int showUAVFeed
field int showSquadRadar
}
mission_config_file --> corpse_and_wreck
class corpse_and_wreck {
tag string profileName
tag string connectedServer
field int corpseManagerMode
field int corpseLimit
field int corpseRemovalMinTime
field int corpseRemovalMaxTime
field int wreckManagerMode
field int wreckLimit
field int wreckRemovalMinTime
field int wreckRemovalMaxTime
field int minPlayerDistance
}
mission_config_file --> mission_settings
class mission_settings {
tag string profileName
tag string connectedServer
field int aiKills
field int briefing
field int debriefing
field string disableChannels
field int disabledAI
field string disableRandomization
field List~string~ enableDebugConsole
field int enableItemsDropping
field int enableTeamSwitch
field int forceRotorLibSimulation
field int joinUnassigned
field int minScore
field int avgScore
field int maxScore
field string onCheat
field string onPauseScript
field int saving
field int scriptedPlayer
field int skipLobby
field int HostDoesNotSkipLobby
field string missionGroup
}
config_state --> visual_settings
class visual_settings {
tag string profileName
tag string connectedServer
field string getTIParameters
field string objectViewDistance
}
class player_state
player_state --> player_identity
class player_identity {
capture: MissionEH, OnUserConnected
capture: MissionEH, OnUserDisconnected
capture: MissionEH, PlayerConnected
capture: MissionEH, PlayerDisconnected
tag string profileName
tag string connectedServer
field string playerID
field string ownerId
field string playerUID
field string profileName
field string displayName
field string steamName
field bool isHC
field bool isJip
field string roleDescription
}
player_state --> player_status
class player_status {
capture: MissionEH, OnUserConnected
capture: MissionEH, OnUserDisconnected
capture: MissionEH, PlayerConnected
capture: MissionEH, PlayerDisconnected
capture: MissionEH, OnUserClientStateChanged
capture: MissionEH, OnUserAdminStateChanged
tag string profileName
tag string connectedServer
field string playerUID
field int clientStateNumber
field int adminState
}
player_state --> player_performance
class player_performance {
capture: ServerPoll
tag string profileName
tag string connectedServer
field string playerUID
field float avgPing
field float avgBandwidth
field float desync
}
player_state --> unit_loadout
class unit_loadout {
capture: InventoryClosedEH
tag string profileName
tag string connectedServer
field string playerUID
field string uniform
field string vest
field string backpack
field string headgear
field string goggles
field string hmd
field string primaryWeapon
field string primaryWeaponMagazine
field string secondaryWeapon
field string secondaryWeaponMagazine
field string handgunWeapon
field string handgunMagazine
}
player_state --> unit_state
class unit_state {
tag string connectedServer
tag string playerUID
field float health
field bool is_unconscious
field bool is_cardiac_arrest
field bool is_captive
field bool in_vehicle
field string vehicle_role
field float speed_kmh
}
class player_events
player_events --> Dammaged
class Dammaged {
capture: UnitEH, Dammaged
tag string connectedServer
tag string playerUID
field string selection
field string damage
field string hitIndex
field string hitPoint
field string shooter
field string projectile
}
player_events --> FiredMan
class FiredMan {
capture: UnitEH, FiredMan
tag string connectedServer
tag string playerUID
field string weapon
field string muzzle
field string mode
field string ammo
field string magazine
field string vehicle
field string vehicleClass
}
player_events --> GetInMan
class GetInMan {
capture: UnitEH, GetInMan
tag string connectedServer
tag string playerUID
field string role
field string vehicle
field string turret
}
player_events --> GetOutMan
class GetOutMan {
capture: UnitEH, GetOutMan
tag string connectedServer
tag string playerUID
field string role
field string vehicle
field string turret
}
player_events --> HandleScore
class HandleScore {
capture: UnitEH, HandleScore
tag string connectedServer
tag string playerUID
field int score
field string object
field string objectclass
}

View File

@@ -0,0 +1 @@
RangerMetrics

View File

@@ -0,0 +1,3 @@
from . import influx
influx

View File

@@ -0,0 +1,190 @@
import influxdb_client
from influxdb_client.client.write_api import SYNCHRONOUS
import threading
from pyproj import Transformer
from datetime import datetime
import json
import os
from .threading_utils import (
call_slow_function,
has_call_finished,
get_call_value,
THREADS,
THREAD_ID,
)
# get parent of parent directory (mod dir)
MOD_DIR = (
os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
.lstrip("\\")
.lstrip("?")
.lstrip("\\")
)
SETTINGS_FILE = ""
SETTINGS = None
DBCLIENT = None
WRITE_API = None
PROCESS_LOG = MOD_DIR + "\\rangermetrics_process.log"
ERROR_LOG = MOD_DIR + "\\rangermetrics_error.log"
DATA_LOG = MOD_DIR + "\\rangermetrics_data.log"
# TRANSFORMER = Transformer.from_crs("epsg:3857", "epsg:4326")
def get_dir():
# get current dir without leading or trailing slashes
this_path = (
os.path.dirname(os.path.realpath(__file__))
.lstrip("\\")
.lstrip("?")
.lstrip("\\")
)
return [0, "Current directory", this_path, PROCESS_LOG]
def load_settings():
# check if settings.json exists in MOD_DIR
if not (os.path.isfile(os.path.join(MOD_DIR, "settings.json"))):
return [1, "settings.json not found in mod directory", MOD_DIR]
global SETTINGS_FILE
SETTINGS_FILE = os.path.join(MOD_DIR, "settings.json")
# import settings from settings.json
global SETTINGS
with open(SETTINGS_FILE, "r") as f:
SETTINGS = json.load(f)
settings_validation = [
["influxdb", "host"],
["influxdb", "token"],
["influxdb", "org"],
["influxdb", "defaultBucket"],
["arma3", "refreshRateMs"],
]
for setting in settings_validation:
if not (setting[0] in SETTINGS and setting[1] in SETTINGS[setting[0]]):
return [1, f"Missing setting: {setting[0]} {setting[1]}"]
# prep settings out to hashMap style list for A3
# [[key, [subkey, subvalue], [subkey, subvalue]]]
settings_out = []
for key, value in SETTINGS.items():
if isinstance(value, dict):
this_values = []
for subkey, subvalue in value.items():
this_values.append([subkey, subvalue])
settings_out.append([key, this_values])
else:
settings_out.append([key, value])
return [0, "Settings loaded", settings_out]
def connect_to_influx():
global DBCLIENT
DBCLIENT = influxdb_client.InfluxDBClient(
url=SETTINGS["influxdb"]["host"],
token=SETTINGS["influxdb"]["token"],
org=SETTINGS["influxdb"]["org"],
enable_gzip=True,
)
if DBCLIENT is None:
return [1, "Error connecting to InfluxDB"]
global WRITE_API
WRITE_API = DBCLIENT.write_api(write_options=SYNCHRONOUS)
if WRITE_API is None:
return [1, "Error connecting to InfluxDB"]
return [0, "Connected to InfluxDB"]
def test_data(data):
with open("influxdb_data.log", "a") as f:
f.write(str(data) + "\n")
f.write(f"{datetime.now()}: {data[2]}\n")
# convert to dict from list of key, value pairs
# format [[key, value], [key, value]] to {key: value, key: value}
measurement, tag_set, field_set, position = data
tag_dict = dict(tag_set)
field_dict = dict(field_set)
f.write(
f"{datetime.now()}: {measurement}, {json.dumps(tag_dict, indent=2)}, {json.dumps(field_dict, indent=2)}, {position}\n"
)
# thread the write to influxdb
return [data, dict(data[1])]
def log_process(line):
# log the process to a file
with open(PROCESS_LOG, "a+") as f:
f.write(f"{datetime.now()}: {line}\n")
return True
def log_error(line):
# log errors to a file
with open(ERROR_LOG, "a+") as f:
f.write(f"{datetime.now()}: {line}\n")
return True
def write_influx(data):
# thread the write to influxdb
thread_id = call_slow_function(write_influx_async, (data,))
return [thread_id]
def write_influx_async(data):
processed = []
timestamp = f" {int(datetime.now().timestamp() * 1e9)}"
# return [data]
target_bucket = data[0] or SETTINGS["influxdb"]["defaultBucket"]
log_process(f"Writing to bucket {target_bucket}")
log_process(f"Processing {len(data)} data points")
for point in data[1]:
measurement = point[0]
value_type = point[1]
tag_dict = dict(point[2])
field_dict = dict(point[3])
if value_type == "int":
field_dict["value"] = int(field_dict["value"])
elif value_type == "float":
field_dict["value"] = float(field_dict["value"])
point_dict = {
"measurement": measurement,
"tags": tag_dict,
"fields": field_dict,
}
processed.append(point_dict)
log_process(f"Writing {len(processed)} data points")
try:
result = WRITE_API.write(target_bucket, SETTINGS["influxdb"]["org"], processed)
if result is not None:
log_process(f"Wrote {len(processed)} data points")
except Exception as e:
# write to file
log_error(f"Error writing to influxdb: {e}")
return [1, f"Error writing to influxdb: {e}"]
success_count = len(processed)
# free up memory
del data
del processed
del timestamp
return [0, f"Wrote {success_count} data points successfully"]
has_call_finished # noqa imported functions
get_call_value # noqa imported functions

View File

@@ -0,0 +1 @@
influxdb-client

View File

@@ -0,0 +1,80 @@
import sys
import threading
# https://stackoverflow.com/a/65447493/6543759
class ThreadWithResult(threading.Thread):
def __init__(
self, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None
):
self.exc = None
if not kwargs:
kwargs = {}
def function():
self.exc = None
try:
self.result = target(*args, **kwargs)
except: # noqa
# Save details of the exception thrown but don't rethrow,
# just complete the function
self.exc = sys.exc_info()
super().__init__(group=group, target=function, name=name, daemon=daemon)
# https://stackoverflow.com/a/12223550/6543759
def join(self, *args, **kwargs):
super().join(*args, **kwargs)
if self.exc:
msg = "Thread '%s' threw an exception: %s" % (self.getName(), self.exc[1])
new_exc = Exception(msg)
raise new_exc.with_traceback(self.exc[2])
THREADS = {}
THREAD_ID = 0
def call_slow_function(function, args):
global THREADS, THREAD_ID
thread = ThreadWithResult(target=function, args=args, daemon=True)
THREAD_ID += 1
THREADS[THREAD_ID] = thread
thread.start()
return THREAD_ID
def has_call_finished(thread_id):
global THREADS
thread = THREADS[thread_id]
if thread.is_alive():
# Thread is still working
return False
# Thread has finished, we can return its value using get_call_value()
return True
def get_call_value(thread_id):
global THREADS
thread = THREADS[thread_id]
if thread.is_alive():
# Thread is still working
raise ValueError("Thread is still running!")
# Thread has finished, we can return its value now
try:
thread.join()
finally:
del THREADS[thread_id]
try:
return thread.result
except AttributeError:
raise RuntimeError(
'The thread does not have the "result" attribute. An unhandled error occurred inside your Thread'
)