package com.css.simulation.resource.scheduler.infra.scheduler;

import api.common.util.SshUtil;
import com.css.simulation.resource.scheduler.infra.configuration.docker.DockerConfiguration;
import com.css.simulation.resource.scheduler.infra.db.mysql.mapper.AlgorithmMapper;
import com.css.simulation.resource.scheduler.infra.entity.AlgorithmEntity;
import com.css.simulation.resource.scheduler.infra.configuration.entity.DockerNodeEntity;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.session.ClientSession;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class AlgorithmScheduler {

    @Resource
    private DockerConfiguration dockerConfiguration;
    @Resource
    private AlgorithmMapper algorithmMapper;


    /**
     * 定时删除算法镜像
     */
    @Scheduled(fixedDelay = 60 * 60 * 1000)
    @SneakyThrows
    public void removeAlgorithmImage() {
        int maxAlgorithmImage = dockerConfiguration.getMaxAlgorithmImage();
        int minAlgorithmImage = dockerConfiguration.getMinAlgorithmImage();
        //1 查询已经导入的算法，根据创建时间排序
        List<AlgorithmEntity> algorithmImportedList = algorithmMapper.selectByDockerImport("1");
        int algorithmImportNumber = algorithmImportedList.size();
        if (algorithmImportNumber >= maxAlgorithmImage) {
            log.info("kubernetes 各个节点已经导入 " + algorithmImportNumber + " 个算法，上限为 30，已超出。");
            //2 如果已经导入到 docker 中的算法镜像已经达到 maxAlgorithmImage 个，则清理算法镜像到 minAlgorithmImage 个；
            List<String> algorithmIdToUpdateList = new ArrayList<>();
            StringBuilder dockerRmiCommand = new StringBuilder("docker rmi ");
            for (int i = minAlgorithmImage; i < algorithmImportedList.size(); i++) {
                AlgorithmEntity tempAlgorithm = algorithmImportedList.get(i);
                algorithmIdToUpdateList.add(tempAlgorithm.getId());
                dockerRmiCommand.append(tempAlgorithm.getDockerImage());
            }
            //3 修改数据库为未导入
            algorithmMapper.updateDockerImportAndDockerImageByIdList("0", "", algorithmIdToUpdateList);
            //4 删除镜像
            List<DockerNodeEntity> nodeList = dockerConfiguration.getNodeList();
            for (DockerNodeEntity dockerNodeEntity : nodeList) {
                String hostname = dockerNodeEntity.getHostname();
                String username = dockerNodeEntity.getUsername();
                String password = dockerNodeEntity.getPassword();
                SshClient client = SshUtil.getClient();
                ClientSession session = SshUtil.getSession(client, hostname, username, password);
                SshUtil.execute(session, dockerRmiCommand.toString());
                SshUtil.stop(client, session);
            }
        }
    }
}
