Commit 0c03802e authored by liaozan's avatar liaozan 🏀

Move jenkins-plugin to standard project

parent a065d494
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
### How to develop
* add the following content to your maven settings.xml
* active jenkins profile on your ide
```xml
<profile>
<id>jenkins</id>
<repositories>
<repository>
<id>repo.jenkins-ci.org</id>
<url>https://repo.jenkins-ci.org/public/</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>repo.jenkins-ci.org</id>
<url>https://repo.jenkins-ci.org/public/</url>
</pluginRepository>
</pluginRepositories>
</profile>
```
### How to build
run `mvn clean package -Dmaven.test.skip` in terminal, plugin will be stored in the target directory named `integration-jenkins-plugin.hpi`, upload it to your jenkins server
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>plugin</artifactId>
<!-- Baseline Jenkins version you use to build and test the plugin. Users must have this version or newer to run. -->
<version>4.62</version>
<relativePath/>
</parent>
<groupId>com.schbrain.ci.jenkins.plugins</groupId>
<artifactId>integration-jenkins-plugin</artifactId>
<version>1.0</version>
<packaging>hpi</packaging>
<scm>
<tag>integration-1.0</tag>
</scm>
<properties>
<jenkins.version>2.397</jenkins.version>
<maven.install.skip>true</maven.install.skip>
<maven.deploy.skip>true</maven.deploy.skip>
<spotbugs.skip>true</spotbugs.skip>
<enforcer.skip>true</enforcer.skip>
</properties>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>git</artifactId>
<version>5.0.1</version>
</dependency>
<dependency>
<groupId>org.jenkins-ci.tools</groupId>
<artifactId>git-parameter</artifactId>
<version>0.9.18</version>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>localization-zh-cn</artifactId>
<version>1.0.24</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.schbrain.ci.jenkins.plugins.integration.action;
import hudson.FilePath;
import hudson.model.*;
import jenkins.model.RunAction2;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import java.io.File;
/**
* @author liaozan
* @since 2022/2/16
*/
public class ViewBuildScriptAction implements RunAction2 {
private final String buildScriptDir;
private transient Run<?, ?> run;
public ViewBuildScriptAction(File buildScriptDir) {
this.buildScriptDir = buildScriptDir.getAbsolutePath();
}
@Override
public String getIconFileName() {
return "document.png";
}
@Override
public String getDisplayName() {
return "构建脚本";
}
@Override
public String getUrlName() {
return "build-scripts";
}
@Override
public void onAttached(Run<?, ?> run) {
this.run = run;
}
@Override
public void onLoad(Run<?, ?> run) {
this.run = run;
}
public Run<?, ?> getRun() {
return run;
}
@SuppressWarnings({"unused", "rawtypes"})
public DirectoryBrowserSupport doList(StaplerRequest request, StaplerResponse response) {
AbstractBuild build = (AbstractBuild) request.findAncestor(AbstractBuild.class).getObject();
FilePath filePath = new FilePath(new File(buildScriptDir));
return new DirectoryBrowserSupport(build, filePath, "构建脚本", "folder.png", true);
}
}
\ No newline at end of file
package com.schbrain.ci.jenkins.plugins.integration.builder;
import com.schbrain.ci.jenkins.plugins.integration.builder.env.BuildEnvContributor;
import com.schbrain.ci.jenkins.plugins.integration.builder.util.Logger;
import com.schbrain.ci.jenkins.plugins.integration.builder.util.TemplateUtils;
import hudson.*;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.tasks.Shell;
import java.io.IOException;
import java.util.Objects;
/**
* @author zhangdd on 2022/1/21
*/
public class BuilderContext {
private final AbstractBuild<?, ?> build;
private final Launcher launcher;
private final FilePath workspace;
private final BuildListener listener;
private final Logger logger;
private final EnvVars envVars;
private boolean imageHasBeenBuilt;
private BuilderContext(Builder builder) {
this.build = builder.build;
this.launcher = builder.launcher;
this.workspace = builder.workspace;
this.listener = builder.listener;
this.logger = builder.logger;
this.envVars = builder.envVars;
this.imageHasBeenBuilt = false;
}
public void execute(String command) throws InterruptedException, IOException {
String resolvedCommand = TemplateUtils.evaluate(command, envVars);
if (!Objects.equals(resolvedCommand, command)) {
log("before resolve: %s", command);
command = resolvedCommand;
}
log("%s", command);
BuildEnvContributor.saveEnvVarsToDisk(this);
Shell shell = new Shell(command);
shell.perform(getBuild(), getLauncher(), getListener());
}
public AbstractBuild<?, ?> getBuild() {
return build;
}
public Launcher getLauncher() {
return launcher;
}
public FilePath getWorkspace() {
return workspace;
}
public BuildListener getListener() {
return listener;
}
public Logger getLogger() {
return logger;
}
public EnvVars getEnvVars() {
return envVars;
}
public boolean isImageHasBeenBuilt() {
return imageHasBeenBuilt;
}
public void setImageHasBeenBuilt() {
this.imageHasBeenBuilt = true;
}
public void log(String template) {
log(template, (Object) null);
}
public void log(String template, Object... arguments) {
logger.println(template, true, arguments);
}
public static class Builder {
private AbstractBuild<?, ?> build;
private Launcher launcher;
private FilePath workspace;
private BuildListener listener;
private Logger logger;
private EnvVars envVars;
public Builder build(AbstractBuild<?, ?> build) {
this.build = build;
return this;
}
public Builder launcher(Launcher launcher) {
this.launcher = launcher;
return this;
}
public Builder workspace(FilePath workspace) {
this.workspace = workspace;
return this;
}
public Builder listener(BuildListener listener) {
this.listener = listener;
return this;
}
public Builder logger(Logger logger) {
this.logger = logger;
return this;
}
public Builder envVars(EnvVars envVars) {
this.envVars = envVars;
return this;
}
public BuilderContext build() {
return new BuilderContext(this);
}
}
}
\ No newline at end of file
package com.schbrain.ci.jenkins.plugins.integration.builder;
import hudson.model.AbstractBuild;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import static com.schbrain.ci.jenkins.plugins.integration.builder.constants.Constants.BuildConstants.*;
/**
* @author liaozan
* @since 2022/2/8
*/
@SuppressWarnings("ResultOfMethodCallIgnored")
public class FileManager {
public static File getCurrentBuildDir(AbstractBuild<?, ?> build) {
return build.getRootDir();
}
public static File getWorkspaceBuildScriptDir(AbstractBuild<?, ?> build) {
return new File(Objects.requireNonNull(build.getWorkspace()).getRemote(), BUILD_SCRIPT_NAME);
}
public static File getEnvVarsFile(AbstractBuild<?, ?> build) throws IOException {
File buildScriptDir = getBuildScriptDir(build);
File envVarsFile = new File(buildScriptDir, ENV_VARS);
if (!envVarsFile.exists()) {
envVarsFile.createNewFile();
}
return envVarsFile;
}
public static File getBuildScriptDir(AbstractBuild<?, ?> build) {
File buildDir = getCurrentBuildDir(build);
File buildScriptDir = new File(buildDir, BUILD_SCRIPT_NAME);
if (!buildScriptDir.exists()) {
buildScriptDir.mkdirs();
}
return buildScriptDir;
}
}
\ No newline at end of file
package com.schbrain.ci.jenkins.plugins.integration.builder;
import com.schbrain.ci.jenkins.plugins.integration.action.ViewBuildScriptAction;
import com.schbrain.ci.jenkins.plugins.integration.builder.config.*;
import com.schbrain.ci.jenkins.plugins.integration.builder.config.DockerConfig.PushConfig;
import com.schbrain.ci.jenkins.plugins.integration.builder.util.FileUtils;
import com.schbrain.ci.jenkins.plugins.integration.builder.util.Logger;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import hudson.*;
import hudson.model.*;
import hudson.tasks.Builder;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import org.springframework.lang.Nullable;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import static com.schbrain.ci.jenkins.plugins.integration.builder.constants.Constants.BuildConstants.*;
import static com.schbrain.ci.jenkins.plugins.integration.builder.constants.Constants.*;
import static com.schbrain.ci.jenkins.plugins.integration.builder.util.FileUtils.lookupFile;
/**
* @author liaozan
* @since 2022/1/14
*/
@SuppressWarnings("unused")
public class IntegrationBuilder extends Builder {
private final MavenConfig mavenConfig;
private final DockerConfig dockerConfig;
private final DeployToK8sConfig deployToK8sConfig;
@DataBoundConstructor
public IntegrationBuilder(@Nullable MavenConfig mavenConfig,
@Nullable DockerConfig dockerConfig,
@Nullable DeployToK8sConfig deployToK8sConfig) {
this.mavenConfig = mavenConfig;
this.dockerConfig = dockerConfig;
this.deployToK8sConfig = deployToK8sConfig;
}
@Nullable
public MavenConfig getMavenConfig() {
return mavenConfig;
}
@Nullable
public DockerConfig getDockerConfig() {
return dockerConfig;
}
@Nullable
public DeployToK8sConfig getDeployToK8sConfig() {
return deployToK8sConfig;
}
/**
* Builder start
*/
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException {
build.addAction(new ViewBuildScriptAction(FileManager.getBuildScriptDir(build)));
BuilderContext builderContext = new BuilderContext.Builder()
.build(build)
.launcher(launcher)
.listener(listener)
.logger(Logger.of(listener.getLogger()))
.workspace(checkWorkspaceValid(build.getWorkspace()))
.envVars(createEnvVars(build))
.build();
return doPerformBuild(builderContext);
}
@Override
public IntegrationDescriptor getDescriptor() {
return (IntegrationDescriptor) super.getDescriptor();
}
protected boolean doPerformBuild(BuilderContext context) throws IOException, InterruptedException {
try {
// download build scripts
downloadBuildScript(context);
// maven build
performMavenBuild(context);
// read maven build-info
readMavenBuildInfo(context);
// docker build
performDockerBuild(context);
// docker push
performDockerPush(context);
// deploy
deployToRemote(context);
} finally {
if (context.isImageHasBeenBuilt()) {
// delete the built image if possible
deleteImageAfterBuild(context);
}
// setup description
setBuildDescription(context);
// copy to buildDir
saveTheBuildScripts(context);
}
return true;
}
private EnvVars createEnvVars(AbstractBuild<?, ?> build) {
EnvVars envVars = new EnvVars();
ParametersAction parametersAction = build.getAction(ParametersAction.class);
if (parametersAction == null) {
return envVars;
}
List<ParameterValue> allParameters = parametersAction.getAllParameters();
for (ParameterValue parameter : allParameters) {
if (parameter.getValue() == null) {
continue;
}
envVars.put(parameter.getName(), parameter.getValue().toString());
}
return envVars;
}
private void downloadBuildScript(BuilderContext context) throws IOException, InterruptedException {
String buildScriptUrl = DEFAULT_SCRIPT_GIT_REPO;
String buildScriptBranch = DEFAULT_SCRIPT_GIT_BRANCH;
// if buildScriptUrl and buildScriptBranch is set, will use specified value to download build-script, otherwise will use default value
if (getDockerConfig() != null) {
if (StringUtils.isNotBlank(getDockerConfig().getBuildScriptUrl())) {
buildScriptUrl = getDockerConfig().getBuildScriptUrl();
}
if (StringUtils.isNotBlank(getDockerConfig().getBuildScriptBranch())) {
buildScriptBranch = getDockerConfig().getBuildScriptBranch();
}
}
// git archive the build scripts
String archiveCommand = String.format("git archive -o %s --format=zip --remote=%s %s", SCRIPT_ZIP_NAME, buildScriptUrl, buildScriptBranch);
context.execute(archiveCommand);
// unzip to directory in workspace
String unzipCommand = String.format("unzip -o %s -d %s", SCRIPT_ZIP_NAME, BUILD_SCRIPT_NAME);
context.execute(unzipCommand);
}
private void setBuildDescription(BuilderContext context) throws IOException, InterruptedException {
FilePath gitPropertiesFile = lookupFile(context, GitConstants.GIT_PROPERTIES_FILE);
if (gitPropertiesFile == null) {
return;
}
Map<String, String> gitProperties = FileUtils.filePathToMap(gitPropertiesFile);
String author = gitProperties.get(GitConstants.GIT_COMMITTER);
String branch = gitProperties.get(GitConstants.GIT_BRANCH);
AbstractBuild<?, ?> build = context.getBuild();
String description = String.format("author: %s, branch: %s", author, branch);
build.setDescription(description);
}
/**
* Check workspace
*/
private FilePath checkWorkspaceValid(@CheckForNull FilePath workspace) throws IOException, InterruptedException {
if (workspace == null) {
throw new IllegalStateException("workspace is null");
}
if (!workspace.exists()) {
throw new IllegalStateException("workspace is not exist");
}
return workspace;
}
private void performMavenBuild(BuilderContext context) throws IOException, InterruptedException {
MavenConfig mavenConfig = getMavenConfig();
if (mavenConfig == null) {
context.log("maven build is not checked");
return;
}
mavenConfig.build(context);
}
private void readMavenBuildInfo(BuilderContext context) throws IOException, InterruptedException {
EnvVars envVars = context.getEnvVars();
FilePath dockerBuildInfo = lookupFile(context, DockerConstants.BUILD_INFO_FILE_NAME);
if (dockerBuildInfo == null) {
context.log("%s file not exist, skip docker build", DockerConstants.BUILD_INFO_FILE_NAME);
return;
}
// overwriting existing environment variables is not allowed
FileUtils.filePathToMap(dockerBuildInfo).forEach(envVars::putIfAbsent);
}
private void performDockerBuild(BuilderContext context) throws IOException, InterruptedException {
DockerConfig dockerConfig = getDockerConfig();
if (dockerConfig == null) {
context.log("docker build is not checked");
return;
}
dockerConfig.build(context);
}
private void performDockerPush(BuilderContext context) throws IOException, InterruptedException {
DockerConfig dockerConfig = getDockerConfig();
if (dockerConfig == null) {
context.log("docker build is not checked");
return;
}
PushConfig pushConfig = dockerConfig.getPushConfig();
if (pushConfig == null) {
context.log("docker push is not checked");
return;
}
pushConfig.build(context);
}
/**
* Delete the image produced in the build
*/
private void deleteImageAfterBuild(BuilderContext context) throws InterruptedException, IOException {
DockerConfig dockerConfig = getDockerConfig();
if (dockerConfig == null) {
context.log("docker build is not checked");
return;
}
if (!dockerConfig.getDeleteImageAfterBuild()) {
context.log("delete built image is skip");
return;
}
String imageName = context.getEnvVars().get(DockerConstants.IMAGE);
if (imageName == null) {
return;
}
String command = String.format("docker rmi -f %s", imageName);
context.execute(command);
}
/**
* 部署镜像到远端
*/
private void deployToRemote(BuilderContext context) throws IOException, InterruptedException {
DeployToK8sConfig k8sConfig = getDeployToK8sConfig();
if (k8sConfig == null) {
context.log("k8s deploy is not checked");
return;
}
k8sConfig.build(context);
}
private void saveTheBuildScripts(BuilderContext context) throws InterruptedException, IOException {
String copy = String.format("cp -r %s %s", BUILD_SCRIPT_NAME, FileManager.getCurrentBuildDir(context.getBuild()));
context.execute(copy);
}
// can not move outside builder class
@Extension
public static class IntegrationDescriptor extends Descriptor<Builder> {
public IntegrationDescriptor() {
load();
}
@Override
public String getDisplayName() {
return "发布集成";
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
save();
return super.configure(req, formData);
}
}
}
\ No newline at end of file
package com.schbrain.ci.jenkins.plugins.integration.builder.config;
import com.schbrain.ci.jenkins.plugins.integration.builder.BuilderContext;
import com.schbrain.ci.jenkins.plugins.integration.builder.util.Logger;
import hudson.*;
import hudson.model.*;
import java.io.IOException;
/**
* @author liaozan
* @since 2022/1/17
*/
public abstract class BuildConfig<T extends AbstractDescribableImpl<T>> extends AbstractDescribableImpl<T> {
protected AbstractBuild<?, ?> build;
protected Launcher launcher;
protected FilePath workspace;
protected BuildListener listener;
protected Logger logger;
protected EnvVars envVars;
protected BuilderContext context;
public void build(BuilderContext context) throws IOException, InterruptedException {
this.context = context;
this.build = context.getBuild();
this.launcher = context.getLauncher();
this.workspace = context.getWorkspace();
this.listener = context.getListener();
this.logger = context.getLogger();
this.envVars = context.getEnvVars();
doBuild();
}
protected abstract void doBuild() throws InterruptedException, IOException;
}
\ No newline at end of file
package com.schbrain.ci.jenkins.plugins.integration.builder.config;
import com.schbrain.ci.jenkins.plugins.integration.builder.config.deploy.DeployStyleRadio;
import com.schbrain.ci.jenkins.plugins.integration.builder.config.deploy.service.ServiceDeployConfig;
import com.schbrain.ci.jenkins.plugins.integration.builder.constants.Constants.DockerConstants;
import com.schbrain.ci.jenkins.plugins.integration.builder.util.FileUtils;
import hudson.*;
import hudson.model.Descriptor;
import jenkins.model.Jenkins;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* @author liaozan
* @since 2022/1/16
*/
@SuppressWarnings("unused")
public class DeployToK8sConfig extends BuildConfig<DeployToK8sConfig> {
private final String configLocation;
private final DeployStyleRadio deployStyle;
private final ServiceDeployConfig serviceDeployConfig;
@DataBoundConstructor
public DeployToK8sConfig(String configLocation, DeployStyleRadio deployStyle, ServiceDeployConfig serviceDeployConfig) {
this.configLocation = Util.fixNull(configLocation);
this.deployStyle = deployStyle;
this.serviceDeployConfig = serviceDeployConfig;
}
public String getConfigLocation() {
return configLocation;
}
public DeployStyleRadio getDeployStyle() {
return deployStyle;
}
public ServiceDeployConfig getServiceDeployConfig() {
return serviceDeployConfig;
}
public void doBuild() throws InterruptedException, IOException {
String imageName = envVars.get(DockerConstants.IMAGE);
if (StringUtils.isBlank(imageName)) {
context.log("image name is empty ,skip deploy");
return;
}
// make sure to build Deployment first
buildDeployment();
buildService();
}
private void buildDeployment() throws IOException, InterruptedException {
DeployStyleRadio deployStyle = getDeployStyle();
if (null == deployStyle) {
return;
}
String deployFileLocation = deployStyle.getDeployFileLocation(context);
executeK8sCommand(deployFileLocation);
}
private void buildService() throws IOException, InterruptedException {
if (serviceDeployConfig == null) {
return;
}
String deployFileLocation = serviceDeployConfig.getServiceDeployFileLocation(context);
executeK8sCommand(deployFileLocation);
}
private void executeK8sCommand(String deployFileLocation) throws InterruptedException, IOException {
String configLocation = getConfigLocation();
if (null == configLocation) {
context.log("not specified configLocation of k8s config ,will use default config .");
}
String deployFileRelativePath = FileUtils.toRelativePath(workspace, new FilePath(new File(deployFileLocation)));
String command = String.format("kubectl apply -f %s", deployFileRelativePath);
if (StringUtils.isNotBlank(configLocation)) {
command = command + " --kubeconfig " + configLocation;
}
context.execute(command);
}
@Extension
public static class DescriptorImpl extends Descriptor<DeployToK8sConfig> {
public List<Descriptor<DeployStyleRadio>> getDeployStyles() {
return Jenkins.get().getDescriptorList(DeployStyleRadio.class);
}
}
}
\ No newline at end of file
package com.schbrain.ci.jenkins.plugins.integration.builder.config;
import com.schbrain.ci.jenkins.plugins.integration.builder.util.FileUtils;
import com.schbrain.ci.jenkins.plugins.integration.builder.util.TemplateUtils;
import hudson.*;
import hudson.model.Descriptor;
import org.apache.commons.lang3.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import org.springframework.lang.Nullable;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import static com.schbrain.ci.jenkins.plugins.integration.builder.constants.Constants.BuildConstants.BUILD_SCRIPT_NAME;
import static com.schbrain.ci.jenkins.plugins.integration.builder.constants.Constants.DockerConstants.*;
import static com.schbrain.ci.jenkins.plugins.integration.builder.util.FileUtils.lookupFile;
/**
* @author liaozan
* @since 2022/1/16
*/
@SuppressWarnings("unused")
public class DockerConfig extends BuildConfig<DockerConfig> {
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(ZoneId.systemDefault());
private final Boolean buildImage;
private final PushConfig pushConfig;
private final Boolean deleteImageAfterBuild;
private final String javaOpts;
private final String buildScriptUrl;
private final String buildScriptBranch;
private final Boolean disableSkywalking;
@DataBoundConstructor
public DockerConfig(Boolean buildImage, PushConfig pushConfig, Boolean deleteImageAfterBuild, String javaOpts,
String buildScriptUrl, String buildScriptBranch, Boolean disableSkywalking) {
this.buildImage = Util.fixNull(buildImage, false);
this.pushConfig = pushConfig;
this.deleteImageAfterBuild = Util.fixNull(deleteImageAfterBuild, false);
this.javaOpts = Util.fixNull(javaOpts);
this.buildScriptUrl = buildScriptUrl;
this.buildScriptBranch = buildScriptBranch;
this.disableSkywalking = disableSkywalking;
}
@Nullable
public PushConfig getPushConfig() {
return pushConfig;
}
public Boolean getBuildImage() {
return buildImage;
}
public Boolean getDeleteImageAfterBuild() {
return deleteImageAfterBuild;
}
public String getJavaOpts() {
return javaOpts;
}
public String getBuildScriptUrl() {
return buildScriptUrl;
}
public String getBuildScriptBranch() {
return buildScriptBranch;
}
public Boolean getDisableSkywalking() {
return disableSkywalking;
}
@Override
public void doBuild() throws IOException, InterruptedException {
if (!getBuildImage()) {
context.log("docker build image is skipped");
return;
}
String javaOpts = this.javaOpts;
if (Boolean.TRUE.equals(getDisableSkywalking())) {
if (StringUtils.isBlank(javaOpts)) {
javaOpts = DISABLE_SKYWALKING_OPTIONS;
} else {
javaOpts = javaOpts + " " + DISABLE_SKYWALKING_OPTIONS;
}
}
envVars.put(JAVA_OPTS, javaOpts);
String imageName = getFullImageName();
if (imageName == null) {
return;
}
envVars.put(IMAGE, imageName);
FilePath dockerfile = lookupFile(workspace.child(BUILD_SCRIPT_NAME), DOCKERFILE_NAME, context.getLogger());
if (dockerfile == null) {
context.log("Dockerfile not exist, skip docker build");
return;
}
TemplateUtils.evaluate(Paths.get(dockerfile.getRemote()), context);
String relativePath = FileUtils.toRelativePath(workspace, dockerfile);
String command = String.format("docker build --pull -t %s -f %s .", imageName, relativePath);
context.execute(command);
context.setImageHasBeenBuilt();
}
private String getFullImageName() {
String registry = null;
PushConfig pushConfig = getPushConfig();
if (pushConfig != null) {
registry = pushConfig.getRegistry();
}
if (StringUtils.isBlank(registry)) {
registry = envVars.get(REGISTRY);
}
if (StringUtils.isBlank(registry)) {
throw new IllegalArgumentException("REGISTRY is null or empty");
}
String appName = envVars.get(APP_NAME);
String version = envVars.get(VERSION);
String buildTime = DATE_TIME_FORMATTER.format(Instant.ofEpochMilli(build.getStartTimeInMillis()));
return String.format("%s/%s:%s-%s", registry, appName, version, buildTime);
}
@Extension
public static class DescriptorImpl extends Descriptor<DockerConfig> {
}
public static class PushConfig extends BuildConfig<PushConfig> {
private final Boolean pushImage;
private final String registry;
@DataBoundConstructor
public PushConfig(Boolean pushImage, String registry) {
this.pushImage = pushImage;
this.registry = registry;
}
public Boolean getPushImage() {
return pushImage;
}
public String getRegistry() {
return registry;
}
@Override
public void doBuild() throws IOException, InterruptedException {
if (!getPushImage()) {
logger.println("docker push image is skipped");
return;
}
String imageName = envVars.get(IMAGE);
if (imageName == null) {
return;
}
String command = String.format("docker push %s", imageName);
context.execute(command);
}
@Extension
@SuppressWarnings("unused")
public static class DescriptorImpl extends Descriptor<PushConfig> {
}
}
}
\ No newline at end of file
package com.schbrain.ci.jenkins.plugins.integration.builder.config;
import hudson.Extension;
import hudson.Util;
import hudson.model.Descriptor;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import java.io.IOException;
/**
* @author liaozan
* @since 2022/1/16
*/
@SuppressWarnings("unused")
public class MavenConfig extends BuildConfig<MavenConfig> {
private final String mvnCommand;
private final String javaHome;
@DataBoundConstructor
public MavenConfig(String mvnCommand, String javaHome) {
this.mvnCommand = Util.fixNull(mvnCommand);
this.javaHome = Util.fixNull(javaHome);
}
public String getMvnCommand() {
return mvnCommand;
}
public String getJavaHome() {
return javaHome;
}
@Override
public void doBuild() throws IOException, InterruptedException {
String mavenCommand = getMvnCommand();
if (StringUtils.isBlank(mavenCommand)) {
logger.println("maven command is empty, skip maven build");
return;
}
String javaHome = getJavaHome();
if (StringUtils.isNotBlank(javaHome)) {
envVars.put("JAVA_HOME", javaHome);
}
context.execute(mavenCommand);
}
@Extension
public static class DescriptorImpl extends Descriptor<MavenConfig> {
}
}
\ No newline at end of file
package com.schbrain.ci.jenkins.plugins.integration.builder.config.deploy;
import com.schbrain.ci.jenkins.plugins.integration.builder.BuilderContext;
import hudson.model.Describable;
import hudson.model.Descriptor;
import jenkins.model.Jenkins;
import java.io.IOException;
/**
* @author zhangdd on 2022/1/20
*/
public abstract class DeployStyleRadio implements Describable<DeployStyleRadio> {
//---------------------------------------------------------------------
// Abstract methods to be implemented by subclasses
//---------------------------------------------------------------------
public abstract String getDeployFileLocation(BuilderContext builderContext) throws IOException, InterruptedException;
@Override
@SuppressWarnings("unchecked")
public Descriptor<DeployStyleRadio> getDescriptor() {
return Jenkins.get().getDescriptor(getClass());
}
public abstract static class InventoryDescriptor extends Descriptor<DeployStyleRadio> {
}
}
\ No newline at end of file
package com.schbrain.ci.jenkins.plugins.integration.builder.config.deploy;
import com.schbrain.ci.jenkins.plugins.integration.builder.BuilderContext;
import com.schbrain.ci.jenkins.plugins.integration.builder.FileManager;
import com.schbrain.ci.jenkins.plugins.integration.builder.util.TemplateUtils;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.EnvVars;
import hudson.Extension;
import org.apache.commons.lang3.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import static com.schbrain.ci.jenkins.plugins.integration.builder.constants.Constants.DeployConstants.*;
/**
* @author zhangdd on 2022/1/20
*/
@SuppressWarnings("unused")
public class DeployTemplateComponent extends DeployStyleRadio {
private final String namespace;
private final String replicas;
private final String memoryRequest;
private final String memoryLimit;
private final String nodeTag;
private final String port;
@DataBoundConstructor
public DeployTemplateComponent(String namespace, String replicas, String memoryRequest, String memoryLimit, String nodeTag, String port) {
this.namespace = namespace;
this.replicas = replicas;
this.memoryRequest = memoryRequest;
this.memoryLimit = memoryLimit;
this.nodeTag = nodeTag;
this.port = port;
}
public String getNamespace() {
return namespace;
}
public String getReplicas() {
return replicas;
}
public String getMemoryRequest() {
return memoryRequest;
}
public String getMemoryLimit() {
return memoryLimit;
}
public String getNodeTag() {
return nodeTag;
}
public String getPort() {
return port;
}
@Override
public String getDeployFileLocation(BuilderContext context) throws IOException, InterruptedException {
Path templateFile = getDeployTemplate(context);
contributeEnv(context.getEnvVars());
TemplateUtils.evaluate(templateFile, context);
return templateFile.toString();
}
private void contributeEnv(EnvVars envVars) {
envVars.put(K8S_POD_NAMESPACE, getNamespace());
envVars.put(K8S_POD_PORT, getPort());
envVars.put(K8S_POD_REPLICAS, getReplicas());
envVars.put(K8S_POD_MEMORY_REQUEST, getMemoryRequest());
envVars.put(K8S_POD_MEMORY_LIMIT, getMemoryLimit());
envVars.put(K8S_POD_NODE_TAG, StringUtils.isBlank(getNodeTag()) ? "app" : getNodeTag());
}
private Path getDeployTemplate(BuilderContext context) {
File buildScriptDir = FileManager.getWorkspaceBuildScriptDir(context.getBuild());
return Paths.get(buildScriptDir.getPath(), DEPLOYMENT_TEMPLATE_FILE_NAME);
}
@Extension
public static class DescriptorImpl extends InventoryDescriptor {
@NonNull
@Override
public String getDisplayName() {
return "使用默认模版";
}
}
}
\ No newline at end of file
package com.schbrain.ci.jenkins.plugins.integration.builder.config.deploy;
import com.schbrain.ci.jenkins.plugins.integration.builder.BuilderContext;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import org.kohsuke.stapler.DataBoundConstructor;
/**
* @author zhangdd on 2022/1/20
*/
@SuppressWarnings("unused")
public class PointDeployFileComponent extends DeployStyleRadio {
private final String deployFileLocation;
@DataBoundConstructor
public PointDeployFileComponent(String deployFileLocation) {
this.deployFileLocation = deployFileLocation;
}
public String getDeployFileLocation() {
return deployFileLocation;
}
@Override
public String getDeployFileLocation(BuilderContext builderContext) {
return getDeployFileLocation();
}
@Extension
public static class DescriptorImpl extends InventoryDescriptor {
@NonNull
@Override
public String getDisplayName() {
return "指定部署文件位置";
}
}
}
\ No newline at end of file
package com.schbrain.ci.jenkins.plugins.integration.builder.config.deploy.service;
import com.schbrain.ci.jenkins.plugins.integration.builder.BuilderContext;
import com.schbrain.ci.jenkins.plugins.integration.builder.FileManager;
import com.schbrain.ci.jenkins.plugins.integration.builder.util.TemplateUtils;
import hudson.EnvVars;
import org.kohsuke.stapler.DataBoundConstructor;
import org.springframework.util.StringUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import static com.schbrain.ci.jenkins.plugins.integration.builder.constants.Constants.DeployConstants.*;
import static com.schbrain.ci.jenkins.plugins.integration.builder.constants.Constants.DockerConstants.APP_NAME;
/**
* @author liaozan
* @since 2022/3/10
*/
public class ServiceDeployConfig {
private final String serviceMode;
private final String serviceNamespace;
private final String serviceName;
private final String servicePort;
@DataBoundConstructor
public ServiceDeployConfig(String serviceMode, String serviceNamespace, String serviceName, String servicePort) {
this.serviceMode = serviceMode;
this.serviceNamespace = serviceNamespace;
this.serviceName = serviceName;
this.servicePort = servicePort;
}
public String getServiceMode() {
return serviceMode;
}
public String getServiceNamespace() {
return serviceNamespace;
}
public String getServiceName() {
return serviceName;
}
public String getServicePort() {
return servicePort;
}
public String getServiceDeployFileLocation(BuilderContext context) throws IOException, InterruptedException {
Path templateFile = getServiceDeployTemplate(context);
contributeEnv(context.getEnvVars());
TemplateUtils.evaluate(templateFile, context);
return templateFile.toString();
}
private void contributeEnv(EnvVars envVars) {
envVars.put(K8S_SERVICE_MODE, getServiceMode());
if (StringUtils.hasText(getServiceNamespace())) {
envVars.put(K8S_SERVICE_NAMESPACE, getServiceNamespace());
} else {
envVars.put(K8S_SERVICE_NAMESPACE, envVars.get(K8S_POD_NAMESPACE));
}
if (StringUtils.hasText(getServiceName())) {
envVars.put(K8S_SERVICE_NAME, getServiceName());
} else {
envVars.put(K8S_SERVICE_NAME, envVars.get(APP_NAME));
}
if (StringUtils.hasText(getServicePort())) {
envVars.put(K8S_SERVICE_PORT, getServicePort());
} else {
envVars.put(K8S_SERVICE_PORT, envVars.get(K8S_POD_PORT));
}
}
private Path getServiceDeployTemplate(BuilderContext context) {
File buildScriptDir = FileManager.getWorkspaceBuildScriptDir(context.getBuild());
return Paths.get(buildScriptDir.getPath(), SERVICE_TEMPLATE_FILE_NAME);
}
}
\ No newline at end of file
package com.schbrain.ci.jenkins.plugins.integration.builder.constants;
/**
* @author zhangdd on 2022/1/20
*/
public class Constants {
public static class BuildConstants {
public static final String DEFAULT_SCRIPT_GIT_REPO = "git@gitlab.schbrain.com:tools/build-script.git";
public static final String DEFAULT_SCRIPT_GIT_BRANCH = "main";
public static final String SCRIPT_ZIP_NAME = "build-script.zip";
public static final String BUILD_SCRIPT_NAME = "build-script";
public static final String ENV_VARS = "envVars";
}
public static class DeployConstants {
public static final String DEPLOYMENT_TEMPLATE_FILE_NAME = "k8s-deploy-template.yaml";
public static final String SERVICE_TEMPLATE_FILE_NAME = "k8s-service-template.yaml";
public static final String K8S_POD_NAMESPACE = "NAMESPACE";
public static final String K8S_POD_PORT = "PORT";
public static final String K8S_POD_REPLICAS = "REPLICAS";
public static final String K8S_POD_MEMORY_LIMIT = "MEMORY_LIMIT";
public static final String K8S_POD_MEMORY_REQUEST = "MEMORY_REQUEST";
public static final String K8S_POD_NODE_TAG = "NODE_TAG";
public static final String K8S_SERVICE_MODE = "SERVICE_MODE";
public static final String K8S_SERVICE_NAMESPACE = "SERVICE_NAMESPACE";
public static final String K8S_SERVICE_NAME = "SERVICE_NAME";
public static final String K8S_SERVICE_PORT = "SERVICE_PORT";
}
public static class DockerConstants {
public static final String BUILD_INFO_FILE_NAME = "dockerBuildInfo";
public static final String DOCKERFILE_NAME = "Dockerfile";
public static final String IMAGE = "IMAGE";
public static final String REGISTRY = "REGISTRY";
public static final String APP_NAME = "APP_NAME";
public static final String VERSION = "VERSION";
public static final String JAVA_OPTS = "JAVA_OPTS";
public static final String DISABLE_SKYWALKING_OPTIONS = "-Dskywalking.agent.enable=false";
}
public static class GitConstants {
public static final String GIT_PROPERTIES_FILE = "git.properties";
public static final String GIT_BRANCH = "git.branch";
public static final String GIT_COMMITTER = "git.commit.user.name";
}
}
\ No newline at end of file
package com.schbrain.ci.jenkins.plugins.integration.builder.env;
import com.schbrain.ci.jenkins.plugins.integration.builder.BuilderContext;
import com.schbrain.ci.jenkins.plugins.integration.builder.FileManager;
import com.schbrain.ci.jenkins.plugins.integration.builder.util.FileUtils;
import hudson.EnvVars;
import hudson.Extension;
import hudson.model.AbstractBuild;
import hudson.model.BuildVariableContributor;
import java.io.File;
import java.io.IOException;
import java.util.Map;
/**
* @author liaozan
* @since 2022/1/17
*/
@Extension
public class BuildEnvContributor extends BuildVariableContributor {
private static final String DELIMITER = "=";
public static void saveEnvVarsToDisk(BuilderContext context) throws IOException {
File envVarsFile = FileManager.getEnvVarsFile(context.getBuild());
FileUtils.writeUtf8String("", envVarsFile);
FileUtils.writeUtf8Map(context.getEnvVars(), envVarsFile, DELIMITER);
}
@Override
public void buildVariablesFor(AbstractBuild build, Map<String, String> variables) {
File envFilePath;
try {
envFilePath = FileManager.getEnvVarsFile(build);
} catch (IOException e) {
return;
}
EnvVars envVars = new EnvVars();
for (String line : FileUtils.readUtf8Lines(envFilePath)) {
String[] variablePair = line.split(DELIMITER);
// variables may not be split by =
if (variablePair.length != 1) {
envVars.putIfNotNull(variablePair[0], variablePair[1]);
}
}
variables.putAll(envVars);
}
}
\ No newline at end of file
package com.schbrain.ci.jenkins.plugins.integration.builder.util;
import com.schbrain.ci.jenkins.plugins.integration.builder.BuilderContext;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import hudson.FilePath;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.Map.Entry;
/**
* @author liaozan
* @since 2022/1/17
*/
public class FileUtils {
/**
* lookup the special file
*/
@CheckForNull
public static FilePath lookupFile(BuilderContext context, String fileName) throws IOException, InterruptedException {
return lookupFile(context.getWorkspace(), fileName, context.getLogger());
}
/**
* lookup the special file
*/
@CheckForNull
public static FilePath lookupFile(FilePath searchLocation, String fileName, Logger logger) throws IOException, InterruptedException {
if (searchLocation == null || !searchLocation.exists()) {
logger.println("searchLocation not exist", true);
return null;
}
FilePath[] fileList = searchLocation.list("**/" + fileName);
if (fileList.length == 0) {
logger.println("could not found matched file: %s", fileName);
return null;
}
return getTheClosestFile(fileList);
}
public static String toRelativePath(FilePath root, FilePath filePath) {
Path rootPath = Paths.get(root.getRemote());
Path targetFilePath = Paths.get(filePath.getRemote());
return rootPath.relativize(targetFilePath).toString();
}
public static FilePath getTheClosestFile(FilePath[] fileList) {
FilePath matched = fileList[0];
if (fileList.length == 1) {
return matched;
}
for (FilePath filePath : fileList) {
String filePathName = filePath.getRemote();
if (filePathName.length() < matched.getRemote().length()) {
matched = filePath;
}
}
return matched;
}
public static Map<String, String> filePathToMap(FilePath lookupFile) throws IOException, InterruptedException {
Map<String, String> result = new HashMap<>();
Properties properties = new Properties();
properties.load(new StringReader(lookupFile.readToString()));
for (String propertyName : properties.stringPropertyNames()) {
result.put(propertyName, properties.getProperty(propertyName));
}
return result;
}
public static void writeUtf8String(String content, File file) {
writeUtf8String(content, file.getPath());
}
public static void writeUtf8String(String content, String path) {
writeString(content, path, StandardCharsets.UTF_8);
}
public static void writeString(String content, String path, Charset charset) {
try {
Path filePath = getFilePath(path);
Files.write(filePath, content.getBytes(charset));
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
public static void writeUtf8Map(Map<String, String> variables, File file, String delimiter) {
try {
Path filePath = getFilePath(file.getPath());
BufferedWriter writer = Files.newBufferedWriter(filePath);
for (Entry<String, String> entry : variables.entrySet()) {
String content = String.format("%s%s%s", entry.getKey(), delimiter, entry.getValue());
writer.write(content);
writer.newLine();
writer.flush();
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
public static List<String> readUtf8Lines(File file) {
try {
Path filePath = getFilePath(file.getPath());
return Files.readAllLines(filePath);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
private static Path getFilePath(String path) throws IOException {
Path filePath = Paths.get(path);
if (Files.notExists(filePath)) {
Files.createFile(filePath);
}
return filePath;
}
}
\ No newline at end of file
package com.schbrain.ci.jenkins.plugins.integration.builder.util;
import java.io.PrintStream;
/**
* @author liaozan
* @since 2022/1/20
*/
public class Logger extends PrintStream {
private final PrintStream delegate;
private Logger(PrintStream delegate) {
super(delegate);
this.delegate = delegate;
}
public static Logger of(PrintStream delegate) {
return new Logger(delegate);
}
public void println(String content, Object... args) {
println(content, true, args);
}
public void println(String content, boolean format, Object... args) {
content = String.format(content, args);
println(content, format);
}
public void println(String content, boolean format) {
if (format) {
String wrappedContent = "|| " + content + " ||";
StringBuilder wrapperLine = new StringBuilder();
wrapperLine.append("=".repeat(wrappedContent.length()));
delegate.println();
delegate.println(wrapperLine);
delegate.println(wrappedContent);
delegate.println(wrapperLine);
delegate.println();
} else {
delegate.println(content);
}
}
}
\ No newline at end of file
package com.schbrain.ci.jenkins.plugins.integration.builder.util;
import com.schbrain.ci.jenkins.plugins.integration.builder.BuilderContext;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @author liaozan
* @since 2022/1/23
*/
public class TemplateUtils {
public static void evaluate(Path templateFile, BuilderContext context) throws IOException, InterruptedException {
if (templateFile == null) {
return;
}
String resolved = evaluate(Files.readString(templateFile), context.getEnvVars());
Files.write(templateFile, resolved.getBytes(StandardCharsets.UTF_8));
}
public static String evaluate(String template, Map<String, String> variables) {
if (null == template) {
return null;
}
if (null == variables || variables.isEmpty()) {
return template;
}
Map<String, Object> params = new LinkedHashMap<>(variables);
VelocityContext velocityContext = new VelocityContext(params);
StringWriter writer = new StringWriter();
Velocity.evaluate(velocityContext, writer, "Template Evaluate", template);
return writer.getBuffer().toString();
}
}
\ No newline at end of file
<?jelly escape-by-default='true'?>
<j:jelly xmlns:j="jelly:core" xmlns:l="/lib/layout" xmlns:st="jelly:stapler">
<l:layout title="build-scripts">
<l:main-panel>
<h2>构建脚本</h2>
<j:set var="url" value="${h.getNearestAncestorUrl(request,it)}"/>
<st:redirect url="${url}/list"/>
</l:main-panel>
</l:layout>
</j:jelly>
\ No newline at end of file
<?jelly escape-by-default='true'?>
<j:jelly xmlns:j="jelly:core" xmlns:f="/lib/form">
<f:entry/>
<f:optionalProperty field="mavenConfig" title="Maven编译"/>
<f:optionalProperty field="dockerConfig" title="Docker构建"/>
<f:optionalProperty field="deployToK8sConfig" title="Kubernetes部署"/>
<f:entry/>
</j:jelly>
<?jelly escape-by-default='true'?>
<j:jelly xmlns:j="jelly:core" xmlns:f="/lib/form">
<f:entry/>
<f:entry title="kubectl --config" description="为空时使用默认配置文件">
<f:textbox field="configLocation" value="${instance.configLocation}"/>
</f:entry>
<f:entry title="选择 Deployment 部署方式">
<f:hetero-radio field="deployStyle" descriptors="${descriptor.getDeployStyles()}"/>
</f:entry>
<f:optionalBlock title="部署 Service" field="serviceDeployConfig" checked="${instance.serviceDeployConfig != null}">
<j:set var="currentConfig" value="${instance.serviceDeployConfig}"/>
<j:set var="defaultValue" value="ClusterIP"/>
<f:entry title="Service 类型">
<f:radio name="serviceMode" title="ClusterIP" checked="${currentConfig.serviceMode == null || currentConfig.serviceMode == 'ClusterIP'}" value="ClusterIP"/>
<f:radio name="serviceMode" title="LoadBalancer" checked="${currentConfig.serviceMode == 'LoadBalancer'}" value="LoadBalancer"/>
</f:entry>
<f:entry title="Service 命名空间(为空时取 PodNamespace)">
<f:textbox field="serviceNamespace" value="${instance.serviceDeployConfig.serviceNamespace}"/>
</f:entry>
<f:entry title="Service 名称(为空时取 PodName)">
<f:textbox field="serviceName" value="${instance.serviceDeployConfig.serviceName}"/>
</f:entry>
<f:entry title="Service 端口号(为空时取 PodPort)">
<f:textbox field="servicePort" value="${instance.serviceDeployConfig.servicePort}"/>
</f:entry>
</f:optionalBlock>
<f:entry/>
</j:jelly>
\ No newline at end of file
<?jelly escape-by-default='true'?>
<j:jelly xmlns:j="jelly:core" xmlns:f="/lib/form">
<f:entry/>
<f:entry title="构建脚本仓库地址" description="如未配置默认为内置的build-script">
<f:textbox field="buildScriptUrl"/>
</f:entry>
<f:entry title="构建脚本仓库分支" description="如未配置默认master分支">
<f:textbox field="buildScriptBranch"/>
</f:entry>
<f:entry>
<f:optionalBlock>
<f:checkbox title="构建镜像" field="buildImage" checked="${instance.buildImage}"/>
</f:optionalBlock>
</f:entry>
<f:entry title="JAVA_OPTS" description="配置Dockerfile中jvm参数">
<f:textbox field="javaOpts"/>
</f:entry>
<f:entry>
<f:optionalBlock>
<f:checkbox title="禁用Skywalking" field="disableSkywalking" checked="${instance.disableSkywalking}"/>
</f:optionalBlock>
</f:entry>
<f:entry>
<f:optionalBlock title="推送镜像" field="pushConfig" checked="${instance.pushConfig.pushImage}">
<f:invisibleEntry>
<f:checkbox field="pushImage" checked="true" value="${instance.pushConfig.pushImage}"/>
</f:invisibleEntry>
<f:entry/>
<f:entry title="镜像仓库" description="为空时默认获取 pom.xml 插件中配置的仓库地址,如项目未指定,则采用 parent pom 插件中的默认值(根据 profile 区分)">
<f:textbox field="registry" value="${instance.pushConfig.registry}"/>
</f:entry>
</f:optionalBlock>
</f:entry>
<f:entry>
<f:optionalBlock>
<f:checkbox title="构建后删除" field="deleteImageAfterBuild" checked="${instance.deleteImageAfterBuild}"/>
</f:optionalBlock>
</f:entry>
<f:entry/>
</j:jelly>
\ No newline at end of file
<?jelly escape-by-default='true'?>
<j:jelly xmlns:j="jelly:core" xmlns:f="/lib/form">
<f:entry/>
<f:entry title="Maven命令" description="如未配置 M2_HOME 环境,请在命令前加入指向 mvn 命令的全路径">
<f:textbox field="mvnCommand" default="mvn clean package -U -B -Dmaven.test.skip=true"/>
</f:entry>
<f:entry title="JAVA_HOME" description="如未配置 JAVA_HOME 环境,则会使用本地默认 JAVA_HOME">
<f:textbox field="javaHome"/>
</f:entry>
<f:entry/>
</j:jelly>
<?jelly escape-by-default='true'?>
<j:jelly xmlns:j="jelly:core" xmlns:f="/lib/form">
<f:entry/>
<f:entry title="Pod 命名空间">
<f:textbox field="namespace" value="${instance.namespace}"/>
</f:entry>
<f:entry title="Pod 副本数">
<f:textbox field="replicas" value="${instance.replicate}" default="1"/>
</f:entry>
<f:entry title="Pod 内存限制(request)">
<f:textbox field="memoryRequest" value="${instance.memoryRequest}" default="2048Mi"/>
</f:entry>
<f:entry title="Pod 内存限制(limit)">
<f:textbox field="memoryLimit" value="${instance.memoryLimit}" default="2048Mi"/>
</f:entry>
<f:entry title="Pod 部署节点标签 (用于指定亲和性)">
<f:textbox field="nodeTag" value="${instance.nodeTag}" default="app"/>
</f:entry>
<f:entry title="Pod 端口号">
<f:textbox field="port" value="${instance.port}"/>
</f:entry>
<f:entry/>
</j:jelly>
\ No newline at end of file
<?jelly escape-by-default='true'?>
<j:jelly xmlns:j="jelly:core" xmlns:f="/lib/form">
<f:entry/>
<f:entry title="部署文件路径" description="指定使用的部署文件位置">
<f:textbox field="deployFileLocation" value="${instance.deployFileLocation}"/>
</f:entry>
<f:entry/>
</j:jelly>
\ No newline at end of file
<?jelly escape-by-default='true'?>
<!--
This view is used to render the installed plugins page.
-->
<div>
This plugin provider integration with Kubernetes.
</div>
\ No newline at end of file
......@@ -16,7 +16,6 @@
<modules>
<module>integration-maven-plugin</module>
<module>integration-jenkins-plugin</module>
</modules>
</project>
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment