-
Notifications
You must be signed in to change notification settings - Fork 133
Expand file tree
/
Copy pathserver.ts
More file actions
258 lines (229 loc) Β· 10 KB
/
server.ts
File metadata and controls
258 lines (229 loc) Β· 10 KB
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
246
247
248
249
250
251
252
253
254
255
256
257
258
import path from "path";
import { commands, l10n, window } from "vscode";
import IBMi from "../api/IBMi";
import { Tools } from "../api/Tools";
import { DebugConfiguration, getDebugServiceDetails, getJavaHome } from "../api/configuration/DebugConfiguration";
import { instance } from "../instantiate";
import { CustomUI } from "../webviews/CustomUI";
export type DebugJobs = {
server?: string
service?: string
}
export const MIN_DEBUG_VERSION = 3;
export function debugPTFInstalled(connection: IBMi) {
return connection.debugPTFInstalled()
}
export async function isDebugSupported(connection: IBMi) {
return debugPTFInstalled(connection) && (await getDebugServiceDetails(connection)).semanticVersion().major >= MIN_DEBUG_VERSION;
}
export async function startService(connection: IBMi) {
const checkAuthority = async (user?: string) => {
if (user && !await connection.getContent().checkObject({ library: "QSYS", name: user, type: "*USRPRF" }, ["*USE"])) {
throw new Error(`You don't have *USE authority on user profile ${user}`);
}
if (user !== "QDBGSRV" && !(await connection.getContent().checkUserSpecialAuthorities(["*ALLOBJ", "*SECADM"], user)).valid) {
throw new Error(`User ${user || connection.currentUser} doesn't have *ALLOBJ special authority`);
}
};
try {
const debugServiceJavaVersion = (await getDebugServiceDetails(connection)).java;
// const debugConfig = await new DebugConfiguration(connection).load();
const javaHome = getJavaHome(connection, debugServiceJavaVersion)
const submitOptions = await window.showInputBox({
title: l10n.t(`Debug Service submit options`),
prompt: l10n.t(`Valid parameters for SBMJOB`),
value: `JOBQ(QSYS/QUSRNOMAX) JOBD(QSYS/QSYSJOBD) OUTQ(QUSRSYS/QDBGSRV) USER(QDBGSRV)`
});
if (submitOptions) {
const submitUser = /USER\(([^)]+)\)/.exec(submitOptions)?.[1]?.toLocaleUpperCase();
if (submitUser && submitUser !== "*CURRENT") {
await checkAuthority(submitUser);
}
else {
await checkAuthority();
}
let debugConfig: DebugConfiguration;
let debugConfigLoaded = false;
try {
debugConfig = await new DebugConfiguration(connection).load();
const config = connection.getConfig();
config.debugPort = debugConfig.getRemoteServiceSecuredPort();
config.debugSepPort = debugConfig.getRemoteServiceSepDaemonPort();
IBMi.connectionManager.update(config);
debugConfigLoaded = true;
} catch (error) {
throw new Error(`Could not load debug service configuration: ${error}`);
} finally {
IBMi.GlobalStorage.setServerSettingsCacheSpecific(connection.currentConnectionName, { debugConfigLoaded });
}
// Attempt to make log directory
await connection.sendCommand({ command: `mkdir -p ${debugConfig.getRemoteServiceWorkspace()}` });
// Change owner to QDBGSRV
if (submitUser && submitUser !== "QDBGSRV") {
await connection.sendCommand({ command: `chown ${submitUser} ${debugConfig.getRemoteServiceWorkspace()}` });
}
// Change the permissions to 777
await connection.sendCommand({ command: `chmod 777 ${debugConfig.getRemoteServiceWorkspace()}` });
const command = `QSYS/SBMJOB JOB(QDBGSRV) SYSLIBL(*SYSVAL) CURLIB(*USRPRF) INLLIBL(*JOBD) ${submitOptions} CMD(QSH CMD('export JAVA_HOME=${javaHome};${debugConfig.getRemoteServiceBin()}/startDebugService.sh > ${debugConfig.getNavigatorLogFile()} 2>&1'))`
const submitResult = await connection.runCommand({ command, noLibList: true });
if (submitResult.code === 0) {
const submitMessage = Tools.parseMessages(submitResult.stderr || submitResult.stdout).findId("CPC1221")?.text;
if (submitMessage) {
const [job] = /([^\/\s]+)\/([^\/]+)\/([^\/\s]+)/.exec(submitMessage) || [];
if (job) {
let tries = 0;
const checkJob = async (done: (started: boolean) => void) => {
if (tries++ < 30) {
const jobDetail = await readActiveJob(connection, job);
if (jobDetail && typeof jobDetail === "object" && !["HLD", "MSGW", "END"].includes(String(jobDetail.JOB_STATUS))) {
if ((await getDebugEngineJobs()).service) {
window.showInformationMessage(l10n.t(`Debug service started.`));
refreshDebugSensitiveItems();
done(true);
}
else {
setTimeout(() => checkJob(done), 1000);
}
} else {
let reason;
if (typeof jobDetail === "object") {
reason = `job is in ${String(jobDetail.JOB_STATUS)} status`;
}
else if (jobDetail) {
reason = jobDetail;
}
else {
reason = "job has ended";
}
window.showErrorMessage(`Debug Service job ${job} failed: ${reason}.`, 'Open output').then(() => openQPRINT(connection, job));
done(false);
}
}
else {
done(false);
}
};
return await new Promise<boolean>(checkJob);
}
}
}
throw new Error(`Failed to submit Debug Service job: ${submitResult.stderr || submitResult.stdout}`)
}
}
catch (error) {
window.showErrorMessage(String(error));
}
return false;
}
export async function stopService(connection: IBMi) {
const debugConfig = await new DebugConfiguration(connection).load();
const endResult = await connection.sendCommand({
command: `${path.posix.join(debugConfig.getRemoteServiceBin(), `stopDebugService.sh`)}`
});
if (!endResult.code) {
window.showInformationMessage(l10n.t(`Debug service stopped.`));
refreshDebugSensitiveItems();
return true;
} else {
window.showErrorMessage(l10n.t(`Failed to stop debug service: {0}`, endResult.stdout || endResult.stderr));
return false;
}
}
export async function getDebugEngineJobs(): Promise<DebugJobs> {
const rows = await instance.getConnection()?.runSQL([
"select 'SERVER' as TYPE, JOB_NAME from table(qsys2.job_info(job_status_filter => '*ACTIVE', job_type_filter => '*BATCH', job_name_filter => 'QB5ROUTER'))",
"Union",
"select 'SERVICE' as TYPE, JOB_NAME from table(qsys2.job_info(job_status_filter => '*ACTIVE', job_type_filter => '*BATCH', job_name_filter => 'QDBGSRV'))"
].join(" "));
return {
server: rows?.find(row => row.TYPE === 'SERVER')?.JOB_NAME as string,
service: rows?.find(row => row.TYPE === 'SERVICE')?.JOB_NAME as string
}
}
export async function isDebugEngineRunning() {
const debugJobs = await getDebugEngineJobs();
return Boolean(debugJobs.server) && Boolean(debugJobs.service);
}
/**
* Gets a list of debug jobs stuck at MSGW in QSYSWRK
*/
export async function getStuckJobs(connection: IBMi): Promise<string[]> {
const sql = [
`SELECT JOB_NAME`,
`FROM TABLE(QSYS2.ACTIVE_JOB_INFO(SUBSYSTEM_LIST_FILTER => 'QSYSWRK', CURRENT_USER_LIST_FILTER => '${connection.currentUser.toUpperCase()}')) X`,
`where JOB_STATUS = 'MSGW'`,
].join(` `);
const jobs = await connection.runSQL(sql);
return jobs.map(row => String(row.JOB_NAME));
}
export function endJobs(jobIds: string[], connection: IBMi) {
const promises = jobIds.map(id => connection.sendCommand({
command: `system "ENDJOB JOB(${id}) OPTION(*IMMED)"`
}));
return Promise.all(promises);
}
export async function startServer() {
const result = await instance.getConnection()?.runCommand({ command: "STRDBGSVR", noLibList: true });
if (result) {
if (result.code) {
window.showErrorMessage(l10n.t(`Failed to start debug server: {0}`, result.stderr));
return false;
}
else {
refreshDebugSensitiveItems();
window.showInformationMessage(l10n.t(`Debug server started.`));
}
}
return true;
}
export async function stopServer() {
const result = await instance.getConnection()?.runCommand({ command: "ENDDBGSVR", noLibList: true });
if (result) {
if (result.code) {
window.showErrorMessage(l10n.t(`Failed to stop debug server: {0}`, result.stderr));
return false;
}
else {
refreshDebugSensitiveItems();
window.showInformationMessage(l10n.t(`Debug server stopped.`));
}
}
return true;
}
export function refreshDebugSensitiveItems() {
commands.executeCommand("code-for-ibmi.updateConnectedBar");
commands.executeCommand("code-for-ibmi.debug.refresh");
}
export async function readActiveJob(connection: IBMi, job: string) {
try {
return (await connection.runSQL(
`select job_name_short "Job name", job_user "Job user", job_number "Job number", subsystem_library_name concat '/' concat subsystem as "Subsystem", authorization_name "Current user", job_status "Job status", memory_pool "Memory pool" from table(qsys2.active_job_info(job_name_filter => '${job.substring(job.lastIndexOf('/') + 1)}')) where job_name = '${job}' fetch first row only`
)).at(0);
} catch (error) {
return String(error);
}
}
export async function readJVMInfo(connection: IBMi, job: string) {
try {
return (await connection.runSQL(`
select START_TIME "Start time", JAVA_HOME "Java Home", USER_DIRECTORY "User directory", CURRENT_HEAP_SIZE "Current memory", MAX_HEAP_SIZE "Maximum allowed memory"
from QSYS2.JVM_INFO
where job_name = '${job}'
fetch first row only`)).at(0);
} catch (error) {
return String(error);
}
}
async function openQPRINT(connection: IBMi, job: string) {
const lines = (await connection.runSQL(`select SPOOLED_DATA from table (systools.spooled_file_data(job_name => '${job}', spooled_file_name => 'QPRINT')) order by ORDINAL_POSITION`))
.map(row => String(row.SPOOLED_DATA));
if (lines.length) {
new CustomUI()
.addParagraph(`<pre><code>${lines.join("<br/>")}</code></pre>`)
.setOptions({ fullWidth: true })
.loadPage(`${job} QPRINT`);
}
else {
window.showWarningMessage(`No QPRINT spooled file found for job ${job}!`);
}
}