package com.sequenceiq.cloudbreak.websocket;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.sequenceiq.cloudbreak.domain.Cluster;
import com.sequenceiq.cloudbreak.domain.Stack;
import com.sequenceiq.cloudbreak.domain.WebsocketEndPoint;
import com.sequenceiq.cloudbreak.repository.ClusterRepository;
import com.sequenceiq.cloudbreak.repository.StackRepository;
import com.sequenceiq.cloudbreak.websocket.message.UptimeMessage;
@Component
public class UptimeNotifier {
@Autowired
private WebsocketService websocketService;
@Autowired
private ClusterRepository clusterRepository;
@Autowired
private StackRepository stackRepository;
@Scheduled(fixedDelay = 60000)
public void sendUptime() {
Map<String, List<UptimeMessage>> uptimes = new HashMap<>();
List<Cluster> clusters = (List<Cluster>) clusterRepository.findAll();
long now = new Date().getTime();
for (Cluster cluster : clusters) {
Stack stack = stackRepository.findStackForCluster(cluster.getId());
if (stack != null) {
Long uptime = cluster.getCreationFinished() == null ? 0L : now - cluster.getCreationFinished();
if (uptimes.containsKey(stack.getOwner())) {
uptimes.get(stack.getOwner()).add(new UptimeMessage(stack.getId(), uptime));
} else {
uptimes.put(stack.getOwner(), new ArrayList<UptimeMessage>());
uptimes.get(stack.getOwner()).add(new UptimeMessage(stack.getId(), uptime));
}
}
}
if (!uptimes.isEmpty()) {
for (Map.Entry<String, List<UptimeMessage>> longListEntry : uptimes.entrySet()) {
websocketService.sendToTopicUser(longListEntry.getKey(), WebsocketEndPoint.UPTIME, longListEntry.getValue());
}
}
}
}