cb6616f38205d8d18a6bf4aa66c4c842639fad15
[ccsdk/cds.git] /
1 /*
2  *  Copyright © 2019 IBM.
3  *
4  *  Licensed under the Apache License, Version 2.0 (the "License");
5  *  you may not use this file except in compliance with the License.
6  *  You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License.
15  */
16
17 package org.onap.ccsdk.cds.controllerblueprints.core.scripts
18
19 import com.google.common.cache.CacheBuilder
20 import com.google.common.cache.CacheLoader
21 import com.google.common.cache.LoadingCache
22 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
23 import org.onap.ccsdk.cds.controllerblueprints.core.logger
24 import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils
25 import java.net.URLClassLoader
26
27 object BluePrintCompileCache {
28     val log = logger(BluePrintCompileCache::class)
29
30     private val classLoaderCache: LoadingCache<String, URLClassLoader> = CacheBuilder.newBuilder()
31         .maximumSize(50)
32         .build(BluePrintClassLoader)
33
34     fun classLoader(key: String): URLClassLoader {
35         return classLoaderCache.get(key)
36     }
37
38     fun cleanClassLoader(key: String) {
39         if (hasClassLoader(key)) {
40             // Make sure to close all classloader loaded resources before we let go of it.
41             // This fixes a Delete failure message on filesystem that keeps locks on opened jars;
42             // like Windows and NFS.
43             classLoaderCache.get(key).close()
44             classLoaderCache.invalidate(key)
45             log.info("Cleaned compiled cache($key)")
46         } else {
47             log.warn("No compiled cache($key) present to clean.")
48         }
49     }
50
51     fun hasClassLoader(key: String): Boolean {
52         return classLoaderCache.asMap().containsKey(key)
53     }
54 }
55
56 object BluePrintClassLoader : CacheLoader<String, URLClassLoader>() {
57
58     val log = logger(BluePrintClassLoader::class)
59
60     override fun load(key: String) = try {
61         log.info("loading compiled cache($key)")
62         BluePrintFileUtils.getURLClassLoaderFromDirectory(key)
63     } catch (e: Exception) {
64         throw BluePrintException("failed to load cache($key) with Exception($e)")
65     }
66 }