/
InstanceAPI.java
245 lines (207 loc) · 7.84 KB
/
InstanceAPI.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package io.jenkins.plugins.pipeline.restful.api;
import com.cloudbees.workflow.util.ServeJson;
import hudson.Extension;
import hudson.model.RootAction;
import hudson.model.User;
import hudson.util.HttpResponses;
import jenkins.model.Jenkins;
import jenkins.model.JenkinsLocationConfiguration;
import jenkins.model.identity.IdentityRootAction;
import jenkins.security.ApiTokenProperty;
import jenkins.slaves.JnlpSlaveAgentProtocol;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.*;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.annotation.CheckForNull;
import javax.annotation.MatchesPattern;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
@Extension
@Restricted(NoExternalUse.class)
public class InstanceAPI implements RootAction {
private static final Logger LOGGER = Logger.getLogger(InstanceAPI.class.getName());
@CheckForNull
@Override
public String getIconFileName() {
return null;
}
@CheckForNull
@Override
public String getDisplayName() {
return "Jenkins instance API";
}
@CheckForNull
@Override
public String getUrlName() {
return "instance";
}
@ServeJson
public JenkinsInstance doIndex() {
IdentityRootAction identityAction = new IdentityRootAction();
JenkinsInstance jenkinsInstance = new JenkinsInstance(identityAction.getFingerprint(), identityAction.getPublicKey());
jenkinsInstance.setSystemMessage(Jenkins.get().getSystemMessage());
return jenkinsInstance;
}
@ServeJson
public Properties doSystemProperties() {
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
LOGGER.severe("no permission to get system properties");
return new Properties();
}
return System.getProperties();
}
@ServeJson
public Map<String, String> doSystemEnv() {
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
LOGGER.severe("no permission to get system environment");
return new HashMap<>();
}
return System.getenv();
}
@RequirePOST
public HttpResponse doUpdateMessage(StaplerRequest req) {
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
LOGGER.severe("no permission to set system message");
return HttpResponses.errorJSON("no permission to set system message");
}
String message = req.getParameter("message");
try {
Jenkins.get().setSystemMessage(message);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "cannot set system message of Jenkins", e);
return HttpResponses.errorJSON(e.getMessage());
}
return HttpResponses.ok();
}
@RequirePOST
public HttpResponse doAgentSecret(@QueryParameter String name) {
try {
return HttpResponses.text(JnlpSlaveAgentProtocol.SLAVE_SECRET.mac(name));
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "cannot get the slave secret", e);
return HttpResponses.errorJSON(e.getMessage());
}
}
/**
* Generate the user token which is prepare for https://github.com/jenkins-zh/jenkins-cli
* @param rsp
* @param callback
* @throws IOException
* @throws ServletException
*/
public void doGenerateToken(StaplerResponse rsp, @QueryParameter(required = true) String callback) throws IOException, ServletException {
User user = User.current();
if (user == null) {
System.out.println("not login yet");
return;
}
ApiTokenProperty token = user.getProperty(ApiTokenProperty.class);
ApiTokenProperty.DescriptorImpl desc = (ApiTokenProperty.DescriptorImpl) token.getDescriptor();
HttpResponse response = desc.doGenerateNewToken(user, "jcli-auto-");
ByteArrayOutputStream output = new ByteArrayOutputStream();
StaplerResponseWrapper out = new StaplerResponseWrapper(rsp) {
@Override
public ServletOutputStream getOutputStream() throws IOException {
return new ServletOutputStream(){
@Override
public void write(int b) throws IOException {
output.write(b);
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setWriteListener(WriteListener writeListener) {
}
};
}
};
response.generateResponse(null, out, null);
HttpURLConnection urlCon = (HttpURLConnection) new URL(callback).openConnection();
urlCon.setRequestMethod("POST");
urlCon.setDoOutput(true);
urlCon.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
JSONObject jsonObj = JSONObject.fromObject(output.toString());
jsonObj.getJSONObject("data").put("userName", user.getFullName());
urlCon.setFixedLengthStreamingMode(jsonObj.toString().length());
try(OutputStream os = urlCon.getOutputStream()) {
os.write(jsonObj.toString().getBytes());
}
String result = "All set, jcli is ready! For example: 'jcli plugin list'. You can close this page now.";
rsp.setContentLength(result.length());
rsp.getWriter().write(result);
}
@RequirePOST
public HttpResponse doSetLocation(@QueryParameter String rootURL, @QueryParameter String email) {
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
return HttpResponses.errorJSON("cannot set Jenkins location due to lack of permission");
}
JenkinsLocationConfiguration config = JenkinsLocationConfiguration.get();
if (config == null) {
return HttpResponses.errorJSON("cannot set Jenkins location due to it is undefined");
}
if (StringUtils.isNotBlank(rootURL)) {
config.setUrl(rootURL);
}
if (StringUtils.isNotBlank(email)) {
config.setAdminAddress(email);
}
config.save();
return HttpResponses.ok();
}
@ServeJson
public Map<String, String> doGetLocation() {
Map<String, String> data = new HashMap<>();
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
return data;
}
JenkinsLocationConfiguration config = JenkinsLocationConfiguration.get();
if (config != null) {
data.put("rootURL", config.getUrl());
data.put("email", config.getAdminAddress());
}
return data;
}
}
class JenkinsInstance {
private String fingerprint;
private String publicKey;
private String systemMessage;
public JenkinsInstance(String fingerprint, String publicKey) {
this.fingerprint = fingerprint;
this.publicKey = publicKey;
}
public String getFingerprint() {
return fingerprint;
}
public void setFingerprint(String fingerprint) {
this.fingerprint = fingerprint;
}
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
public String getSystemMessage() {
return systemMessage;
}
public void setSystemMessage(String systemMessage) {
this.systemMessage = systemMessage;
}
}