mattshma / bigdata

hadoop,hbase,storm,spark,etc..

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

kubernetes create hook

mattshma opened this issue · comments

kubernetes 在启动后或关闭前可添加hook来执行特定操作,比如用户安装的 pip 包,在关闭前通过 preStop 先执行 pip freeze > /X/requirements.txt 操作,其中 /X 为共享存储路径,如 ceph 等。在启动后,再通过 postStart 执行 pip install -r /X/requirements.txt。这种可保证用户安装的 pip 不丢失。

关于 kubernetes lifecyle hook 此不赘述,可参考 container-lifecycle-hooks。在调用 API 创建 hook 时,需记住 lifecycle 都是在 container 创建时设置的,而非关闭时才设置 preStop。以下是 Java Demo:

            Lifecycle lifecycle = new Lifecycle();
            if (containerPojo.getLabel().indexOf("Jupyter") != -1) {
                // set postStart hook
                Handler postStartHandler = new Handler();
                List<String> startCmd = new ArrayList<>();
                startCmd.add("/bin/sh");
                startCmd.add("-c");
                startCmd.add("/post_start.sh");
                lifecycle.setPostStart(postStartHandler);

                // set preStop handler
                Handler preStopHandler = new Handler();
                List<String> stopCmd = new ArrayList<>();
                stopCmd.add("/bin/sh");
                stopCmd.add("-c");
                stopCmd.add("/pre_stop.sh");
                ExecAction execAction = new ExecAction(stopCmd);
                preStopHandler.setExec(execAction);
                lifecycle.setPreStop(preStopHandler);
            }
            ContainerBuilder containerBuilder = new ContainerBuilder()
                    .withName(name)
                    .withImage(image)
                    .withLifecycle(lifecycle)
                    .withResources(resources)
                    .withEnv(env)
                    .withVolumeMounts(volumeMounts)
                    .withPorts(port);
            Container container = containerBuilder.build();

对于 pre_stop.sh, post_start.sh,需在 Dockerfile 中拷贝到容器中;当然这 pre_stop.sh, post_start.sh也可真为 shell 命令。