package com.nanri.aiimage.config; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; @Slf4j @Component public class InstanceMetadata { private final String instanceId; private final String hostname; private final String source; private final boolean stable; /** * 本进程的启动时刻。开机自回收用它当界:owner=本机且 status=RUNNING 的行若 * {@code updated_at} 早于这一刻,只可能是上一个进程留下的遗骸,不可能是本进程在跑的。 */ private final LocalDateTime startedAt; public InstanceMetadata(@Value("${aiimage.instance-id:}") String configuredInstanceId) { this.startedAt = LocalDateTime.ofInstant( Instant.ofEpochMilli(ManagementFactory.getRuntimeMXBean().getStartTime()), ZoneId.systemDefault()); this.hostname = resolveHostname(); String normalizedConfiguredInstanceId = configuredInstanceId == null ? "" : configuredInstanceId.trim(); if (!normalizedConfiguredInstanceId.isBlank()) { this.instanceId = normalizedConfiguredInstanceId; this.source = "configured"; this.stable = true; log.info("[instance] resolved instanceId={} source={} hostname={} continuityRisk=LOW", this.instanceId, this.source, this.hostname); } else { this.instanceId = this.hostname; this.source = detectFallbackSource(this.hostname); this.stable = false; log.warn("[instance] aiimage.instance-id is not configured, falling back to {}={} as instanceId. " + "This may change after restart/redeploy and break task owner continuity. " + "Set AIIMAGE_INSTANCE_ID in 1Panel/Docker env, or set -Daiimage.instance-id= in IDEA/local startup.", this.source, this.hostname); } } public String getInstanceId() { return instanceId; } public String getHostname() { return hostname; } public String getSource() { return source; } public boolean isStable() { return stable; } public LocalDateTime getStartedAt() { return startedAt; } private static String resolveHostname() { try { return InetAddress.getLocalHost().getHostName(); } catch (Exception ignored) { String envHostname = System.getenv("HOSTNAME"); return (envHostname == null || envHostname.isBlank()) ? "unknown-host" : envHostname; } } private static String detectFallbackSource(String hostname) { String envHostname = System.getenv("HOSTNAME"); if (envHostname != null && !envHostname.isBlank() && envHostname.equalsIgnoreCase(hostname)) { return "env.HOSTNAME"; } return "os.hostname"; } }