Skip to content

An open source, self-hosted, real-time port monitoring and discovery tool.

Fix #98 (#99)

Roberto Leinardicf1b05542bc3
diff --git a/backend/collectors/base_collector.js b/backend/collectors/base_collector.js
index 921721d..5daceff 100644
--- a/backend/collectors/base_collector.js
+++ b/backend/collectors/base_collector.js
@@ -240,6 +240,92 @@ class BaseCollector {
clearAllCache() {
this._cache.clear();
}
+
+ /**
+ * Extract Docker Swarm / Compose label metadata from a container's label map.
+ * @param {Object} labels The container's Labels object (may be null/undefined)
+ * @param {string} containerName Fallback owner name when no swarm service is present
+ * @returns {{ swarmServiceName: string|null, stackNamespace: string|null,
+ * composeProject: string|null, composeService: string|null,
+ * effectiveOwner: string }}
+ */
+ _extractSwarmLabels(labels, containerName) {
+ const swarmServiceName = labels?.['com.docker.swarm.service.name'] || null;
+ const stackNamespace = labels?.['com.docker.stack.namespace'] || null;
+ const composeProject = labels?.['com.docker.compose.project'] || stackNamespace || null;
+ let composeService = labels?.['com.docker.compose.service'] || null;
+ if (!composeService && swarmServiceName) {
+ composeService = (stackNamespace && swarmServiceName.startsWith(stackNamespace + '_'))
+ ? swarmServiceName.slice(stackNamespace.length + 1)
+ : swarmServiceName;
+ }
+ return {
+ swarmServiceName,
+ stackNamespace,
+ composeProject,
+ composeService,
+ effectiveOwner: swarmServiceName || containerName,
+ };
+ }
+
+ /**
+ * Get Docker Swarm service ports (ingress and host publish modes).
+ * These ports are managed at the service layer and do not appear in
+ * container-level port bindings, so they require separate discovery.
+ * Requires `this.dockerApi` to be set by the subclass constructor.
+ * @returns {Promise<Array>} Swarm service port entries
+ * @private
+ */
+ async _getSwarmServicePorts() {
+ try {
+ const systemInfo = await this.dockerApi.getSystemInfo();
+ if (systemInfo?.Swarm?.LocalNodeState !== 'active') {
+ return [];
+ }
+
+ const services = await this.dockerApi.listServices();
+ const portEntries = [];
+
+ for (const service of services) {
+ const serviceId = service.ID;
+ const serviceName = service.Spec?.Name || serviceId;
+ const labels = service.Spec?.Labels || {};
+ const stackNamespace = labels['com.docker.stack.namespace'] || null;
+
+ let composeService = serviceName;
+ if (stackNamespace && serviceName.startsWith(stackNamespace + '_')) {
+ composeService = serviceName.slice(stackNamespace.length + 1);
+ }
+
+ const ports = service.Endpoint?.Ports || [];
+ for (const port of ports) {
+ if (!port.PublishedPort) continue;
+
+ portEntries.push(
+ this.normalizePortEntry({
+ source: 'docker',
+ owner: serviceName,
+ protocol: (port.Protocol || 'tcp').toLowerCase(),
+ host_ip: '0.0.0.0',
+ host_port: port.PublishedPort,
+ target: `${serviceId.substring(0, 12)}:${port.TargetPort}`,
+ container_id: null,
+ app_id: serviceName,
+ compose_project: stackNamespace,
+ compose_service: composeService,
+ pids: [],
+ })
+ );
+ }
+ }
+
+ this.logInfo(`Collected ${portEntries.length} Swarm service ports`);
+ return portEntries;
+ } catch (err) {
+ this.logWarn('Failed to get Swarm service ports:', err.message);
+ return [];
+ }
+ }
}
module.exports = BaseCollector;
diff --git a/backend/collectors/docker_collector.js b/backend/collectors/docker_collector.js
index 6efb662..96d731a 100644
--- a/backend/collectors/docker_collector.js
+++ b/backend/collectors/docker_collector.js
@@ -295,6 +295,16 @@ class DockerCollector extends BaseCollector {
}
});
+ const swarmPorts = await this._getSwarmServicePorts();
+ swarmPorts.forEach((port) => {
+ const normalizedIp = this._normalizeHostIp(port.host_ip);
+ const key = `${normalizedIp}:${port.host_port}:${port.protocol}`;
+ if (!dockerPortsMap.has(key)) {
+ dockerPortsMap.set(key, port);
+ allPorts.push(port);
+ }
+ });
+
const allRunningContainers = await this._getHostNetworkContainers();
allRunningContainers.forEach((container) => {
if (container.pids && container.pids.length > 0) {
@@ -410,9 +420,12 @@ class DockerCollector extends BaseCollector {
for (const container of containers) {
const containerName = container.Names;
const containerId = container.ID;
- const composeProject = container.Labels?.['com.docker.compose.project'] || null;
- const composeService = container.Labels?.['com.docker.compose.service'] || null;
-
+
+ // For swarm task containers, use the service name as the owner so host-mode
+ // published ports are attributed and grouped consistently with ingress services.
+ const { composeProject, composeService, effectiveOwner } =
+ this._extractSwarmLabels(container.Labels, containerName);
+
if (!container.Ports || container.Ports.length === 0) {
continue;
}
@@ -420,9 +433,9 @@ class DockerCollector extends BaseCollector {
const rawPorts = await this.dockerApi.docker.getContainer(container.ID).inspect();
const portBindings = rawPorts.NetworkSettings.Ports || {};
- for (const [containerPort, hostBindings] of Object.entries(portBindings)) {
+ for (const [containerPort, hostBindings] of Object.entries(portBindings)) {
if (!hostBindings) continue;
-
+
const [port, protocol] = containerPort.split('/');
const targetPort = parseInt(port, 10);
@@ -435,13 +448,13 @@ class DockerCollector extends BaseCollector {
portEntries.push(
this.normalizePortEntry({
source: "docker",
- owner: containerName,
+ owner: effectiveOwner,
protocol: protocol,
host_ip: hostIp,
host_port: hostPort,
target: `${containerId}:${targetPort}`,
container_id: containerId,
- app_id: containerName,
+ app_id: effectiveOwner,
compose_project: composeProject,
compose_service: composeService,
pids: [],
@@ -803,7 +816,7 @@ class DockerCollector extends BaseCollector {
}
this.logInfo(`Fallback /proc method: ${allPorts.length} ports found (TCP: ${tcpPorts.length}, UDP: ${udpPorts.length})`);
- return allPorts.map(port => this.normalizePortEntry(port));
+ return allPorts.map(port => this.normalizePortEntry({ source: port.source || 'system', ...port }));
}
}
} catch (procErr) {
diff --git a/backend/collectors/truenas_collector.js b/backend/collectors/truenas_collector.js
index 6d8c29d..d05ca29 100644
--- a/backend/collectors/truenas_collector.js
+++ b/backend/collectors/truenas_collector.js
@@ -699,8 +699,10 @@ class TrueNASCollector extends BaseCollector {
for (const container of containers) {
const containerName = this._formatContainerNames(container.Names);
const containerId = container.ID;
- const composeProject = container.Labels?.['com.docker.compose.project'] || null;
- const composeService = container.Labels?.['com.docker.compose.service'] || null;
+ // For swarm task containers, use the service name as the owner so host-mode
+ // published ports are attributed and grouped consistently with ingress services.
+ const { composeProject, composeService, effectiveOwner } =
+ this._extractSwarmLabels(container.Labels, containerName);
const rawPorts = await this.dockerApi.docker.getContainer(container.ID).inspect();
const portBindings = rawPorts.NetworkSettings.Ports || {};
@@ -708,9 +710,9 @@ class TrueNASCollector extends BaseCollector {
if (container.Ports && container.Ports.length > 0) {
for (const [containerPort, hostBindings] of Object.entries(portBindings)) {
if (!hostBindings) continue;
-
+
const [port, protocol] = containerPort.split('/');
-
+
for (const hostBinding of hostBindings) {
const hostIP = this._resolveHostIP(hostBinding.HostIp || '0.0.0.0');
const hostPort = hostBinding.HostPort;
@@ -724,14 +726,14 @@ class TrueNASCollector extends BaseCollector {
ports.push({
source: "docker",
- owner: containerName,
+ owner: effectiveOwner,
protocol: protocol || "tcp",
host_ip: hostIP,
host_port: parseInt(hostPort, 10),
target: port,
container_id: containerId,
vm_id: null,
- app_id: containerId,
+ app_id: effectiveOwner,
compose_project: composeProject,
compose_service: composeService,
});
@@ -751,14 +753,14 @@ class TrueNASCollector extends BaseCollector {
if (!isNaN(portNum) && !isPublished) {
ports.push({
source: "docker",
- owner: containerName,
+ owner: effectiveOwner,
protocol: protocol || "tcp",
host_ip: "0.0.0.0",
host_port: portNum,
target: `${containerId.substring(0, 12)}:${portNum}(internal)`,
container_id: containerId,
vm_id: null,
- app_id: containerId,
+ app_id: effectiveOwner,
internal: true,
compose_project: composeProject,
compose_service: composeService,
@@ -1245,6 +1247,25 @@ class TrueNASCollector extends BaseCollector {
try {
perf.start("docker-ports-collection");
const dockerPorts = await this._getDockerPorts();
+
+ // Merge Swarm service ports (ingress + host-mode published at service layer)
+ const swarmPorts = await this._getSwarmServicePorts();
+ const dockerPortsMap = new Map();
+ dockerPorts.forEach(p => {
+ const ip = this._resolveHostIP(p.host_ip);
+ const key = p.internal
+ ? `${p.container_id}:${p.host_port}:internal`
+ : `${ip}:${p.host_port}:${p.protocol || 'tcp'}`;
+ dockerPortsMap.set(key, p);
+ });
+ swarmPorts.forEach(p => {
+ const ip = this._resolveHostIP(p.host_ip);
+ const key = `${ip}:${p.host_port}:${p.protocol || 'tcp'}`;
+ if (!dockerPortsMap.has(key)) {
+ dockerPortsMap.set(key, p);
+ dockerPorts.push(p);
+ }
+ });
perf.end("docker-ports-collection");
const portsByContainer = new Map();
@@ -1354,7 +1375,7 @@ class TrueNASCollector extends BaseCollector {
const normalizedIp = this._resolveHostIP(port.host_ip);
if (port.internal && port.container_id) {
- const publishedKey = `${normalizedIp}:${port.host_port}`;
+ const publishedKey = `${normalizedIp}:${port.host_port}:${port.protocol || 'tcp'}`;
const existingPort = uniquePorts.get(publishedKey);
if (existingPort && existingPort.container_id === port.container_id) {
continue;
@@ -1363,7 +1384,7 @@ class TrueNASCollector extends BaseCollector {
const key = port.internal
? `${port.container_id}:${port.host_port}:internal`
- : `${normalizedIp}:${port.host_port}`;
+ : `${normalizedIp}:${port.host_port}:${port.protocol || 'tcp'}`;
port.host_ip = normalizedIp;
port.created =
containerCreationTimeMap.get(port.container_id) || null;
@@ -1372,7 +1393,7 @@ class TrueNASCollector extends BaseCollector {
for (const port of systemPorts) {
const normalizedIp = this._resolveHostIP(port.host_ip);
- const key = `${normalizedIp}:${port.host_port}`;
+ const key = `${normalizedIp}:${port.host_port}:${port.protocol || 'tcp'}`;
const portPid = getPrimaryPid(port);
port.host_ip = normalizedIp;
if (uniquePorts.has(key)) {
diff --git a/backend/lib/docker-api.js b/backend/lib/docker-api.js
index 434a2a1..9bf89ac 100644
--- a/backend/lib/docker-api.js
+++ b/backend/lib/docker-api.js
@@ -158,6 +158,19 @@ class DockerAPIClient {
});
}
+ async listServices(options = {}) {
+ await this._ensureConnected();
+ const key = `services:${JSON.stringify(options.filters || {})}`;
+ return await this.cache.getOrSet(key, this.ttl.containers, async () => {
+ try {
+ return await this.docker.listServices(options);
+ } catch (error) {
+ this.logger.error('listServices failed:', error.message);
+ throw error;
+ }
+ });
+ }
+
async inspectContainer(containerId, options = {}) {
await this._ensureConnected();
const useSize = options.size === true;