54663124026509e61a2e4d47262632b3fc9209c9
[ccsdk/cds.git] / ms / controllerblueprints / modules / blueprint-core / src / main / kotlin / org / onap / ccsdk / cds / controllerblueprints / core / scripts / BluePrintCompilerProxy.kt
1 /*
2  * Copyright © 2017-2018 AT&T Intellectual Property.
3  * Modifications Copyright © 2018 IBM.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 package org.onap.ccsdk.cds.controllerblueprints.core.scripts
19
20 import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
21 import org.jetbrains.kotlin.cli.common.config.addKotlinSourceRoots
22 import org.jetbrains.kotlin.cli.common.environment.setIdeaIoUseFallback
23 import org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport
24 import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
25 import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
26 import org.jetbrains.kotlin.cli.common.messages.MessageCollector
27 import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles
28 import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
29 import org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler
30 import org.jetbrains.kotlin.cli.jvm.config.JvmClasspathRoot
31 import org.jetbrains.kotlin.com.intellij.openapi.util.Disposer
32 import org.jetbrains.kotlin.config.*
33 import org.onap.ccsdk.cds.controllerblueprints.core.checkFileExists
34 import org.slf4j.LoggerFactory
35 import kotlin.script.experimental.api.*
36 import kotlin.script.experimental.host.ScriptingHostConfiguration
37 import kotlin.script.experimental.jvm.util.classpathFromClasspathProperty
38 import kotlin.script.experimental.jvmhost.KJvmCompilerProxy
39
40 open class BluePrintsCompilerProxy(private val hostConfiguration: ScriptingHostConfiguration) : KJvmCompilerProxy {
41
42     private val log = LoggerFactory.getLogger(BluePrintsCompilerProxy::class.java)!!
43
44     override fun compile(script: SourceCode, scriptCompilationConfiguration: ScriptCompilationConfiguration)
45             : ResultWithDiagnostics<CompiledScript<*>> {
46
47         val messageCollector = ScriptDiagnosticsMessageCollector()
48
49         fun failure(vararg diagnostics: ScriptDiagnostic): ResultWithDiagnostics.Failure =
50                 ResultWithDiagnostics.Failure(*messageCollector.diagnostics.toTypedArray(), *diagnostics)
51
52         // Compile the Code
53         try {
54
55             log.trace("Scripting Host Configuration : $hostConfiguration")
56
57             setIdeaIoUseFallback()
58
59             val blueprintSourceCode = script as BluePrintSourceCode
60
61             val compiledJarFile = blueprintSourceCode.targetJarFile
62
63             /** Check cache is present for the blueprint scripts */
64             val hasCompiledCache = BluePrintCompileCache.hasClassLoader(blueprintSourceCode.cacheKey)
65
66             log.debug("Jar Exists : ${compiledJarFile.exists()}, Regenerate : ${blueprintSourceCode.regenerate}," +
67                     " Compiled hash(${blueprintSourceCode.cacheKey}) : $hasCompiledCache")
68
69             if (!compiledJarFile.exists() || blueprintSourceCode.regenerate || !hasCompiledCache) {
70                 log.info("compiling for cache key(${blueprintSourceCode.cacheKey})")
71
72                 var environment: KotlinCoreEnvironment? = null
73
74                 val rootDisposable = Disposer.newDisposable()
75
76                 try {
77
78                     // Clean the cache, if present
79                     if (hasCompiledCache) {
80                         BluePrintCompileCache.cleanClassLoader(blueprintSourceCode.cacheKey)
81                     }
82
83                     val compilerConfiguration = CompilerConfiguration().apply {
84
85                         put(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY, messageCollector)
86                         put(CommonConfigurationKeys.MODULE_NAME, blueprintSourceCode.moduleName)
87                         put(JVMConfigurationKeys.OUTPUT_JAR, compiledJarFile)
88                         put(JVMConfigurationKeys.RETAIN_OUTPUT_IN_MEMORY, false)
89
90                         // Load Current Class loader to Compilation Class loader
91                         val currentClassLoader = classpathFromClasspathProperty()
92                         currentClassLoader?.forEach {
93                             add(CLIConfigurationKeys.CONTENT_ROOTS, JvmClasspathRoot(it))
94                         }
95
96                         // Add all Kotlin Sources
97                         addKotlinSourceRoots(blueprintSourceCode.blueprintKotlinSources)
98                         // for Kotlin 1.3.30 greater
99                         //add(ComponentRegistrar.PLUGIN_COMPONENT_REGISTRARS, ScriptingCompilerConfigurationComponentRegistrar())
100
101                         languageVersionSettings = LanguageVersionSettingsImpl(
102                                 LanguageVersion.LATEST_STABLE, ApiVersion.LATEST_STABLE, mapOf(AnalysisFlags.skipMetadataVersionCheck to true)
103                         )
104                     }
105
106                     //log.info("Executing with compiler configuration : $compilerConfiguration")
107
108                     environment = KotlinCoreEnvironment.createForProduction(rootDisposable, compilerConfiguration,
109                             EnvironmentConfigFiles.JVM_CONFIG_FILES)
110
111                     // Compile Kotlin Sources
112                     val compiled = KotlinToJVMBytecodeCompiler.compileBunchOfSources(environment)
113
114                     val analyzerWithCompilerReport = AnalyzerWithCompilerReport(messageCollector,
115                             environment.configuration.languageVersionSettings)
116
117                     if (analyzerWithCompilerReport.hasErrors()) {
118                         return ResultWithDiagnostics.Failure(messageCollector.diagnostics)
119                     }
120                 } finally {
121                     rootDisposable.dispose()
122                 }
123             }
124
125             checkFileExists(compiledJarFile) { "couldn't generate compiled jar(${compiledJarFile.absolutePath})" }
126
127             val compiledScript = BluePrintCompiledScript<String>(blueprintSourceCode.cacheKey, scriptCompilationConfiguration)
128
129             return compiledScript.asSuccess()
130
131         } catch (ex: Throwable) {
132             return failure(ex.asDiagnostics())
133         }
134     }
135 }
136
137 class ScriptDiagnosticsMessageCollector : MessageCollector {
138
139     private val _diagnostics = arrayListOf<ScriptDiagnostic>()
140
141     val diagnostics: List<ScriptDiagnostic> get() = _diagnostics
142
143     override fun clear() {
144         _diagnostics.clear()
145     }
146
147     override fun hasErrors(): Boolean =
148             _diagnostics.any { it.severity == ScriptDiagnostic.Severity.ERROR }
149
150
151     override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) {
152         val mappedSeverity = when (severity) {
153             CompilerMessageSeverity.EXCEPTION,
154             CompilerMessageSeverity.ERROR -> ScriptDiagnostic.Severity.ERROR
155             CompilerMessageSeverity.STRONG_WARNING,
156             CompilerMessageSeverity.WARNING -> ScriptDiagnostic.Severity.WARNING
157             CompilerMessageSeverity.INFO -> ScriptDiagnostic.Severity.INFO
158             CompilerMessageSeverity.LOGGING -> ScriptDiagnostic.Severity.DEBUG
159             else -> null
160         }
161         if (mappedSeverity != null) {
162             val mappedLocation = location?.let {
163                 if (it.line < 0 && it.column < 0) null // special location created by CompilerMessageLocation.create
164                 else SourceCode.Location(SourceCode.Position(it.line, it.column))
165             }
166             _diagnostics.add(ScriptDiagnostic(message, mappedSeverity, location?.path, mappedLocation))
167         }
168     }
169 }
170