springBoot整合harbor

<docker.version>3.2.13</docker.version>
<fastjson.version>1.2.75</fastjson.version>

<dependencies>
        <dependency>
            <groupId>com.github.docker-java</groupId>
            <artifactId>docker-java-core</artifactId>
            <version>${docker.version}</version>
        </dependency>
        <dependency>
            <groupId>com.github.docker-java</groupId>
            <artifactId>docker-java-transport-httpclient5</artifactId>
            <version>${docker.version}</version>
        </dependency>
        <dependency>
            <groupId>com.github.docker-java</groupId>
            <artifactId>docker-java</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.glassfish.jersey.connectors</groupId>
                    <artifactId>jersey-apache-connector</artifactId>
                </exclusion>
            </exclusions>
            <version>${docker.version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>
    </dependencies>
import com.alibaba.fastjson.JSON;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.BuildImageCmd;
import com.github.dockerjava.api.command.BuildImageResultCallback;
import com.github.dockerjava.api.command.LoadImageCmd;
import com.github.dockerjava.api.command.TagImageCmd;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientImpl;
import com.github.dockerjava.httpclient5.ApacheDockerHttpClient;
import com.github.dockerjava.transport.DockerHttpClient;
import com.sunyard.staging.starter.harbor.properties.HarborProperties;
import com.sunyard.staging.starter.harbor.utils.AesCbcUtil;
import com.sunyard.staging.starter.harbor.utils.UnCompress;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class HarborApiClient {
    @Autowired
    private HarborProperties harborProperties;

    /**
     * 构建DocekrClient实例
     *
     * @return
     */
    public DockerClient getDocekrClient() throws Exception {
        DefaultDockerClientConfig dockerClientConfig = null;
        if (harborProperties.isDockertlsverify()) {
            dockerClientConfig = DefaultDockerClientConfig.createDefaultConfigBuilder()
                    .withDockerHost(harborProperties.getDockerhost())
                    .withDockerTlsVerify(true)
                    .withDockerCertPath(harborProperties.getDockerCertPath())
                    .withRegistryUsername(harborProperties.getRegistryusername())
                    .withRegistryPassword(AesCbcUtil.Decrypt(harborProperties.getRegistrypassword()))
                    .withRegistryUrl(harborProperties.getRegistryurl())
                    .build();
        } else {
            dockerClientConfig = DefaultDockerClientConfig.createDefaultConfigBuilder()
                    .withDockerHost(harborProperties.getDockerhost())
                    .withDockerTlsVerify(false)
                    .withDockerCertPath(harborProperties.getDockerCertPath())
                    .withRegistryUsername(harborProperties.getRegistryusername())
                    .withRegistryPassword(AesCbcUtil.Decrypt(harborProperties.getRegistrypassword()))
                    .withRegistryUrl(harborProperties.getRegistryurl())
                    .build();
        }
        DockerHttpClient httpClient = new ApacheDockerHttpClient.Builder()
                .dockerHost(dockerClientConfig.getDockerHost())
                .sslConfig(dockerClientConfig.getSSLConfig())
                .build();
        return DockerClientImpl.getInstance(dockerClientConfig, httpClient);
    }


    /**
     * 构建DocekrClient实例
     *
     * @param dockerIpPort tcp://172.1.0.154:2375
     * @param dockerCertPath docker安全证书配置路径
     * @param dockerTlsVerify docker是否需要TLS认证
     * @return
     * @throws Exception
     */
    public DockerClient getDockerClient(String dockerIpPort, String dockerCertPath, boolean dockerTlsVerify) throws Exception {
        DefaultDockerClientConfig dockerClientConfig = null;
        if (dockerTlsVerify) {
            dockerClientConfig = DefaultDockerClientConfig.createDefaultConfigBuilder()
                    .withDockerHost(StringUtils.isNotBlank(dockerIpPort) ? dockerIpPort : harborProperties.getDockerhost())
                    .withDockerTlsVerify(true)
                    .withDockerCertPath(StringUtils.isNotBlank(dockerCertPath) ? dockerCertPath : harborProperties.getDockerCertPath())
                    .withRegistryUsername(harborProperties.getRegistryusername())
                    .withRegistryPassword(AesCbcUtil.Decrypt(harborProperties.getRegistrypassword()))
                    .withRegistryUrl(harborProperties.getRegistryurl())
                    .build();
        } else {
            dockerClientConfig = DefaultDockerClientConfig.createDefaultConfigBuilder()
                    .withDockerHost(StringUtils.isNotBlank(dockerIpPort) ? dockerIpPort : harborProperties.getDockerhost())
                    .withDockerTlsVerify(false)
                    .withDockerCertPath(StringUtils.isNotBlank(dockerCertPath) ? dockerCertPath : harborProperties.getDockerCertPath())
                    .withRegistryUsername(harborProperties.getRegistryusername())
                    .withRegistryPassword(AesCbcUtil.Decrypt(harborProperties.getRegistrypassword()))
                    .withRegistryUrl(harborProperties.getRegistryurl())
                    .build();
        }
        DockerHttpClient httpClient = new ApacheDockerHttpClient.Builder()
                .dockerHost(dockerClientConfig.getDockerHost())
                .sslConfig(dockerClientConfig.getSSLConfig())
                .build();
        return DockerClientImpl.getInstance(dockerClientConfig, httpClient);
    }

    /**
     * 获取docker基础信息
     *
     * @param dockerClient
     * @return
     */
    public static String getDockerInfo(DockerClient dockerClient) {
        Info info = dockerClient.infoCmd().exec();
        return JSON.toJSONString(info);
    }

    /**
     * 给镜像打标签
     *
     * @param dockerClient
     * @param imageIdOrFullName
     * @param respository
     * @param tag
     */
    public static void tagImage(DockerClient dockerClient, String imageIdOrFullName, String respository, String tag) {
        TagImageCmd tagImageCmd = dockerClient.tagImageCmd(imageIdOrFullName, respository, tag);
        tagImageCmd.exec();
    }

    /**
     * load镜像
     *
     * @param dockerClient
     * @param inputStream
     */
    public static void loadImage(DockerClient dockerClient, InputStream inputStream) {
        LoadImageCmd loadImageCmd = dockerClient.loadImageCmd(inputStream);
        loadImageCmd.exec();
    }

/**
     * Description 从harbor中拉取镜像到指定服务端的docker环境
     *
     * @date 2023/9/21 15:24
     * @param: dockerIpPort  "tcp://172.1.1.74:2375"
     * @param: dockerCertPath 安全证书路径
     * @param: dockerTlsVerify是否使用ssl
     * @param: imagePathInHarbor 镜像再harbor的路径 去除docker pull后的路径值
     * @return: boolean
     */
    private boolean harborImagePull(String dockerIpPort, String dockerCertPath, boolean dockerTlsVerify, String imagePathInHarbor) {
        try {
            DockerClient dockerClient = harborApiClient.getDockerClient(dockerIpPort, dockerCertPath, dockerTlsVerify);
            PullImageResultCallback exec = new PullImageResultCallback() {
                @Override
                public void onNext(PullResponseItem item) {
                    //用于进行镜像拉取的回调数据显示,item会显示镜像拉取的layer每层的状态
                }
            };
            // harbor服务器连接认证配置
            AuthConfig authConfig = new AuthConfig()
                    .withRegistryAddress(harborProperties.getRegistryurl() + ":" + harborProperties.getPort())
                    .withUsername(harborProperties.getRegistryusername())
                    .withPassword(AesCbcUtil.Decrypt(harborProperties.getRegistrypassword()));
            // 直接通过docker pull命令拉取时如果docker中未配置harbor密钥信息时不指定端口80,否则docker 中执行命令时将会失败
            dockerClient.pullImageCmd(imagePathInHarbor).withAuthConfig(authConfig).exec(exec)
                    .awaitCompletion(30, TimeUnit.MINUTES);
            exec.close();
            return true;
        } catch (Exception e) {
            logger.error("harbor镜像拉取失败:", e);
            return false;
        }
    }

    /**
     * 推送镜像
     *
     * @param dockerClient
     * @param imageName
     * @return
     * @throws InterruptedException
     */
    public static Boolean pushImage(DockerClient dockerClient, String imageName) throws InterruptedException {
        final Boolean[] result = {true};
        ResultCallback.Adapter<PushResponseItem> callBack = new ResultCallback.Adapter<PushResponseItem>() {
            @Override
            public void onNext(PushResponseItem pushResponseItem) {
                if (pushResponseItem != null) {
                    ResponseItem.ErrorDetail errorDetail = pushResponseItem.getErrorDetail();
                    if (errorDetail != null) {
                        result[0] = false;
                        log.error(errorDetail.getMessage(), errorDetail);
                    }
                }
                super.onNext(pushResponseItem);
            }
        };
        dockerClient.pushImageCmd(imageName).exec(callBack).awaitCompletion();
        return result[0];
    }

    /**
     * 上传镜像
     *
     * @param file      镜像文件
     * @param imageName
     * @throws Exception
     */
    public void uploadImage(DockerClient dockerClient, MultipartFile file, String imageName) throws Exception {
        InputStream inputStream = null;
        //获取加载镜像的名称
        String uploadImageName = "";
        try {
            inputStream = file.getInputStream();
            String password = AesCbcUtil.Decrypt(harborProperties.getRegistrypassword());
            //Harbor登录信息
            AuthConfig autoConfig =
                    new AuthConfig().withRegistryAddress(harborProperties.getRegistryurl()).
                            withUsername(harborProperties.getRegistryusername()).withPassword(password);
            //加载镜像
            dockerClient.loadImageCmd(inputStream).exec();
            String imageFile = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
            String imageId = imageFile.substring(imageFile.lastIndexOf("_") + 1);
            List<Image> list = dockerClient.listImagesCmd().exec();
            for (Image image : list) {
                // 压缩包可能包含多个对象,只导入指定镜像
                if (image.getId().contains(imageId)) {
                    uploadImageName = image.getRepoTags()[0];
                    break;
                }
            }
            //镜像打tag
            dockerClient.tagImageCmd(uploadImageName, imageName, imageName.split(":")[2]).exec();
            //push至镜像仓库
            dockerClient.pushImageCmd(imageName).withAuthConfig(autoConfig).start().awaitCompletion(30, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("上传镜像出现异常", e);
        } finally {
            //push成功后,删除本地加载的镜像
            dockerClient.removeImageCmd(imageName).exec();
            dockerClient.removeImageCmd(uploadImageName).exec();
            //关闭文件流,这个应该使用try-catch 的try中
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

    /**
     * 从镜像的tar文件中获取镜像名称
     *
     * @param imagePath
     * @return
     */
    public static String getImageName(String imagePath) {
        try {
            return UnCompress.getImageName(imagePath);
        } catch (Exception e) {
            log.error("从镜像的tar文件中获取镜像名称出现异常!", e);
            return null;
        }
    }

    /**
     * 通过dockerFile构建镜像
     *
     * @param dockerClient
     * @param dockerFile
     * @return
     */
    public static String buildImage(DockerClient dockerClient, File dockerFile) {
        BuildImageCmd buildImageCmd = dockerClient.buildImageCmd(dockerFile);
        BuildImageResultCallback buildImageResultCallback = new BuildImageResultCallback() {
            @Override
            public void onNext(BuildResponseItem item) {
                log.info("{}", item);
                super.onNext(item);
            }
        };
        return buildImageCmd.exec(buildImageResultCallback).awaitImageId();
    }

    /**
     * 获取镜像列表
     *
     * @param dockerClient
     * @return
     */
    public static List<Image> imageList(DockerClient dockerClient) {
        List<Image> imageList = dockerClient.listImagesCmd().withShowAll(true).exec();
        return imageList;
    }
}
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Setter
@Getter
@Configuration
@ConfigurationProperties(prefix = "spring.harbor")
public class HarborProperties {

    // docker服务端IP地址
    public String dockerhost = "tcp://127.0.0.1:2375";
    // docker安全证书配置路径
    public String dockerCertPath = "";
    // docker是否需要TLS认证
    public boolean dockertlsverify = false;
    // Harbor仓库的IP
    public String registryurl = "127.0.0.1:80";
    // Harbor仓库的登录用户名
    public String registryusername = "sungrid";
    // Harbor仓库的登录密码 当前密码进行了加密处理
    public String registrypassword = "h8Wj3V01WWbBotV72XFJ38Js2nUD3Jj6Mc9K";
    // docker 镜像部署服务器地址
    public String dockerservicemachine = "172.1.0.154:22";

    public String dockerservicemachineusername = "root";

    public String dockerservicemachinepassword = "Xydxnj220406!";

    public int port = 80;

}


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Slf4j
public class UnCompress {
    private static final String BASE_DIR = "";
    // 符号"/"用来作为目录标识判断符
    private static final String PATH = File.separator;
    private static final int BUFFER = 1024;
    private static final String EXT = ".tar";

    /**
     * 归档
     * @param srcPath
     * @param destPath
     * @throws Exception
     */
    public static void archive(String srcPath, String destPath) throws Exception {
        File srcFile = new File(srcPath);
        archive(srcFile, destPath);
    }

    /**
     * 归档
     * @param srcFile 源路径
     * @param destFile 目标路径
     * @throws Exception
     */
    public static void archive(File srcFile, File destFile) throws Exception {
        TarArchiveOutputStream taos = new TarArchiveOutputStream(new FileOutputStream(destFile));
        archive(srcFile, taos, BASE_DIR);
        taos.flush();
        taos.close();
    }

    /**
     * 归档
     * @param srcFile
     * @throws Exception
     */
    public static void archive(File srcFile) throws Exception {
        String name = srcFile.getName();
        String basePath = srcFile.getParent();
        String destPath = basePath+File.separator + name + EXT;
        archive(srcFile, destPath);
    }

    /**
     * 归档文件
     * @param srcFile
     * @param destPath
     * @throws Exception
     */
    public static void archive(File srcFile, String destPath) throws Exception {
        archive(srcFile, new File(destPath));
    }

    /**
     * 归档
     * @param srcPath
     * @throws Exception
     */
    public static void archive(String srcPath) throws Exception {
        File srcFile = new File(srcPath);
        archive(srcFile);
    }

    /**
     * 归档
     * @param srcFile 源路径
     * @param taos TarArchiveOutputStream
     * @param basePath 归档包内相对路径
     * @throws Exception
     */
    private static void archive(File srcFile, TarArchiveOutputStream taos, String basePath) throws Exception {
        if (srcFile.isDirectory()) {
            archiveDir(srcFile, taos, basePath);
        } else {
            archiveFile(srcFile, taos, basePath);
        }
    }

    /**
     * 目录归档
     * @param dir
     * @param taos TarArchiveOutputStream
     * @param basePath
     * @throws Exception
     */
    private static void archiveDir(File dir, TarArchiveOutputStream taos, String basePath) throws Exception {
        File[] files = dir.listFiles();
        if (files.length < 1) {
            TarArchiveEntry entry = new TarArchiveEntry(basePath + dir.getName() + PATH);
            taos.putArchiveEntry(entry);
            taos.closeArchiveEntry();
        }
        for (File file : files) {
            // 递归归档
            archive(file, taos, basePath + dir.getName() + PATH);
        }
    }

    /**
     * 归档内文件名定义
     * <pre>
     * 如果有多级目录,那么这里就需要给出包含目录的文件名
     * 如果用WinRAR打开归档包,中文名将显示为乱码
     * </pre>
     */
    private static void archiveFile(File file, TarArchiveOutputStream taos, String dir) throws Exception {
        TarArchiveEntry entry = new TarArchiveEntry(dir + file.getName());
        //如果打包不需要文件夹,就用 new TarArchiveEntry(file.getName())
        entry.setSize(file.length());
        taos.putArchiveEntry(entry);
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        int count;
        byte data[] = new byte[BUFFER];
        while ((count = bis.read(data, 0, BUFFER)) != -1) {
            taos.write(data, 0, count);
        }
        bis.close();
        taos.closeArchiveEntry();
    }

    /**
     * 解归档
     * @param srcFile
     * @throws Exception
     */
    public static void dearchive(File srcFile) throws Exception {
        String basePath = srcFile.getParent();
        dearchive(srcFile, basePath);
    }

    /**
     * 解归档
     * @param srcFile
     * @param destFile
     * @throws Exception
     */
    public static void dearchive(File srcFile, File destFile) throws Exception {
        TarArchiveInputStream tais = new TarArchiveInputStream(new FileInputStream(srcFile));
        dearchive(destFile, tais);
        tais.close();
    }

    /**
     * 解归档
     * @param srcFile
     * @param destPath
     * @throws Exception
     */
    public static void dearchive(File srcFile, String destPath) throws Exception {
        dearchive(srcFile, new File(destPath));
    }

    /**
     * 文件 解归档
     * @param destFile 目标文件
     * @param tais ZipInputStream
     * @throws Exception
     */
    private static void dearchive(File destFile, TarArchiveInputStream tais) throws Exception {
        TarArchiveEntry entry = null;
        while ((entry = tais.getNextTarEntry()) != null) {
            // 文件
            String dir = destFile.getPath() + File.separator + entry.getName();
            File dirFile = new File(dir);
            // 文件检查
            fileProber(dirFile);
            if (entry.isDirectory()) {
                dirFile.mkdirs();
            } else {
                dearchiveFile(dirFile, tais);
            }
        }
    }

    /**
     * 文件 解归档
     * @param srcPath 源文件路径
     * @throws Exception
     */
    public static void dearchive(String srcPath) throws Exception {
        File srcFile = new File(srcPath);
        dearchive(srcFile);
    }

    /**
     * 文件 解归档
     * @param srcPath 源文件路径
     * @param destPath 目标文件路径
     * @throws Exception
     */
    public static void dearchive(String srcPath, String destPath) throws Exception {
        File srcFile = new File(srcPath);
        dearchive(srcFile, destPath);
    }

    /**
     * 文件解归档
     * @param destFile 目标文件
     * @param tais TarArchiveInputStream
     * @throws Exception
     */
    private static void dearchiveFile(File destFile, TarArchiveInputStream tais) throws Exception {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
        int count;
        byte data[] = new byte[BUFFER];
        while ((count = tais.read(data, 0, BUFFER)) != -1) {
            bos.write(data, 0, count);
        }
        bos.close();
    }

    /**
     * 文件探针
     * <pre>
     * 当父目录不存在时,创建目录!
     * </pre>
     * @param dirFile
     */
    private static void fileProber(File dirFile) {
        File parentFile = dirFile.getParentFile();
        if (!parentFile.exists()) {
            // 递归寻找上级目录
            fileProber(parentFile);
            parentFile.mkdir();
        }
    }

    public static String getImageName(String tempFilePath) throws Exception{
        String dirPath = tempFilePath.substring(0, tempFilePath.lastIndexOf("."));
        File dirFile = new File(dirPath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        UnCompress.dearchive(tempFilePath, dirPath);
        if (!dirPath.endsWith(File.separator)) {
            dirPath += File.separator;
        }
        //目标文件
        String destFilePath = dirPath + "manifest.json";
        File destFile = new File(destFilePath);
        if (!destFile.exists()) {
            return null;
        }
        StringBuilder sb = new StringBuilder("");
        InputStream io = new FileInputStream(new File(destFilePath));
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = io.read(bytes)) > 0) {
            sb.append(new String(bytes, 0, len));
        }
        String content = sb.toString();
        //只取第一个配置项
        List<JSONObject> jsonList = (List<JSONObject>) JSONArray.parse(content);
        System.out.println("jsonList = " + jsonList);
        return ((List<String>)jsonList.get(0).get("RepoTags")).get(0);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Docker、Jenkins、GitLab、Maven、HarborSpring Boot是一些常用的IT工具和技术,可以用于实现自动化构建和部署。 Docker是一个开源的容器化平台,可以将应用程序及其依赖项打包到容器中,从而实现应用程序的快速部署和隔离。使用Docker可以方便地创建、分享和管理应用程序的容器化版本。 Jenkins是一个开源的持续集成和持续交付工具,可以帮助团队自动化构建、测试和部署应用程序。使用Jenkins可以通过配置和管理各种构建和部署任务,从而实现自动化的软件开发流程。 GitLab是一个基于Git的代码托管和协作平台,可以帮助团队协同开发、管理代码和进行版本控制。使用GitLab可以方便地管理代码仓库、进行代码审查和版本管理。 Maven是一个软件项目管理和构建工具,可以帮助团队自动化构建、测试和部署Java项目。使用Maven可以方便地管理项目依赖、编译代码、运行单元测试等构建任务。 Harbor是一个开源的企业级Docker镜像仓库,用于管理和存储Docker镜像。使用Harbor可以方便地管理镜像的推送、拉取和版本控制。 Spring Boot是一个轻量级的Java开发框架,可以帮助开发者快速构建和部署基于Spring的应用程序。使用Spring Boot可以简化项目配置和管理,提高开发效率。 将这些工具结合使用,可以实现自动化构建和部署。例如,可以使用Jenkins配置一个定时任务,当代码提交到GitLab时,Jenkins会自动触发构建任务。构建任务可以使用Maven编译、打包和测试应用程序,然后使用Docker将应用程序打包成容器镜像,并推送到Harbor中。最后,使用Docker将应用程序部署到服务器上进行运行。这样,我们就可以实现应用程序的自动化构建和部署,提高开发和交付效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值