importlombok.extern.slf4j.Slf4j;importorg.apache.flink.client.cli.CliFrontend;importorg.apache.flink.client.cli.CustomCommandLine;importorg.apache.flink.client.cli.DefaultCLI;importorg.apache.flink.client.cli.GenericCLI;importorg.apache.flink.client.deployment.ClusterDeploymentException;importorg.apache.flink.client.deployment.ClusterSpecification;importorg.apache.flink.client.deployment.application.ApplicationConfiguration;importorg.apache.flink.client.program.ClusterClientProvider;importorg.apache.flink.configuration.*;importorg.apache.flink.runtime.security.SecurityConfiguration;importorg.apache.flink.runtime.security.SecurityUtils;importorg.apache.flink.util.ExceptionUtils;importorg.apache.flink.yarn.YarnClientYarnClusterInformationRetriever;importorg.apache.flink.yarn.YarnClusterDescriptor;importorg.apache.flink.yarn.YarnClusterInformationRetriever;importorg.apache.flink.yarn.configuration.YarnConfigOptions;importorg.apache.flink.yarn.configuration.YarnDeploymentTarget;importorg.apache.hadoop.fs.Path;importorg.apache.hadoop.yarn.api.records.ApplicationId;importorg.apache.hadoop.yarn.client.api.YarnClient;importorg.apache.hadoop.yarn.conf.YarnConfiguration;importorg.junit.Test;importjava.io.File;importjava.lang.reflect.Constructor;importjava.lang.reflect.UndeclaredThrowableException;importjava.util.ArrayList;importjava.util.Collections;importjava.util.List;importjava.util.Optional;importstaticorg.apache.flink.util.Preconditions.checkNotNull;@Slf4jpublicclassAppTestV1{@TestpublicvoidsubmitJobWithYarnDesc()throwsClusterDeploymentException{// hadoopString hadoopConfDir ="C:\\Users\\HPN-21-117\\software\\configClusterhadoop\\configurations\\cdh5";// String hadoopConfDir = "C:\\Users\\HPN-21-117\\software\\configClusterhadoop\\configurations\\cdh6";//flink的本地配置目录,为了得到flink的配置String flinkConfDir ="C:\\Users\\HPN-21-117\\software\\flink-1.12.7\\conf";//存放flink集群相关的jar包目录String flinkLibs ="hdfs://cdh-node0.hypers.com:8020/flink/1.12.7/lib";//用户jarString userJarPath ="hdfs://cdh-node0.hypers.com:8020/flink/demo/TopSpeedWindowing.jar";String flinkDistJar ="hdfs://cdh-node0.hypers.com:8020/flink/1.12.7/lib/flink-dist_2.12-1.12.7.jar";// String flinkDistJar = "hdfs://cdh-node0.hypers.com:8022/flink/lib";String[] args ="".split("\\s+");String appMainClass ="org.apache.flink.streaming.examples.windowing.TopSpeedWindowing";YarnClient yarnClient =YarnUtils.getYarnClient(hadoopConfDir);
yarnClient.start();Configuration flinkConf =GlobalConfiguration.loadConfiguration(flinkConfDir);//set run model
flinkConf.setString(DeploymentOptions.TARGET,YarnDeploymentTarget.APPLICATION.getName());//set application name
flinkConf.setString(YarnConfigOptions.APPLICATION_NAME,"onYarnApiSubmitCase");//flink on yarn dependency
flinkConf.set(YarnConfigOptions.PROVIDED_LIB_DIRS,Collections.singletonList(newPath(flinkLibs).toString()));
flinkConf.set(YarnConfigOptions.FLINK_DIST_JAR, flinkDistJar);
flinkConf.set(PipelineOptions.JARS,Collections.singletonList(newPath(userJarPath).toString()));//设置:资源/并发度
flinkConf.setInteger(CoreOptions.DEFAULT_PARALLELISM,1);
flinkConf.set(JobManagerOptions.TOTAL_PROCESS_MEMORY,MemorySize.parse("1G"));
flinkConf.set(TaskManagerOptions.TOTAL_PROCESS_MEMORY,MemorySize.parse("1G"));
flinkConf.setInteger(TaskManagerOptions.NUM_TASK_SLOTS,1);ClusterSpecification clusterSpecification =newClusterSpecification
.ClusterSpecificationBuilder().setMasterMemoryMB(1024).setTaskManagerMemoryMB(1024).setSlotsPerTaskManager(2).createClusterSpecification();YarnClusterInformationRetriever ycir =YarnClientYarnClusterInformationRetriever.create(yarnClient);YarnConfiguration yarnConf =(YarnConfiguration) yarnClient.getConfig();ApplicationConfiguration appConfig =newApplicationConfiguration(args, appMainClass);YarnClusterDescriptor yarnClusterDescriptor =newYarnClusterDescriptor(
flinkConf,
yarnConf,
yarnClient,
ycir,false);ClusterClientProvider<ApplicationId> applicationCluster =
yarnClusterDescriptor.deployApplicationCluster( clusterSpecification, appConfig );
yarnClient.stop();}@TestpublicvoidsubmitJobWithCliForte()throwsException{System.setProperty("ENV_FLINK_CONF_DIR","C:\\Users\\HPN-21-117\\software\\flink-1.14.6\\conf");System.setProperty("FLINK_CONF_DIR","C:\\Users\\HPN-21-117\\software\\flink-1.14.6\\conf");// 1. find the configuration directoryfinalString configurationDirectory =getConfigurationDirectoryFromDir("C:\\Users\\HPN-21-117\\software\\flink-1.14.6\\conf");// 2. load the global configurationfinalConfiguration configuration =GlobalConfiguration.loadConfiguration(configurationDirectory);// 3. load the custom command linesfinalList<CustomCommandLine> customCommandLines =loadCustomCommandLines(configuration, configurationDirectory);try{finalCliFrontend cli =newCliFrontend(configuration, customCommandLines);SecurityUtils.install(newSecurityConfiguration(cli.getConfiguration()));String[] args ="run-application -t yarn-application hdfs://cdh-node0.hypers.com:8022/flink/demo/TopSpeedWindowing.jar".split("\\s+");int retCode =SecurityUtils.getInstalledContext().runSecured(()-> cli.parseAndRun(args));System.exit(retCode);}catch(Throwable t){finalThrowable strippedThrowable =ExceptionUtils.stripException(t,UndeclaredThrowableException.class);
log.error("Fatal error while running command line interface.", strippedThrowable);
strippedThrowable.printStackTrace();System.exit(31);}}publicstaticList<CustomCommandLine>loadCustomCommandLines(Configuration configuration,String configurationDirectory){List<CustomCommandLine> customCommandLines =newArrayList<>();
customCommandLines.add(newGenericCLI(configuration, configurationDirectory));// Command line interface of the YARN session, with a special initialization here// to prefix all options with y/yarn.finalString flinkYarnSessionCLI ="org.apache.flink.yarn.cli.FlinkYarnSessionCli";try{
customCommandLines.add(loadCustomCommandLine(
flinkYarnSessionCLI,
configuration,
configurationDirectory,"y","yarn"));}catch(NoClassDefFoundError|Exception e){finalString errorYarnSessionCLI ="org.apache.flink.yarn.cli.FallbackYarnSessionCli";try{
log.info("Loading FallbackYarnSessionCli");
customCommandLines.add(loadCustomCommandLine(errorYarnSessionCLI, configuration));}catch(Exception exception){
log.warn("Could not load CLI class {}.", flinkYarnSessionCLI, e);}}// Tips: DefaultCLI must be added at last, because getActiveCustomCommandLine(..) will get// the// active CustomCommandLine in order and DefaultCLI isActive always return true.
customCommandLines.add(newDefaultCLI());return customCommandLines;}/**
* Loads a class from the classpath that implements the CustomCommandLine interface.
*
* @param className The fully-qualified class name to load.
* @param params The constructor parameters
*/privatestaticCustomCommandLineloadCustomCommandLine(String className,Object... params)throwsException{Class<?extendsCustomCommandLine> customCliClass =Class.forName(className).asSubclass(CustomCommandLine.class);// construct class types from the parametersClass<?>[] types =newClass<?>[params.length];for(int i =0; i < params.length; i++){checkNotNull(params[i],"Parameters for custom command-lines may not be null.");
types[i]= params[i].getClass();}Constructor<?extendsCustomCommandLine> constructor = customCliClass.getConstructor(types);return constructor.newInstance(params);}publicstaticStringgetConfigurationDirectoryFromDir(String env_flink_conf_dir){// String env_flink_conf_dir = System.getenv(flinkConfDir);String location =Optional.ofNullable(env_flink_conf_dir).filter(dir ->newFile(dir).exists()).orElseThrow(()->newRuntimeException("The configuration directory '"+ env_flink_conf_dir
+"', specified in the '"+ConfigConstants.ENV_FLINK_CONF_DIR+"' environment variable, does not exist."));return location;}publicstaticStringgetConfigurationDirectoryFromEnv(){System.setProperty("MY_VAR","value");String env_flink_conf_dir =System.getenv(ConfigConstants.ENV_FLINK_CONF_DIR);String location =Optional.ofNullable(env_flink_conf_dir).filter(dir ->newFile(dir).exists()).orElseThrow(()->newRuntimeException("The configuration directory '"+ env_flink_conf_dir
+"', specified in the '"+ConfigConstants.ENV_FLINK_CONF_DIR+"' environment variable, does not exist."));return location;}}