package com.lanyuanxiaoyao.service.executor;

import org.apache.flink.client.deployment.ClusterClientFactory;
import org.apache.flink.client.deployment.ClusterDescriptor;
import org.apache.flink.client.deployment.ClusterSpecification;
import org.apache.flink.client.deployment.DefaultClusterClientServiceLoader;
import org.apache.flink.client.deployment.application.ApplicationConfiguration;
import org.apache.flink.client.program.ClusterClient;
import org.apache.flink.client.program.ClusterClientProvider;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.security.SecurityConfiguration;
import org.apache.flink.runtime.security.SecurityUtils;
import org.apache.hadoop.yarn.api.records.ApplicationId;

/**
 * 启动类 #
 *
 * @author ZhangJiacheng
 * @date 2022-06-01
 */
public class Runner {
    public static ApplicationId run(Configuration inputConfiguration, String className, String[] args) throws Exception {
        Configuration configuration = new Configuration(inputConfiguration);
        SecurityUtils.install(new SecurityConfiguration(configuration));
        return SecurityUtils.getInstalledContext()
                .runSecured(() -> {
                    DefaultClusterClientServiceLoader yarnServiceLoader = new DefaultClusterClientServiceLoader();
                    ApplicationConfiguration applicationConfiguration = new ApplicationConfiguration(args, className);
                    //ApplicationDeployer deployer = new ApplicationClusterDeployer(new DefaultClusterClientServiceLoader());
                    //deployer.run(configuration, applicationConfiguration);
                    final ClusterClientFactory<ApplicationId> clientFactory = yarnServiceLoader.getClusterClientFactory(configuration);
                    try (final ClusterDescriptor<ApplicationId> clusterDescriptor = clientFactory.createClusterDescriptor(configuration)) {
                        final ClusterSpecification clusterSpecification = clientFactory.getClusterSpecification(configuration);
                        ClusterClientProvider<ApplicationId> provider = clusterDescriptor.deployApplicationCluster(clusterSpecification, applicationConfiguration);
                        ClusterClient<ApplicationId> clusterClient = provider.getClusterClient();
                        if (clusterClient == null) {
                            return null;
                        }
                        return clusterClient.getClusterId();
                    }
                });
    }
}
