Search in sources :

Example 1 with MasterEnvironmentRunnable

use of io.cdap.cdap.master.spi.environment.MasterEnvironmentRunnable in project cdap by caskdata.

the class MasterEnvironmentMain method doMain.

/**
 * The actual main method that get invoke through reflection from the {@link #main(String[])} method.
 */
@SuppressWarnings("unused")
public static void doMain(String[] args) throws Exception {
    CountDownLatch shutdownLatch = new CountDownLatch(1);
    try {
        // System wide setup
        Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler());
        // Intercept JUL loggers
        SLF4JBridgeHandler.removeHandlersForRootLogger();
        SLF4JBridgeHandler.install();
        EnvironmentOptions options = new EnvironmentOptions();
        String[] runnableArgs = OptionsParser.init(options, args, MasterEnvironmentMain.class.getSimpleName(), ProjectInfo.getVersion().toString(), System.out).toArray(new String[0]);
        String runnableClass = options.getRunnableClass();
        if (runnableClass == null) {
            throw new IllegalArgumentException("Missing runnable class name");
        }
        CConfiguration cConf = CConfiguration.create();
        SConfiguration sConf = SConfiguration.create();
        if (options.getExtraConfPath() != null) {
            cConf.addResource(new File(options.getExtraConfPath(), "cdap-site.xml").toURI().toURL());
            sConf.addResource(new File(options.getExtraConfPath(), "cdap-security.xml").toURI().toURL());
        }
        SecurityUtil.loginForMasterService(cConf);
        Configuration hConf = new Configuration();
        // Creates the master environment and load the MasterEnvironmentRunnable class from it.
        MasterEnvironment masterEnv = MasterEnvironments.setMasterEnvironment(MasterEnvironments.create(cConf, options.getEnvProvider()));
        MasterEnvironmentContext context = MasterEnvironments.createContext(cConf, hConf, masterEnv.getName());
        masterEnv.initialize(context);
        try {
            Class<?> cls = masterEnv.getClass().getClassLoader().loadClass(runnableClass);
            if (!MasterEnvironmentRunnable.class.isAssignableFrom(cls)) {
                throw new IllegalArgumentException("Runnable class " + runnableClass + " is not an instance of " + MasterEnvironmentRunnable.class);
            }
            RemoteClientFactory remoteClientFactory = new RemoteClientFactory(masterEnv.getDiscoveryServiceClientSupplier().get(), getInternalAuthenticator(cConf), getRemoteAuthenticator(cConf));
            MasterEnvironmentRunnableContext runnableContext = new DefaultMasterEnvironmentRunnableContext(context.getLocationFactory(), remoteClientFactory);
            @SuppressWarnings("unchecked") MasterEnvironmentRunnable runnable = masterEnv.createRunnable(runnableContext, (Class<? extends MasterEnvironmentRunnable>) cls);
            AtomicBoolean completed = new AtomicBoolean();
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                if (!completed.get()) {
                    runnable.stop();
                    Uninterruptibles.awaitUninterruptibly(shutdownLatch, 30, TimeUnit.SECONDS);
                }
                Optional.ofNullable(tokenManager).ifPresent(TokenManager::stopAndWait);
            }));
            runnable.run(runnableArgs);
            completed.set(true);
        } finally {
            masterEnv.destroy();
        }
    } catch (Exception e) {
        LOG.error("Failed to execute with arguments {}", Arrays.toString(args), e);
        throw e;
    } finally {
        shutdownLatch.countDown();
    }
}
Also used : RemoteClientFactory(io.cdap.cdap.common.internal.remote.RemoteClientFactory) Configuration(org.apache.hadoop.conf.Configuration) CConfiguration(io.cdap.cdap.common.conf.CConfiguration) SConfiguration(io.cdap.cdap.common.conf.SConfiguration) MasterEnvironmentRunnable(io.cdap.cdap.master.spi.environment.MasterEnvironmentRunnable) CountDownLatch(java.util.concurrent.CountDownLatch) CConfiguration(io.cdap.cdap.common.conf.CConfiguration) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MasterEnvironmentContext(io.cdap.cdap.master.spi.environment.MasterEnvironmentContext) MasterEnvironment(io.cdap.cdap.master.spi.environment.MasterEnvironment) SConfiguration(io.cdap.cdap.common.conf.SConfiguration) UncaughtExceptionHandler(io.cdap.cdap.common.logging.common.UncaughtExceptionHandler) File(java.io.File) DefaultMasterEnvironmentRunnableContext(io.cdap.cdap.master.environment.DefaultMasterEnvironmentRunnableContext) MasterEnvironmentRunnableContext(io.cdap.cdap.master.spi.environment.MasterEnvironmentRunnableContext) DefaultMasterEnvironmentRunnableContext(io.cdap.cdap.master.environment.DefaultMasterEnvironmentRunnableContext)

Example 2 with MasterEnvironmentRunnable

use of io.cdap.cdap.master.spi.environment.MasterEnvironmentRunnable in project cdap by caskdata.

the class KubeTwillPreparer method createContainer.

/**
 * Creates a {@link V1Container} specification for running a {@link MasterEnvironmentRunnable} in a container.
 */
private V1Container createContainer(String name, String containerImage, String imagePullPolicy, String workDir, V1ResourceRequirements resourceRequirements, List<V1VolumeMount> volumeMounts, Map<String, String> environments, Class<? extends MasterEnvironmentRunnable> runnableClass, String... args) {
    Map<String, String> environs = new HashMap<>(environments);
    // Set the environments for controlling the working directory
    environs.put("CDAP_LOCAL_DIR", workDir);
    environs.put("CDAP_TEMP_DIR", "tmp");
    // Set the process memory is through the JAVA_HEAPMAX variable.
    environs.put("JAVA_HEAPMAX", String.format("-Xmx%dm", computeMaxHeapSize(resourceRequirements)));
    List<V1EnvVar> containerEnvironments = environs.entrySet().stream().map(e -> new V1EnvVar().name(e.getKey()).value(e.getValue())).collect(Collectors.toList());
    V1ContainerBuilder builder = new V1ContainerBuilder();
    if (containerSecurityContexts.containsKey(name)) {
        builder.withSecurityContext(containerSecurityContexts.get(name));
    }
    List<V1VolumeMount> containerVolumeMounts = new ArrayList<>();
    for (V1VolumeMount mount : volumeMounts) {
        if (readonlyDisks.containsKey(name) && readonlyDisks.get(name).contains(mount.getName())) {
            containerVolumeMounts.add(new V1VolumeMount().readOnly(true).name(mount.getName()).mountPath(mount.getMountPath()).mountPropagation(mount.getMountPropagation()).subPath(mount.getSubPath()).subPathExpr(mount.getSubPathExpr()));
        } else {
            containerVolumeMounts.add(mount);
        }
    }
    return builder.withName(cleanse(name, 254)).withImage(containerImage).withWorkingDir(workDir).withResources(resourceRequirements).withImagePullPolicy(imagePullPolicy).addAllToVolumeMounts(containerVolumeMounts).addAllToEnv(containerEnvironments).addToArgs(masterEnvContext.getRunnableArguments(runnableClass, args)).build();
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Arrays(java.util.Arrays) TypeToken(com.google.gson.reflect.TypeToken) BatchV1Api(io.kubernetes.client.openapi.apis.BatchV1Api) V1ResourceRequirements(io.kubernetes.client.openapi.models.V1ResourceRequirements) SecureStore(org.apache.twill.api.SecureStore) DirectoryStream(java.nio.file.DirectoryStream) V1EnvVar(io.kubernetes.client.openapi.models.V1EnvVar) DefaultLocalFile(org.apache.twill.internal.DefaultLocalFile) Configs(org.apache.twill.api.Configs) Map(java.util.Map) V1VolumeMount(io.kubernetes.client.openapi.models.V1VolumeMount) Path(java.nio.file.Path) V1PersistentVolumeClaimBuilder(io.kubernetes.client.openapi.models.V1PersistentVolumeClaimBuilder) RuntimeSpecification(org.apache.twill.api.RuntimeSpecification) V1Volume(io.kubernetes.client.openapi.models.V1Volume) TwillController(org.apache.twill.api.TwillController) LocalFile(org.apache.twill.api.LocalFile) SecretDisk(io.cdap.cdap.master.spi.twill.SecretDisk) DefaultRuntimeSpecification(org.apache.twill.internal.DefaultRuntimeSpecification) Set(java.util.Set) StandardCharsets(java.nio.charset.StandardCharsets) Stream(java.util.stream.Stream) V1SecurityContextBuilder(io.kubernetes.client.openapi.models.V1SecurityContextBuilder) MasterEnvironmentContext(io.cdap.cdap.master.spi.environment.MasterEnvironmentContext) V1PersistentVolumeClaim(io.kubernetes.client.openapi.models.V1PersistentVolumeClaim) LogHandler(org.apache.twill.api.logging.LogHandler) V1Deployment(io.kubernetes.client.openapi.models.V1Deployment) StatefulDisk(io.cdap.cdap.master.spi.twill.StatefulDisk) Location(org.apache.twill.filesystem.Location) V1Job(io.kubernetes.client.openapi.models.V1Job) Paths(org.apache.twill.internal.utils.Paths) StatefulTwillPreparer(io.cdap.cdap.master.spi.twill.StatefulTwillPreparer) AppsV1Api(io.kubernetes.client.openapi.apis.AppsV1Api) ApiClient(io.kubernetes.client.openapi.ApiClient) BufferedOutputStream(java.io.BufferedOutputStream) ArrayList(java.util.ArrayList) V1EmptyDirVolumeSource(io.kubernetes.client.openapi.models.V1EmptyDirVolumeSource) TwillRuntimeSpecification(org.apache.twill.internal.TwillRuntimeSpecification) V1ObjectMeta(io.kubernetes.client.openapi.models.V1ObjectMeta) TwillRuntimeSpecificationAdapter(org.apache.twill.internal.json.TwillRuntimeSpecificationAdapter) ClassAcceptor(org.apache.twill.api.ClassAcceptor) SecureTwillPreparer(io.cdap.cdap.master.spi.twill.SecureTwillPreparer) Resources(com.google.common.io.Resources) Files(java.nio.file.Files) V1PodSpecBuilder(io.kubernetes.client.openapi.models.V1PodSpecBuilder) IOException(java.io.IOException) V1ResourceRequirementsBuilder(io.kubernetes.client.openapi.models.V1ResourceRequirementsBuilder) LogOnlyEventHandler(org.apache.twill.internal.LogOnlyEventHandler) DefaultTwillSpecification(org.apache.twill.internal.DefaultTwillSpecification) TwillRunnable(org.apache.twill.api.TwillRunnable) V1ObjectMetaBuilder(io.kubernetes.client.openapi.models.V1ObjectMetaBuilder) TwillRunnableSpecification(org.apache.twill.api.TwillRunnableSpecification) JsonObject(com.google.gson.JsonObject) PodInfo(io.cdap.cdap.master.environment.k8s.PodInfo) URL(java.net.URL) TwillPreparer(org.apache.twill.api.TwillPreparer) LoggerFactory(org.slf4j.LoggerFactory) V1DeploymentBuilder(io.kubernetes.client.openapi.models.V1DeploymentBuilder) V1DownwardAPIVolumeSource(io.kubernetes.client.openapi.models.V1DownwardAPIVolumeSource) V1SecurityContext(io.kubernetes.client.openapi.models.V1SecurityContext) Gson(com.google.gson.Gson) V1StatefulSet(io.kubernetes.client.openapi.models.V1StatefulSet) RunId(org.apache.twill.api.RunId) Quantity(io.kubernetes.client.custom.Quantity) URI(java.net.URI) V1ObjectFieldSelector(io.kubernetes.client.openapi.models.V1ObjectFieldSelector) V1StatefulSetBuilder(io.kubernetes.client.openapi.models.V1StatefulSetBuilder) Collection(java.util.Collection) ResourceSpecification(org.apache.twill.api.ResourceSpecification) V1LabelSelector(io.kubernetes.client.openapi.models.V1LabelSelector) Collectors(java.util.stream.Collectors) List(java.util.List) Type(java.lang.reflect.Type) Writer(java.io.Writer) Annotation(java.lang.annotation.Annotation) SecurityContext(io.cdap.cdap.master.spi.twill.SecurityContext) Optional(java.util.Optional) V1JobBuilder(io.kubernetes.client.openapi.models.V1JobBuilder) LogEntry(org.apache.twill.api.logging.LogEntry) Completable(io.cdap.cdap.master.spi.twill.Completable) Hashing(com.google.common.hash.Hashing) HashMap(java.util.HashMap) HashSet(java.util.HashSet) ApiException(io.kubernetes.client.openapi.ApiException) JarEntry(java.util.jar.JarEntry) Constants(org.apache.twill.internal.Constants) V1Container(io.kubernetes.client.openapi.models.V1Container) V1DownwardAPIVolumeFile(io.kubernetes.client.openapi.models.V1DownwardAPIVolumeFile) JarOutputStream(java.util.jar.JarOutputStream) OutputStream(java.io.OutputStream) V1ContainerBuilder(io.kubernetes.client.openapi.models.V1ContainerBuilder) Logger(org.slf4j.Logger) KubeMasterEnvironment(io.cdap.cdap.master.environment.k8s.KubeMasterEnvironment) V1SecretVolumeSource(io.kubernetes.client.openapi.models.V1SecretVolumeSource) TimeUnit(java.util.concurrent.TimeUnit) DependentTwillPreparer(io.cdap.cdap.master.spi.twill.DependentTwillPreparer) V1PodSpec(io.kubernetes.client.openapi.models.V1PodSpec) AbstractMap(java.util.AbstractMap) TwillSpecification(org.apache.twill.api.TwillSpecification) MasterEnvironmentRunnable(io.cdap.cdap.master.spi.environment.MasterEnvironmentRunnable) Collections(java.util.Collections) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) V1ContainerBuilder(io.kubernetes.client.openapi.models.V1ContainerBuilder) V1EnvVar(io.kubernetes.client.openapi.models.V1EnvVar) V1VolumeMount(io.kubernetes.client.openapi.models.V1VolumeMount)

Aggregations

MasterEnvironmentContext (io.cdap.cdap.master.spi.environment.MasterEnvironmentContext)2 MasterEnvironmentRunnable (io.cdap.cdap.master.spi.environment.MasterEnvironmentRunnable)2 Hashing (com.google.common.hash.Hashing)1 Resources (com.google.common.io.Resources)1 Gson (com.google.gson.Gson)1 JsonObject (com.google.gson.JsonObject)1 TypeToken (com.google.gson.reflect.TypeToken)1 CConfiguration (io.cdap.cdap.common.conf.CConfiguration)1 SConfiguration (io.cdap.cdap.common.conf.SConfiguration)1 RemoteClientFactory (io.cdap.cdap.common.internal.remote.RemoteClientFactory)1 UncaughtExceptionHandler (io.cdap.cdap.common.logging.common.UncaughtExceptionHandler)1 DefaultMasterEnvironmentRunnableContext (io.cdap.cdap.master.environment.DefaultMasterEnvironmentRunnableContext)1 KubeMasterEnvironment (io.cdap.cdap.master.environment.k8s.KubeMasterEnvironment)1 PodInfo (io.cdap.cdap.master.environment.k8s.PodInfo)1 MasterEnvironment (io.cdap.cdap.master.spi.environment.MasterEnvironment)1 MasterEnvironmentRunnableContext (io.cdap.cdap.master.spi.environment.MasterEnvironmentRunnableContext)1 Completable (io.cdap.cdap.master.spi.twill.Completable)1 DependentTwillPreparer (io.cdap.cdap.master.spi.twill.DependentTwillPreparer)1 SecretDisk (io.cdap.cdap.master.spi.twill.SecretDisk)1 SecureTwillPreparer (io.cdap.cdap.master.spi.twill.SecureTwillPreparer)1