-
Notifications
You must be signed in to change notification settings - Fork 5
/
salt.ts
221 lines (204 loc) · 6.71 KB
/
salt.ts
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
import axios, { Axios, RawAxiosRequestHeaders } from "axios";
import { URLSearchParams } from "url";
import EventSource from "eventsource";
interface SaltConfig {
url: string;
username?: string;
password?: string;
token?: string;
eauth?: string;
}
interface FunOptions {
client?: "local" | "runner" | "wheel";
arg?: string | string[];
kwarg?: any;
tgt_type?: "glob" | "pcre" | "list" | "grain" | "grain_pcre" | "pillar" | "pillar_pcre" | "nodegroup" | "range" | "compound" | "ipcidr";
pillar?: string;
timeout?: number;
full_return?: boolean;
}
export class Salt {
config: SaltConfig = {
url: "http://localhost:8000",
eauth: "pam",
};
headers: RawAxiosRequestHeaders = {
Accept: "application/json",
};
axios: Axios;
debug: boolean;
private token: string;
private expire;
constructor(config: SaltConfig, debug = false, axiosInstance: Axios | undefined = undefined) {
this.config = config;
this.debug = debug;
if (typeof axiosInstance === "undefined") {
this.axios =
axiosInstance ||
axios.create({
headers: {
Accept: "application/json",
},
});
}
if (this.debug) {
// Set request startTime
this.axios.interceptors.request.use(
function (config: any) {
config.metadata = { startTime: new Date() };
return config;
},
function (error) {
return Promise.reject(error);
},
);
// Set request endTime and calculate duration
this.axios.interceptors.response.use(
function (response: any) {
response.config.metadata.endTime = new Date();
response.duration = response.config.metadata.endTime - response.config.metadata.startTime;
return response;
},
function (error) {
error.config.metadata.endTime = new Date();
error.duration = error.config.metadata.endTime - error.config.metadata.startTime;
return Promise.reject(error);
},
);
}
}
/**
* Log in to receive a session token
*/
async login(): Promise<void> {
const form: { [key: string]: any } = {
eauth: typeof this.config.eauth === "string" ? this.config.eauth : "pam",
};
if (typeof this.config.username !== "undefined") form.username = this.config.username;
if (typeof this.config.password !== "undefined") form.password = this.config.password;
if (typeof this.config.token !== "undefined") form.token = this.config.token;
const response = await this.axios.post(this.config.url + "/login", new URLSearchParams(form), {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
});
const data = response.data;
this.debugLog({ url: this.config.url, path: "/login", perms: data.return[0].perms }, response);
if (typeof data === "object" && typeof data.return === "object" && typeof data.return[0].token === "string") {
this.token = data.return[0].token;
this.expire = data.return[0].expire;
} else {
throw "Got no token";
}
}
/**
* Opens An HTTP stream of the Salt master event bus
* @returns EventSource
*/
async eventSource(): Promise<EventSource> {
if ((this.expire <= Date.now() / 1000) as any) {
this.debugLog({ path: "/events", log: "Token expired, logging in again" });
// Token expired, logging in again
await this.login();
}
return new EventSource(`${this.config.url}/events`, { headers: { ...this.headers, "X-Auth-Token": this.token } });
}
/**
* Send one or more Salt commands in the request body
* @param tgt
* @param fun
* @param funOptions
* @returns
*/
async fun(tgt = "*", fun: string | string[] = "test.ping", funOptions: FunOptions = undefined): Promise<any> {
if ((this.expire <= Date.now() / 1000) as any) {
// Debug log
this.debugLog({ function: "fun", log: "Token expired, logging in again" });
// Token expired, logging in again
await this.login();
}
const form: { [key: string]: any } = { tgt, fun, client: "local" };
if (funOptions?.client) form.arg = funOptions.client;
if (funOptions?.arg) form.arg = funOptions.arg;
if (funOptions?.kwarg) form.kwarg = funOptions.kwarg;
if (funOptions?.tgt_type) form.tgt_type = funOptions.tgt_type;
if (funOptions?.pillar) form.pillar = funOptions.pillar;
if (funOptions?.timeout) form.timeout = funOptions.timeout;
return this.axios
.post(this.config.url, form, {
headers: { ...this.headers, "X-Auth-Token": this.token },
})
.then((response) => {
this.debugLog(form, response);
return response.data;
})
.catch((err) => {
this.debugLog(form, undefined, err);
throw err;
});
}
/**
* List minions or get minion details
* @param mid
* @returns
*/
async minions(mid = ""): Promise<any> {
if ((this.expire <= Date.now() / 1000) as any) {
this.debugLog({ path: "/minions", mid, log: "Token expired, logging in again" });
// Token expired, logging in again
await this.login();
}
return this.axios
.get(`${this.config.url}/minions/${mid}`, {
headers: { ...this.headers, "X-Auth-Token": this.token },
})
.then((response) => {
this.debugLog({ path: "/minions", mid }, response);
return response.data;
})
.catch((err) => {
this.debugLog({ path: "/minions", mid }, undefined, err);
throw err;
});
}
/**
* List jobs or show a single job from the job cache.
* @param jid
* @returns
*/
async jobs(jid = ""): Promise<any> {
if ((this.expire <= Date.now() / 1000) as any) {
this.debugLog({ path: "/jobs", jid, log: "Token expired, logging in again" });
// Token expired, logging in again
await this.login();
}
return this.axios
.get(`${this.config.url}/jobs/${jid}`, {
headers: { ...this.headers, "X-Auth-Token": this.token },
})
.then((response) => {
this.debugLog({ path: "/jobs", jid }, response);
return response.data;
})
.catch((err) => {
this.debugLog({ path: "/jobs", jid }, undefined, err);
throw err;
});
}
/**
* Debug log, if debug is enabled logs requests with duration to console
* @param debugObject
* @param response object
* @param error object
*/
private debugLog(debugObject: any, response: any = undefined, error: any = undefined): void {
if (!this.debug) return;
if (response) debugObject.duration = response.duration / 1000;
if (error) {
debugObject.duration = error.duration / 1000;
console.log(`[NODE-SALT-API] ${error.message}`);
}
console.log("[NODE-SALT-API]");
console.log(debugObject);
}
}