-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPolicyRefresher.java
More file actions
445 lines (355 loc) · 14.4 KB
/
PolicyRefresher.java
File metadata and controls
445 lines (355 loc) · 14.4 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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
package org.apache.ranger.plugin.util;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Reader;
import java.io.Writer;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ranger.admin.client.RangerAdminClient;
import org.apache.ranger.authorization.hadoop.config.RangerConfiguration;
import org.apache.ranger.plugin.service.RangerBasePlugin;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class PolicyRefresher extends Thread {
private static final Log LOG = LogFactory.getLog(PolicyRefresher.class);
private static final Log PERF_POLICYENGINE_INIT_LOG = RangerPerfTracer.getPerfLogger("policyengine.init");
private final RangerBasePlugin plugIn;
private final String serviceType;
private final String serviceName;
private final RangerAdminClient rangerAdmin;
private final String cacheFileName;
private final String cacheDir;
private final Gson gson;
private final boolean disableCacheIfServiceNotFound;
private long pollingIntervalMs = 30 * 1000;
private long lastKnownVersion = -1L;
private long lastActivationTimeInMillis;
private boolean policiesSetInPlugin;
private boolean serviceDefSetInPlugin;
public PolicyRefresher(RangerBasePlugin plugIn, String serviceType, String appId, String serviceName, RangerAdminClient rangerAdmin, long pollingIntervalMs, String cacheDir) {
if(LOG.isDebugEnabled()) {
LOG.debug("==> PolicyRefresher(serviceName=" + serviceName + ").PolicyRefresher()");
}
this.plugIn = plugIn;
this.serviceType = serviceType;
this.serviceName = serviceName;
this.rangerAdmin = rangerAdmin;
this.pollingIntervalMs = pollingIntervalMs;
if(StringUtils.isEmpty(appId)) {
appId = serviceType;
}
String cacheFilename = String.format("%s_%s.json", appId, serviceName);
cacheFilename = cacheFilename.replace(File.separatorChar, '_');
cacheFilename = cacheFilename.replace(File.pathSeparatorChar, '_');
this.cacheFileName = cacheFilename;
this.cacheDir = cacheDir;
Gson gson = null;
try {
gson = new GsonBuilder().setDateFormat("yyyyMMdd-HH:mm:ss.SSS-Z").setPrettyPrinting().create();
} catch(Throwable excp) {
LOG.fatal("PolicyRefresher(): failed to create GsonBuilder object", excp);
}
this.gson = gson;
String propertyPrefix = "ranger.plugin." + serviceType;
disableCacheIfServiceNotFound = RangerConfiguration.getInstance().getBoolean(propertyPrefix + ".disable.cache.if.servicenotfound", true);
if(LOG.isDebugEnabled()) {
LOG.debug("<== PolicyRefresher(serviceName=" + serviceName + ").PolicyRefresher()");
}
}
/**
* @return the plugIn
*/
public RangerBasePlugin getPlugin() {
return plugIn;
}
/**
* @return the serviceType
*/
public String getServiceType() {
return serviceType;
}
/**
* @return the serviceName
*/
public String getServiceName() {
return serviceName;
}
/**
* @return the rangerAdmin
*/
public RangerAdminClient getRangerAdminClient() {
return rangerAdmin;
}
/**
* @return the pollingIntervalMilliSeconds
*/
public long getPollingIntervalMs() {
return pollingIntervalMs;
}
/**
* @param pollingIntervalMilliSeconds the pollingIntervalMilliSeconds to set
*/
public void setPollingIntervalMilliSeconds(long pollingIntervalMilliSeconds) {
this.pollingIntervalMs = pollingIntervalMilliSeconds;
}
public long getLastActivationTimeInMillis() {
return lastActivationTimeInMillis;
}
public void setLastActivationTimeInMillis(long lastActivationTimeInMillis) {
this.lastActivationTimeInMillis = lastActivationTimeInMillis;
}
public void startRefresher() {
loadPolicy();
super.start();
}
public void stopRefresher() {
super.interrupt();
try {
super.join();
} catch (InterruptedException excp) {
LOG.warn("PolicyRefresher(serviceName=" + serviceName + "): error while waiting for thread to exit", excp);
}
}
public void run() {
if(LOG.isDebugEnabled()) {
LOG.debug("==> PolicyRefresher(serviceName=" + serviceName + ").run()");
}
while(true) {
loadPolicy();
try {
Thread.sleep(pollingIntervalMs);
} catch(InterruptedException excp) {
LOG.info("PolicyRefresher(serviceName=" + serviceName + ").run(): interrupted! Exiting thread", excp);
break;
}
}
if(LOG.isDebugEnabled()) {
LOG.debug("<== PolicyRefresher(serviceName=" + serviceName + ").run()");
}
}
private void loadPolicy() {
if(LOG.isDebugEnabled()) {
LOG.debug("==> PolicyRefresher(serviceName=" + serviceName + ").loadPolicy()");
}
RangerPerfTracer perf = null;
if(RangerPerfTracer.isPerfTraceEnabled(PERF_POLICYENGINE_INIT_LOG)) {
perf = RangerPerfTracer.getPerfTracer(PERF_POLICYENGINE_INIT_LOG, "PolicyRefresher.loadPolicy(serviceName=" + serviceName + ")");
long freeMemory = Runtime.getRuntime().freeMemory();
long totalMemory = Runtime.getRuntime().totalMemory();
PERF_POLICYENGINE_INIT_LOG.debug("In-Use memory: " + (totalMemory-freeMemory) + ", Free memory:" + freeMemory);
}
try {
//load policy from PolicyAdmin
ServicePolicies svcPolicies = loadPolicyfromPolicyAdmin();
if (svcPolicies == null) {
//if Policy fetch from Policy Admin Fails, load from cache
if (!policiesSetInPlugin) {
svcPolicies = loadFromCache();
}
} else {
saveToCache(svcPolicies);
}
RangerPerfTracer.log(perf);
if (PERF_POLICYENGINE_INIT_LOG.isDebugEnabled()) {
long freeMemory = Runtime.getRuntime().freeMemory();
long totalMemory = Runtime.getRuntime().totalMemory();
PERF_POLICYENGINE_INIT_LOG.debug("In-Use memory: " + (totalMemory - freeMemory) + ", Free memory:" + freeMemory);
}
if (svcPolicies != null) {
plugIn.setPolicies(svcPolicies);
plugIn.setHaveNewPolicy(true);
policiesSetInPlugin = true;
setLastActivationTimeInMillis(System.currentTimeMillis());
lastKnownVersion = svcPolicies.getPolicyVersion();
} else {
if (!policiesSetInPlugin && !serviceDefSetInPlugin) {
plugIn.setPolicies(null);
serviceDefSetInPlugin = true;
}
}
} catch (RangerServiceNotFoundException snfe) {
if (disableCacheIfServiceNotFound) {
disableCache();
plugIn.setPolicies(null);
setLastActivationTimeInMillis(System.currentTimeMillis());
lastKnownVersion = -1;
serviceDefSetInPlugin = true;
}
} catch (Exception excp) {
LOG.error("Encountered unexpected exception, ignoring..", excp);
}
if(LOG.isDebugEnabled()) {
LOG.debug("<== PolicyRefresher(serviceName=" + serviceName + ").loadPolicy()");
}
}
private ServicePolicies loadPolicyfromPolicyAdmin() throws RangerServiceNotFoundException {
if(LOG.isDebugEnabled()) {
LOG.debug("==> PolicyRefresher(serviceName=" + serviceName + ").loadPolicyfromPolicyAdmin()");
}
ServicePolicies svcPolicies = null;
RangerPerfTracer perf = null;
if(RangerPerfTracer.isPerfTraceEnabled(PERF_POLICYENGINE_INIT_LOG)) {
perf = RangerPerfTracer.getPerfTracer(PERF_POLICYENGINE_INIT_LOG, "PolicyRefresher.loadPolicyFromPolicyAdmin(serviceName=" + serviceName + ")");
}
try {
svcPolicies = rangerAdmin.getServicePoliciesIfUpdated(lastKnownVersion, lastActivationTimeInMillis);
boolean isUpdated = svcPolicies != null;
if(isUpdated) {
long newVersion = svcPolicies.getPolicyVersion() == null ? -1 : svcPolicies.getPolicyVersion().longValue();
if(!StringUtils.equals(serviceName, svcPolicies.getServiceName())) {
LOG.warn("PolicyRefresher(serviceName=" + serviceName + "): ignoring unexpected serviceName '" + svcPolicies.getServiceName() + "' in service-store");
svcPolicies.setServiceName(serviceName);
}
LOG.info("PolicyRefresher(serviceName=" + serviceName + "): found updated version. lastKnownVersion=" + lastKnownVersion + "; newVersion=" + newVersion);
} else {
if(LOG.isDebugEnabled()) {
LOG.debug("PolicyRefresher(serviceName=" + serviceName + ").run(): no update found. lastKnownVersion=" + lastKnownVersion);
}
}
} catch (RangerServiceNotFoundException snfe) {
LOG.error("PolicyRefresher(serviceName=" + serviceName + "): failed to find service. Will clean up local cache of policies (" + lastKnownVersion + ")", snfe);
throw snfe;
} catch (Exception excp) {
LOG.error("PolicyRefresher(serviceName=" + serviceName + "): failed to refresh policies. Will continue to use last known version of policies (" + lastKnownVersion + ")", excp);
svcPolicies = null;
}
RangerPerfTracer.log(perf);
if(LOG.isDebugEnabled()) {
LOG.debug("<== PolicyRefresher(serviceName=" + serviceName + ").loadPolicyfromPolicyAdmin()");
}
return svcPolicies;
}
private ServicePolicies loadFromCache() {
ServicePolicies policies = null;
if(LOG.isDebugEnabled()) {
LOG.debug("==> PolicyRefresher(serviceName=" + serviceName + ").loadFromCache()");
}
File cacheFile = cacheDir == null ? null : new File(cacheDir + File.separator + cacheFileName);
if(cacheFile != null && cacheFile.isFile() && cacheFile.canRead()) {
Reader reader = null;
RangerPerfTracer perf = null;
if(RangerPerfTracer.isPerfTraceEnabled(PERF_POLICYENGINE_INIT_LOG)) {
perf = RangerPerfTracer.getPerfTracer(PERF_POLICYENGINE_INIT_LOG, "PolicyRefresher.loadFromCache(serviceName=" + serviceName + ")");
}
try {
reader = new FileReader(cacheFile);
policies = gson.fromJson(reader, ServicePolicies.class);
if(policies != null) {
if(!StringUtils.equals(serviceName, policies.getServiceName())) {
LOG.warn("ignoring unexpected serviceName '" + policies.getServiceName() + "' in cache file '" + cacheFile.getAbsolutePath() + "'");
policies.setServiceName(serviceName);
}
lastKnownVersion = policies.getPolicyVersion() == null ? -1 : policies.getPolicyVersion().longValue();
}
} catch (Exception excp) {
LOG.error("failed to load policies from cache file " + cacheFile.getAbsolutePath(), excp);
} finally {
RangerPerfTracer.log(perf);
if(reader != null) {
try {
reader.close();
} catch(Exception excp) {
LOG.error("error while closing opened cache file " + cacheFile.getAbsolutePath(), excp);
}
}
}
} else {
LOG.warn("cache file does not exist or not readable '" + (cacheFile == null ? null : cacheFile.getAbsolutePath()) + "'");
}
if(LOG.isDebugEnabled()) {
LOG.debug("<== PolicyRefresher(serviceName=" + serviceName + ").loadFromCache()");
}
return policies;
}
private void saveToCache(ServicePolicies policies) {
if(LOG.isDebugEnabled()) {
LOG.debug("==> PolicyRefresher(serviceName=" + serviceName + ").saveToCache()");
}
if(policies != null) {
File cacheFile = null;
if (cacheDir != null) {
// Create the cacheDir if it doesn't already exist
File cacheDirTmp = new File(cacheDir);
if (cacheDirTmp.exists()) {
cacheFile = new File(cacheDir + File.separator + cacheFileName);
} else {
try {
cacheDirTmp.mkdirs();
cacheFile = new File(cacheDir + File.separator + cacheFileName);
} catch (SecurityException ex) {
LOG.error("Cannot create cache directory", ex);
}
}
}
if(cacheFile != null) {
RangerPerfTracer perf = null;
if(RangerPerfTracer.isPerfTraceEnabled(PERF_POLICYENGINE_INIT_LOG)) {
perf = RangerPerfTracer.getPerfTracer(PERF_POLICYENGINE_INIT_LOG, "PolicyRefresher.saveToCache(serviceName=" + serviceName + ")");
}
Writer writer = null;
try {
writer = new FileWriter(cacheFile);
gson.toJson(policies, writer);
} catch (Exception excp) {
LOG.error("failed to save policies to cache file '" + cacheFile.getAbsolutePath() + "'", excp);
} finally {
if(writer != null) {
try {
writer.close();
} catch(Exception excp) {
LOG.error("error while closing opened cache file '" + cacheFile.getAbsolutePath() + "'", excp);
}
}
}
RangerPerfTracer.log(perf);
}
} else {
LOG.info("policies is null. Nothing to save in cache");
}
if(LOG.isDebugEnabled()) {
LOG.debug("<== PolicyRefresher(serviceName=" + serviceName + ").saveToCache()");
}
}
private void disableCache() {
if (LOG.isDebugEnabled()) {
LOG.debug("==> PolicyRefresher.disableCache(serviceName=" + serviceName + ")");
}
File cacheFile = cacheDir == null ? null : new File(cacheDir + File.separator + cacheFileName);
if(cacheFile != null && cacheFile.isFile() && cacheFile.canRead()) {
LOG.warn("Cleaning up local cache");
String renamedCacheFile = cacheFile.getAbsolutePath() + "_" + System.currentTimeMillis();
if (!cacheFile.renameTo(new File(renamedCacheFile))) {
LOG.error("Failed to move " + cacheFile.getAbsolutePath() + " to " + renamedCacheFile);
} else {
LOG.warn("Moved " + cacheFile.getAbsolutePath() + " to " + renamedCacheFile);
}
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("No local policy cache found. No need to disable it!");
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("<== PolicyRefresher.disableCache(serviceName=" + serviceName + ")");
}
}
}