Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use gradle variables in kernel source #37

Merged
merged 4 commits into from
Dec 26, 2019
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 83 additions & 48 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import com.beust.klaxon.JsonObject
import groovy.json.JsonOutput

import java.nio.file.Path
import java.nio.file.Paths
import java.util.regex.Pattern
import java.util.stream.Collectors

buildscript {
ext.shadowJarVersion = "5.2.0"
ext.kotlinVersion = '1.3.70-eap-3'
ext.baseVersion = '0.7.40'
ext.baseVersion = '0.7.41'
repositories {
jcenter()
mavenLocal()
Expand All @@ -18,7 +20,6 @@ buildscript {
//noinspection DifferentKotlinGradleVersion
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
classpath "com.github.jengelman.gradle.plugins:shadow:$shadowJarVersion"
classpath "com.beust:klaxon:5.2"
}
}

Expand All @@ -42,45 +43,61 @@ allprojects {
testCompile "org.jetbrains.kotlin:kotlin-test:$kotlinVersion"
}

String artifactsPathStr = rootProject.findProperty('artifactsPath') ?: 'artifacts'
String buildCounterStr = rootProject.findProperty('build.counter') ?: '100500'
String buildNumber = rootProject.findProperty('build.number') ?: ''
String installPath = rootProject.findProperty('installPath')

ext.rootPath = rootDir.toPath()
ext.packageName = 'kotlin-jupyter-kernel'
ext.artifactsDir = rootPath.resolve(artifactsPathStr)
ext.isProtectedBranch = isProtectedBranch()
ext.versionFileName = "VERSION"

ext.installPathLocal = installPath ? Paths.get(installPath) :
Paths.get(System.properties['user.home'].toString(), ".ipython", "kernels", "kotlin")
ext.distributionPath = rootPath.resolve("distrib")
ext.distribBuildPath = rootPath.resolve("distrib-build")
ext.logosPath = getSubDir(rootPath, "resources", "logos")

String devAddition = isProtectedBranch ? '' : '.dev1'
String defaultBuildNumber = "$baseVersion.$buildCounterStr$devAddition"
String buildNumberRegex = "[0-9]+(\\.[0-9]+){3}(\\.dev[0-9]+)?"

if (!Pattern.matches(buildNumberRegex, buildNumber)) {
def versionFile = artifactsDir.resolve(versionFileName).toFile()
if (versionFile.exists()) {
def lines = versionFile.readLines()
assert !lines.empty, "There should be at least one line in VERSION file"
buildNumber = lines.first().trim()
ext {
packageName = "kotlin-jupyter-kernel"
versionFileName = "VERSION"

String artifactsPathStr = rootProject.findProperty('artifactsPath') ?: 'artifacts'
String installPath = rootProject.findProperty('installPath')

//noinspection GroovyAssignabilityCheck
rootPath = rootDir.toPath()
//noinspection GroovyAssignabilityCheck
artifactsDir = rootPath.resolve(artifactsPathStr)

//noinspection GroovyAssignabilityCheck
installPathLocal = installPath ? Paths.get(installPath) :
Paths.get(System.properties['user.home'].toString(), ".ipython", "kernels", "kotlin")
//noinspection GroovyAssignabilityCheck
distributionPath = rootPath.resolve("distrib")
//noinspection GroovyAssignabilityCheck
distribBuildPath = rootPath.resolve("distrib-build")
//noinspection GroovyAssignabilityCheck
logosPath = getSubDir(rootPath, "resources", "logos")

if (project == rootProject) {
isProtectedBranch = isProtectedBranch()
String buildCounterStr = rootProject.findProperty('build.counter') ?: '100500'
String buildNumber = rootProject.findProperty('build.number') ?: ''
String devAddition = isProtectedBranch ? '' : '.dev1'
String defaultBuildNumber = "$baseVersion.$buildCounterStr$devAddition"
String buildNumberRegex = "[0-9]+(\\.[0-9]+){3}(\\.dev[0-9]+)?"

if (!Pattern.matches(buildNumberRegex, buildNumber)) {
def versionFile = artifactsDir.resolve(versionFileName).toFile()
if (versionFile.exists()) {
def lines = versionFile.readLines()
assert !lines.empty, "There should be at least one line in VERSION file"
buildNumber = lines.first().trim()
} else {
buildNumber = defaultBuildNumber
}
}

project.version = buildNumber
println("##teamcity[buildNumber '$version']")
} else {
buildNumber = defaultBuildNumber
isProtectedBranch = rootProject.isProtectedBranch
project.version = rootProject.version
}
}

project.version = buildNumber
println("##teamcity[buildNumber '$version']")

ext {
debugPort = 1044
debuggerConfig = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=$debugPort".toString()

mainSourceSetDir = "main"
resourcesDir = "resources"
runtimePropertiesFile = "runtime.properties"

jarsPath = "jars"
librariesPath = "libraries"
kernelFile = "kernel.json"
Expand Down Expand Up @@ -112,6 +129,7 @@ allprojects {
distribGroup = "distrib"
condaGroup = "conda"
pyPiGroup = "pip"
buildGroup = "build"

condaUserStable = rootProject.findProperty('condaUserStable') ?: ''
condaPasswordStable = rootProject.findProperty('condaPasswordStable') ?: ''
Expand Down Expand Up @@ -161,6 +179,25 @@ jar.manifest.attributes(
'Implementation-Version': version
)

task buildProperties(group: buildGroup) {
def outputDir = file(getSubDir(buildDir.toPath(), resourcesDir, mainSourceSetDir))

inputs.property "version", version
outputs.dir outputDir

doLast {
outputDir.mkdirs()
def propertiesFile = file(getSubDir(outputDir.toPath(), runtimePropertiesFile))
propertiesFile.text = inputs.properties.entrySet().stream().map {
"${it.key}=${it.value}\n"
}.collect(Collectors.joining())
}
}

processResources {
dependsOn buildProperties
}

shadowJar {
archiveBaseName.set(packageName)
archiveClassifier.set('')
Expand All @@ -182,24 +219,24 @@ static String makeTaskName(String prefix, Boolean local) {
return prefix + (local ? "Local" : "Distrib")
}

static void makeDirs(java.nio.file.Path path) {
static void makeDirs(Path path) {
File dir = path.toFile()
if (!dir.exists()) {
dir.mkdirs()
}
}

static java.nio.file.Path getSubDir(java.nio.file.Path dir, String... subDir) {
static Path getSubDir(Path dir, String... subDir) {
def newDir = dir
for (s in subDir) {
newDir = newDir.resolve(s)
}
return newDir
}

static void writeJson(Map<String, Object> json, java.nio.file.Path path) {
def jsonString = new JsonObject(json).toJsonString(true, false)
path.toFile().write(jsonString, 'UTF-8')
static void writeJson(Map<String, Object> json, Path path) {
def str = JsonOutput.prettyPrint(JsonOutput.toJson(json))
path.toFile().write(str, 'UTF-8')
}

void createCleanTasks() {
Expand All @@ -216,7 +253,7 @@ void createCleanTasks() {
createCleanTasks()

@SuppressWarnings("unused")
void createInstallTasks(Boolean local, java.nio.file.Path specPath, java.nio.file.Path mainInstallPath) {
void createInstallTasks(Boolean local, Path specPath, Path mainInstallPath) {
def groupName = local ? localGroup : distribGroup
def cleanDirTask = getTasks().getByName(makeTaskName(cleanInstallDirTaskPrefix, local))
def args = [type: Copy, dependsOn: cleanDirTask, group: groupName]
Expand All @@ -242,7 +279,7 @@ void createInstallTasks(Boolean local, java.nio.file.Path specPath, java.nio.fil
}
}

String createTaskForSpecs(Boolean debug, Boolean local, String group, Task cleanDir, java.nio.file.Path specPath, java.nio.file.Path mainInstallPath) {
String createTaskForSpecs(Boolean debug, Boolean local, String group, Task cleanDir, Path specPath, Path mainInstallPath) {
String taskName = makeTaskName(debug ? "createDebugSpecs" : "createSpecs", local)
task([group: group], taskName) {
dependsOn cleanDir, shadowJar
Expand Down Expand Up @@ -283,7 +320,7 @@ void createMainInstallTask(Boolean debug, Boolean local, String group, String sp
}
}

void makeKernelSpec(java.nio.file.Path installPath, Boolean localInstall) {
void makeKernelSpec(Path installPath, Boolean localInstall) {
def argv = localInstall ?
Arrays.asList("python",
installPath.resolve(runKernelPy).toString(),
Expand All @@ -304,7 +341,7 @@ void makeKernelSpec(java.nio.file.Path installPath, Boolean localInstall) {
}
}

void makeJarArgs(java.nio.file.Path installPath, String kernelJarPath, List<String> classPath, String debuggerConfig = "") {
void makeJarArgs(Path installPath, String kernelJarPath, List<String> classPath, String debuggerConfig = "") {
writeJson([
"mainJar": kernelJarPath,
"classPath": classPath,
Expand All @@ -321,8 +358,6 @@ task copyRunKernelPy(type: Copy, dependsOn: cleanInstallDirLocal, group: localGr

createInstallTasks(true, installPathLocal, installPathLocal)

task uninstall(dependsOn: cleanInstallDirLocal, group: localGroup) {

}
task uninstall(dependsOn: cleanInstallDirLocal, group: localGroup)

apply from: 'distrib.gradle'
13 changes: 12 additions & 1 deletion src/main/kotlin/org/jetbrains/kotlin/jupyter/config.kt
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,25 @@ enum class JupyterSockets {
iopub
}

data class RuntimeKernelProperties(
var version: String = "unspecified"
) {
constructor(map: Map<String, String>?) : this() {
if (map == null)
return
version = map["version"] ?: version
}
}

data class KernelConfig(
val ports: Array<Int>,
val transport: String,
val signatureScheme: String,
val signatureKey: String,
val pollingIntervalMillis: Long = 100,
val scriptClasspath: List<File> = emptyList(),
val resolverConfig: ResolverConfig?
val resolverConfig: ResolverConfig?,
val runtimeProperties: RuntimeKernelProperties = RuntimeKernelProperties()
)

val protocolVersion = "5.3"
Expand Down
13 changes: 11 additions & 2 deletions src/main/kotlin/org/jetbrains/kotlin/jupyter/ikotlin.kt
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@ fun printClassPath() {
log.info("Current classpath: " + cp.joinToString())
}

fun loadRuntimeProperties(): RuntimeKernelProperties {
val map = object{}.javaClass.classLoader
.getResource("runtime.properties")
?.readText()?.parseIniConfig()

return RuntimeKernelProperties(map)
}

fun main(vararg args: String) {
try {
log.info("Kernel args: "+ args.joinToString { it })
Expand All @@ -62,7 +70,8 @@ fun main(vararg args: String) {
signatureScheme = sigScheme ?: "hmac1-sha256",
signatureKey = if (sigScheme == null || key == null) "" else key,
scriptClasspath = scriptClasspath,
resolverConfig = loadResolverConfig(rootPath)
resolverConfig = loadResolverConfig(rootPath),
runtimeProperties = loadRuntimeProperties()
))
} catch (e: Exception) {
log.error("exception running kernel with args: \"${args.joinToString()}\"", e)
Expand All @@ -80,7 +89,7 @@ fun kernelServer(config: KernelConfig) {

val executionCount = AtomicLong(1)

val repl = ReplForJupyter(config.scriptClasspath, config.resolverConfig)
val repl = ReplForJupyter(config.scriptClasspath, config.resolverConfig, config.runtimeProperties)

val mainThread = Thread.currentThread()

Expand Down
8 changes: 6 additions & 2 deletions src/main/kotlin/org/jetbrains/kotlin/jupyter/protocol.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ data class ResponseWithMessage(val state: ResponseState, val result: MimeTypedRe

fun JupyterConnection.Socket.shellMessagesHandler(msg: Message, repl: ReplForJupyter?, executionCount: AtomicLong) {
val msgType = msg.header!!["msg_type"]
val replProperties = repl?.properties ?: RuntimeKernelProperties()
when (msgType) {
"kernel_info_request" ->
sendWrapped(msg, makeReplyMessage(msg, "kernel_info_reply",
Expand All @@ -32,13 +33,16 @@ fun JupyterConnection.Socket.shellMessagesHandler(msg: Message, repl: ReplForJup
"language_info" to jsonObject(
"name" to "kotlin",
"codemirror_mode" to "text/x-kotlin",
"file_extension" to ".kt"
"file_extension" to ".kt",
"mimetype" to "text/x-kotlin",
"pygments_lexer" to "kotlin",
"version" to KotlinCompilerVersion.VERSION
),

// Jupyter lab Console support
"banner" to "Kotlin language, version ${KotlinCompilerVersion.VERSION}",
"implementation" to "Kotlin",
"implementation_version" to KotlinCompilerVersion.VERSION,
"implementation_version" to replProperties.version,
"status" to "ok"
)))
"history_request" ->
Expand Down
3 changes: 2 additions & 1 deletion src/main/kotlin/org/jetbrains/kotlin/jupyter/repl.kt
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ class ReplCompilerException(val errorResult: ReplCompileResult.Error) : ReplExce
}

class ReplForJupyter(val scriptClasspath: List<File> = emptyList(),
val config: ResolverConfig? = null) {
val config: ResolverConfig? = null,
val properties: RuntimeKernelProperties = RuntimeKernelProperties()) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does ReplForJupyter need RuntimeKernelProperties? They are not used within it


private val resolver = JupyterScriptDependenciesResolver(config)

Expand Down