e231f6d1c43970149738a227366de471a6a33bf2
[ccsdk/cds.git] /
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             if (!compiledJarFile.exists() || blueprintSourceCode.regenerate || !hasCompiledCache) {
67                 log.info("compiling for cache key(${blueprintSourceCode.cacheKey})")
68
69                 var environment: KotlinCoreEnvironment? = null
70
71                 val rootDisposable = Disposer.newDisposable()
72
73                 try {
74
75                     // Clean the cache, if present
76                     if (hasCompiledCache) {
77                         BluePrintCompileCache.cleanClassLoader(blueprintSourceCode.cacheKey)
78                     }
79
80                     val compilerConfiguration = CompilerConfiguration().apply {
81
82                         put(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY, messageCollector)
83                         put(CommonConfigurationKeys.MODULE_NAME, blueprintSourceCode.moduleName)
84                         put(JVMConfigurationKeys.OUTPUT_JAR, compiledJarFile)
85                         put(JVMConfigurationKeys.RETAIN_OUTPUT_IN_MEMORY, false)
86
87                         // Load Current Class loader to Compilation Class loader
88                         val currentClassLoader = classpathFromClasspathProperty()
89                         currentClassLoader?.forEach {
90                             add(CLIConfigurationKeys.CONTENT_ROOTS, JvmClasspathRoot(it))
91                         }
92
93                         // Add all Kotlin Sources
94                         addKotlinSourceRoots(blueprintSourceCode.blueprintKotlinSources)
95                         // for Kotlin 1.3.30 greater
96                         //add(ComponentRegistrar.PLUGIN_COMPONENT_REGISTRARS, ScriptingCompilerConfigurationComponentRegistrar())
97
98                         languageVersionSettings = LanguageVersionSettingsImpl(
99                                 LanguageVersion.LATEST_STABLE, ApiVersion.LATEST_STABLE, mapOf(AnalysisFlags.skipMetadataVersionCheck to true)
100                         )
101                     }
102
103                     //log.info("Executing with compiler configuration : $compilerConfiguration")
104
105                     environment = KotlinCoreEnvironment.createForProduction(rootDisposable, compilerConfiguration,
106                             EnvironmentConfigFiles.JVM_CONFIG_FILES)
107
108                     // Compile Kotlin Sources
109                     val compiled = KotlinToJVMBytecodeCompiler.compileBunchOfSources(environment)
110
111                     val analyzerWithCompilerReport = AnalyzerWithCompilerReport(messageCollector,
112                             environment.configuration.languageVersionSettings)
113
114                     if (analyzerWithCompilerReport.hasErrors()) {
115                         return ResultWithDiagnostics.Failure(messageCollector.diagnostics)
116                     }
117                 } finally {
118                     rootDisposable.dispose()
119                 }
120             }
121
122             checkFileExists(compiledJarFile) { "couldn't generate compiled jar(${compiledJarFile.absolutePath})" }
123
124             val compiledScript = BluePrintCompiledScript<String>(blueprintSourceCode.cacheKey, scriptCompilationConfiguration)
125
126             return compiledScript.asSuccess()
127
128         } catch (ex: Throwable) {
129             return failure(ex.asDiagnostics())
130         }
131     }
132 }
133
134 class ScriptDiagnosticsMessageCollector : MessageCollector {
135
136     private val _diagnostics = arrayListOf<ScriptDiagnostic>()
137
138     val diagnostics: List<ScriptDiagnostic> get() = _diagnostics
139
140     override fun clear() {
141         _diagnostics.clear()
142     }
143
144     override fun hasErrors(): Boolean =
145             _diagnostics.any { it.severity == ScriptDiagnostic.Severity.ERROR }
146
147
148     override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) {
149         val mappedSeverity = when (severity) {
150             CompilerMessageSeverity.EXCEPTION,
151             CompilerMessageSeverity.ERROR -> ScriptDiagnostic.Severity.ERROR
152             CompilerMessageSeverity.STRONG_WARNING,
153             CompilerMessageSeverity.WARNING -> ScriptDiagnostic.Severity.WARNING
154             CompilerMessageSeverity.INFO -> ScriptDiagnostic.Severity.INFO
155             CompilerMessageSeverity.LOGGING -> ScriptDiagnostic.Severity.DEBUG
156             else -> null
157         }
158         if (mappedSeverity != null) {
159             val mappedLocation = location?.let {
160                 if (it.line < 0 && it.column < 0) null // special location created by CompilerMessageLocation.create
161                 else SourceCode.Location(SourceCode.Position(it.line, it.column))
162             }
163             _diagnostics.add(ScriptDiagnostic(message, mappedSeverity, location?.path, mappedLocation))
164         }
165     }
166 }
167