diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index a8c54f0e534..38697dbebfd 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -156,7 +156,7 @@ jobs: go build - run: | cd tests/go-e2e-fileops - go build + go build - name: start minikube uses: medyagh/setup-minikube@master with: @@ -218,3 +218,18 @@ jobs: - name: Collect container logs if: ${{ failure() }} run: for CONTAINER in $(docker ps --format "{{.ID}}"); do echo $CONTAINER && docker logs $CONTAINER; done + + build_intellij_plugin: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Setup Java + uses: actions/setup-java@v3 + with: + distribution: zulu + java-version: 11 + - name: Build Plugin + run: | + cd intellij-ext + chmod +x ./gradlew + ./gradlew buildPlugin diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 565e9e01ad1..fe9e4603b65 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -104,7 +104,7 @@ jobs: ghcr.io/metalbear-co/mirrord:${{ steps.version.outputs.version }} release_vscode_ext: - needs: [build_binaries, build_binaries_macos, release_docker_image] + needs: [ build_binaries, build_binaries_macos, release_docker_image ] runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 @@ -124,12 +124,12 @@ jobs: id: version - run: npm install -g vsce typescript esbuild - run: cp CHANGELOG.md LICENSE vscode-ext/ - - run: mv /tmp/artifacts/x86_64-unknown-linux-gnu/libmirrord_layer.so vscode-ext/ + - run: cp /tmp/artifacts/x86_64-unknown-linux-gnu/libmirrord_layer.so vscode-ext/ - run: cd vscode-ext && npm install && tsc && vsce publish ${{ steps.version.outputs.version }} --target linux-x64 env: VSCE_PAT: ${{ secrets.VSCE_PAT }} - run: rm vscode-ext/libmirrord_layer.so - - run: mv /tmp/artifacts/universal-apple-darwin/libmirrord_layer.dylib vscode-ext/ + - run: cp /tmp/artifacts/universal-apple-darwin/libmirrord_layer.dylib vscode-ext/ # Same binary for darwin - run: cd vscode-ext && npm install && tsc && vsce publish ${{ steps.version.outputs.version }} --target darwin-x64 env: @@ -138,8 +138,36 @@ jobs: env: VSCE_PAT: ${{ secrets.VSCE_PAT }} + + release_intellij_plugin: + needs: [ build_binaries, build_binaries_macos, release_docker_image ] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/download-artifact@v3 + with: + path: /tmp/artifacts + - name: Setup Java + uses: actions/setup-java@v3 + with: + distribution: zulu + java-version: 11 + - run: cp LICENSE intellij-ext/ + - run: cp /tmp/artifacts/x86_64-unknown-linux-gnu/libmirrord_layer.* intellij-ext/ + - name: Publish Plugin + env: + PUBLISH_TOKEN: ${{ secrets.PUBLISH_TOKEN }} + CERTIFICATE_CHAIN: ${{ secrets.CERTIFICATE_CHAIN }} + PRIVATE_KEY: ${{ secrets.PRIVATE_KEY }} + PRIVATE_KEY_PASSWORD: ${{ secrets.PRIVATE_KEY_PASSWORD }} + run: | + cd intellij-ext + chmod +x ./gradlew + ./gradlew publishPlugin + + release_gh: - needs: [build_binaries, build_binaries_macos, release_docker_image, release_vscode_ext] + needs: [ build_binaries, build_binaries_macos, release_docker_image, release_vscode_ext ] runs-on: ubuntu-latest permissions: packages: write diff --git a/.gitignore b/.gitignore index ae400e33e53..d46b5920eb2 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,10 @@ tests/go-e2e-fileops/go-e2e-fileops !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json + +### Intellij ### +intellij-ext/.gradle +intellij-ext/.idea +intellij-ext/.qodana +intellij-ext/build +intellij-ext/libmirrord_layer.* \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 688d9098225..b3bf31e4fee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how ### Added - Support for Golang fileops +- IntelliJ Extension for mirrord ### Changed - mirrord-layer: Added common `Result` type to to reduce boilerplate, removed dependency of `anyhow` crate. diff --git a/intellij-ext/README.md b/intellij-ext/README.md new file mode 100644 index 00000000000..7eaab5bd632 --- /dev/null +++ b/intellij-ext/README.md @@ -0,0 +1,30 @@ +# mirrord + + +mirrord works by letting you select a pod to mirror traffic from. It launches a privileged pod on the same node which enters the namespace of the selected pod and captures traffic from it. +### How To Use + +* Click "Enable/Disable mirrord" toggle button on the run tool window. +* Start debugging your project +* Choose pod to mirror traffic from, select and configure mirrord options. +* The debugged process will start with mirrord, and receive traffic. + + + +## Installation + +- Using IDE built-in plugin system: + + Settings/Preferences > Plugins > Marketplace > Search for "mirrord-intellij-plugin" > + Install Plugin + +- Manually: + + Download the latest release and install it manually using + Settings/Preferences > Plugins > ⚙️ > Install plugin from disk... + + +--- +Plugin based on the [IntelliJ Platform Plugin Template][template]. + +[template]: https://github.com/JetBrains/intellij-platform-plugin-template diff --git a/intellij-ext/build.gradle.kts b/intellij-ext/build.gradle.kts new file mode 100644 index 00000000000..67a098e2203 --- /dev/null +++ b/intellij-ext/build.gradle.kts @@ -0,0 +1,120 @@ +import org.jetbrains.changelog.markdownToHTML +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +fun properties(key: String) = project.findProperty(key).toString() + +plugins { + // Java support + id("java") + // Kotlin support + id("org.jetbrains.kotlin.jvm") version "1.6.10" + // Gradle IntelliJ Plugin + id("org.jetbrains.intellij") version "1.8.1" + // Gradle Changelog Plugin + id("org.jetbrains.changelog") version "1.3.1" + // Gradle Qodana Plugin + id("org.jetbrains.qodana") version "0.1.13" +} + +group = properties("pluginGroup") +version = properties("pluginVersion") + +// Configure project's dependencies +repositories { + mavenCentral() +} +dependencies { + implementation("io.kubernetes:client-java:16.0.0") { + exclude(group="org.slf4j", module = "slf4j-api") + } +} + +// Configure Gradle IntelliJ Plugin - read more: https://github.com/JetBrains/gradle-intellij-plugin +intellij { + pluginName.set(properties("pluginName")) + version.set(properties("platformVersion")) + type.set(properties("platformType")) + // Plugin Dependencies. Uses `platformPlugins` property from the gradle.properties file. + plugins.set(properties("platformPlugins").split(',').map(String::trim).filter(String::isNotEmpty)) +} + +// Configure Gradle Qodana Plugin - read more: https://github.com/JetBrains/gradle-qodana-plugin +qodana { + cachePath.set(projectDir.resolve(".qodana").canonicalPath) + reportPath.set(projectDir.resolve("build/reports/inspections").canonicalPath) + saveReport.set(true) + showReport.set(System.getenv("QODANA_SHOW_REPORT")?.toBoolean() ?: false) +} + +tasks { + // Set the JVM compatibility versions + properties("javaVersion").let { + withType { + sourceCompatibility = it + targetCompatibility = it + } + withType { + kotlinOptions.jvmTarget = it + } + } + + wrapper { + gradleVersion = properties("gradleVersion") + } + + patchPluginXml { + version.set(properties("pluginVersion")) + sinceBuild.set(properties("pluginSinceBuild")) + untilBuild.set(properties("pluginUntilBuild")) + + // Extract the section from README.md and provide for the plugin's manifest + pluginDescription.set( + projectDir.resolve("README.md").readText().lines().run { + val start = "" + val end = "" + + if (!containsAll(listOf(start, end))) { + throw GradleException("Plugin description section not found in README.md:\n$start ... $end") + } + subList(indexOf(start) + 1, indexOf(end)) + }.joinToString("\n").run { markdownToHTML(this) } + ) + } + + prepareSandbox { + doLast { + copy { + from(file("$projectDir/libmirrord_layer.dylib")) + into(file("$buildDir/idea-sandbox/config")) + } + copy { + from(file("$projectDir/libmirrord_layer.so")) + into(file("$buildDir/idea-sandbox/config")) + } + } + } + + // Configure UI tests plugin + // Read more: https://github.com/JetBrains/intellij-ui-test-robot + runIdeForUiTests { + systemProperty("robot-server.port", "8082") + systemProperty("ide.mac.message.dialogs.as.sheets", "false") + systemProperty("jb.privacy.policy.text", "") + systemProperty("jb.consents.confirmation.enabled", "false") + } + + signPlugin { + certificateChain.set(System.getenv("CERTIFICATE_CHAIN")) + privateKey.set(System.getenv("PRIVATE_KEY")) + password.set(System.getenv("PRIVATE_KEY_PASSWORD")) + } + + publishPlugin { + token.set(System.getenv("PUBLISH_TOKEN")) + // pluginVersion is based on the SemVer (https://semver.org) and supports pre-release labels, like 2.1.7-alpha.3 + // Specify pre-release label to publish the plugin in a custom Release Channel automatically. Read more: + // https://plugins.jetbrains.com/docs/intellij/deployment.html#specifying-a-release-channel + channels.set(listOf("beta")) + channels.set(listOf(properties("pluginVersion").split('-').getOrElse(1) { "default" }.split('.').first())) + } +} diff --git a/intellij-ext/gradle.properties b/intellij-ext/gradle.properties new file mode 100644 index 00000000000..411044af9b6 --- /dev/null +++ b/intellij-ext/gradle.properties @@ -0,0 +1,30 @@ +# IntelliJ Platform Artifacts Repositories +# -> https://plugins.jetbrains.com/docs/intellij/intellij-artifacts.html + +pluginGroup = com.metalbear.mirrord +pluginName = mirrord +# SemVer format -> https://semver.org +pluginVersion = 2.7.4 + +# See https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html +# for insight into build numbers and IntelliJ Platform versions. +pluginSinceBuild = 213 +pluginUntilBuild = 222.* + +platformType = IC +platformVersion = 2021.3.3 + +# Plugin Dependencies -> https://plugins.jetbrains.com/docs/intellij/plugin-dependencies.html +# Example: platformPlugins = com.intellij.java, com.jetbrains.php:203.4449.22 +platformPlugins = + +# Java language level used to compile sources and to generate the files for - Java 11 is required since 2020.3 +javaVersion = 11 + +# Gradle Releases -> https://github.com/gradle/gradle/releases +gradleVersion = 7.5.1 + +# Opt-out flag for bundling Kotlin standard library. +# See https://plugins.jetbrains.com/docs/intellij/kotlin.html#kotlin-standard-library for details. +# suppress inspection "UnusedProperty" +kotlin.stdlib.default.dependency = false diff --git a/intellij-ext/gradle/wrapper/gradle-wrapper.jar b/intellij-ext/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..41d9927a4d4 Binary files /dev/null and b/intellij-ext/gradle/wrapper/gradle-wrapper.jar differ diff --git a/intellij-ext/gradle/wrapper/gradle-wrapper.properties b/intellij-ext/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..41dfb87909a --- /dev/null +++ b/intellij-ext/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/intellij-ext/gradlew b/intellij-ext/gradlew new file mode 100644 index 00000000000..1b6c787337f --- /dev/null +++ b/intellij-ext/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed 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 +# +# https://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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/intellij-ext/gradlew.bat b/intellij-ext/gradlew.bat new file mode 100644 index 00000000000..107acd32c4e --- /dev/null +++ b/intellij-ext/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/intellij-ext/qodana.yml b/intellij-ext/qodana.yml new file mode 100644 index 00000000000..dac95d3195b --- /dev/null +++ b/intellij-ext/qodana.yml @@ -0,0 +1,6 @@ +# Qodana configuration: +# https://www.jetbrains.com/help/qodana/qodana-yaml.html + +version: 1.0 +profile: + name: qodana.recommended diff --git a/intellij-ext/settings.gradle.kts b/intellij-ext/settings.gradle.kts new file mode 100644 index 00000000000..22b89c230a8 --- /dev/null +++ b/intellij-ext/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "mirrord" diff --git a/intellij-ext/src/main/kotlin/com/metalbear/mirrord/KubeDataProvider.kt b/intellij-ext/src/main/kotlin/com/metalbear/mirrord/KubeDataProvider.kt new file mode 100644 index 00000000000..5e3e67cd729 --- /dev/null +++ b/intellij-ext/src/main/kotlin/com/metalbear/mirrord/KubeDataProvider.kt @@ -0,0 +1,15 @@ +package com.metalbear.mirrord +import io.kubernetes.client.openapi.apis.CoreV1Api +import io.kubernetes.client.util.Config + +class KubeDataProvider : CoreV1Api(Config.defaultClient()) { + fun getNameSpacedPods(namespace: String): List { + val pods = listNamespacedPod(namespace, null, null, null, null, null, null, null, null, null, null) + return pods.items.map{ it.metadata!!.name!! } + } + + fun getNamespaces() : List { + val namespaces = listNamespace(null, null, null, null, null, null, null, null, null, null) + return namespaces.items.map{ it.metadata!!.name!! } + } +} \ No newline at end of file diff --git a/intellij-ext/src/main/kotlin/com/metalbear/mirrord/MirrordDefaultData.kt b/intellij-ext/src/main/kotlin/com/metalbear/mirrord/MirrordDefaultData.kt new file mode 100644 index 00000000000..8fe8bbc3843 --- /dev/null +++ b/intellij-ext/src/main/kotlin/com/metalbear/mirrord/MirrordDefaultData.kt @@ -0,0 +1,12 @@ +package com.metalbear.mirrord + +import com.intellij.openapi.application.PathManager +import java.nio.file.Paths + +data class MirrordDefaultData(val ldPreloadPath: String, val dylibPath: String, val agentLog: String, val rustLog: String, val acceptInvalidCertificates: Boolean, val ephemeralContainers: Boolean) { + constructor() : this(getSharedLibPath("libmirrord_layer.so"), getSharedLibPath("libmirrord_layer.dylib"), "DEBUG", "DEBUG", true, false) +} + +private fun getSharedLibPath(libName: String): String { + return Paths.get(PathManager.getConfigPath(), libName).toString() +} diff --git a/intellij-ext/src/main/kotlin/com/metalbear/mirrord/MirrordDialogBuilder.kt b/intellij-ext/src/main/kotlin/com/metalbear/mirrord/MirrordDialogBuilder.kt new file mode 100644 index 00000000000..1fdd2e4ec37 --- /dev/null +++ b/intellij-ext/src/main/kotlin/com/metalbear/mirrord/MirrordDialogBuilder.kt @@ -0,0 +1,78 @@ +package com.metalbear.mirrord + +import com.intellij.openapi.ui.DialogBuilder +import com.intellij.ui.components.JBList +import java.awt.BorderLayout +import java.awt.Dimension +import java.awt.GridBagLayout +import java.awt.GridLayout +import javax.swing.* +import javax.swing.border.EmptyBorder + + +class MirrordDialogBuilder { + private val dialogHeading: String = "mirrord" + private val podLabel: JLabel = JLabel("Select pod to impersonate") + private val namespaceLabel: JLabel = JLabel("Select Namespace to use") + private val optionLabel: JLabel = JLabel("Options") + + fun createMirrordKubeDialog(pods: JBList, fileOpsCheckbox: JCheckBox, remoteDnsCheckbox: JCheckBox, ephemeralCheckbox: JCheckBox, agentRustLog: JTextField, rustLog: JTextField): JPanel { + val dialogPanel = JPanel(BorderLayout()) + podLabel.border = EmptyBorder(5, 40, 5, 5) + + val podPanel = JPanel(GridLayout(2, 1, 10, 5)) + podPanel.add(podLabel, BorderLayout.NORTH) + podPanel.add(pods) + + dialogPanel.add(podPanel, BorderLayout.WEST) + + dialogPanel.add(JSeparator(JSeparator.VERTICAL), + BorderLayout.CENTER) + + val optionsPanel = JPanel(GridLayout(6, 1, 10, 2)) + optionLabel.border = EmptyBorder(5, 110, 5, 20) + + optionsPanel.add(optionLabel) + optionsPanel.add(fileOpsCheckbox) + optionsPanel.add(remoteDnsCheckbox) + optionsPanel.add(ephemeralCheckbox) + + val agentLogPanel = JPanel(GridBagLayout()) + agentLogPanel.add(JLabel("Agent Log Level: ")) + agentRustLog.size = Dimension(5, 5) + agentLogPanel.add(agentRustLog) + + agentLogPanel.border = EmptyBorder(10, 10, 10, 10) + + val rustLogPanel = JPanel(GridBagLayout()) + rustLogPanel.add(JLabel("Layer Log Level: ")) + rustLog.size = Dimension(5, 5) + rustLogPanel.add(rustLog) + + rustLogPanel.border = EmptyBorder(10, 10, 10, 10) + + optionsPanel.add(agentLogPanel) + optionsPanel.add(rustLogPanel) + + dialogPanel.add(optionsPanel, BorderLayout.EAST) + + return dialogPanel + } + + fun createMirrordNamespaceDialog(namespaces: JBList): JPanel { + val dialogPanel = JPanel(BorderLayout()) + namespaceLabel.border = EmptyBorder(5, 20, 5, 20) + dialogPanel.add(namespaceLabel, BorderLayout.NORTH) + dialogPanel.add(namespaces, BorderLayout.SOUTH) + return dialogPanel + } + + fun getDialogBuilder(dialogPanel: JPanel): DialogBuilder { + val dialogBuilder = DialogBuilder() + + dialogBuilder.setCenterPanel(dialogPanel) + dialogBuilder.setTitle(dialogHeading) + + return dialogBuilder + } +} \ No newline at end of file diff --git a/intellij-ext/src/main/kotlin/com/metalbear/mirrord/MirrordEnabler.kt b/intellij-ext/src/main/kotlin/com/metalbear/mirrord/MirrordEnabler.kt new file mode 100644 index 00000000000..9377831b582 --- /dev/null +++ b/intellij-ext/src/main/kotlin/com/metalbear/mirrord/MirrordEnabler.kt @@ -0,0 +1,34 @@ +package com.metalbear.mirrord + +import com.intellij.notification.NotificationGroup +import com.intellij.notification.NotificationGroupManager +import com.intellij.openapi.actionSystem.AnActionEvent +import com.intellij.openapi.actionSystem.ToggleAction + +@Suppress("DialogTitleCapitalization") +class MirrordEnabler : ToggleAction() { + private val notificationManager: NotificationGroup + get() = NotificationGroupManager + .getInstance() + .getNotificationGroup("mirrord Notification Handler") + + + override fun isSelected(e: AnActionEvent): Boolean { + return MirrordListener.enabled + } + + override fun setSelected(e: AnActionEvent, state: Boolean) { + if (state) { + notificationManager + .createNotification("mirrord", "mirrord enabled") + .notify(e.project) + + } else { + notificationManager + .createNotification("mirrord", "mirrord disabled") + .notify(e.project) + } + + MirrordListener.enabled = state + } +} \ No newline at end of file diff --git a/intellij-ext/src/main/kotlin/com/metalbear/mirrord/MirrordListener.kt b/intellij-ext/src/main/kotlin/com/metalbear/mirrord/MirrordListener.kt new file mode 100644 index 00000000000..59d92227e22 --- /dev/null +++ b/intellij-ext/src/main/kotlin/com/metalbear/mirrord/MirrordListener.kt @@ -0,0 +1,96 @@ +package com.metalbear.mirrord + +import com.intellij.execution.ExecutionListener +import com.intellij.execution.process.ProcessHandler +import com.intellij.execution.runners.ExecutionEnvironment +import com.intellij.openapi.ui.DialogWrapper +import com.intellij.ui.components.JBList +import javax.swing.JCheckBox +import javax.swing.JTextField + + +class MirrordListener : ExecutionListener { + private val mirrordEnv: LinkedHashMap = LinkedHashMap() + + init { + val (ldPreloadPath, dylibPath, defaultMirrordAgentLog, rustLog, invalidCertificates, ephemeralContainers) = MirrordDefaultData() + + mirrordEnv["DYLD_INSERT_LIBRARIES"] = dylibPath + mirrordEnv["LD_PRELOAD"] = ldPreloadPath + mirrordEnv["MIRRORD_AGENT_RUST_LOG"] = defaultMirrordAgentLog + mirrordEnv["RUST_LOG"] = rustLog + mirrordEnv["MIRRORD_ACCEPT_INVALID_CERTIFICATES"] = invalidCertificates.toString() + mirrordEnv["MIRRORD_EPHEMERAL_CONTAINER"] = ephemeralContainers.toString() + + } + + companion object { + var enabled: Boolean = false + var envSet: Boolean = false + } + + override fun processStarting(executorId: String, env: ExecutionEnvironment) { + + if (enabled) { + val customDialogBuilder = MirrordDialogBuilder() + val kubeDataProvider = KubeDataProvider() + + // Prompt the user to choose a namespace + val namespaces = JBList(kubeDataProvider.getNamespaces()) + val panel = customDialogBuilder.createMirrordNamespaceDialog(namespaces) + val dialogBuilder = customDialogBuilder.getDialogBuilder(panel) + + // SUCCESS: Ask the user for the impersonated pod in the chosen namespace + if (dialogBuilder.show() == DialogWrapper.OK_EXIT_CODE) { + val choseNamespace = namespaces.selectedValue + val pods = JBList(kubeDataProvider.getNameSpacedPods(choseNamespace)) + + val fileOpsCheckbox = JCheckBox("Enable File Operations") + val remoteDnsCheckbox = JCheckBox("Enable Remote DNS") + val ephemeralContainerCheckBox = JCheckBox("Enable Ephemeral Containers") + + val agentRustLog = JTextField(mirrordEnv["MIRRORD_AGENT_RUST_LOG"]) + val rustLog = JTextField(mirrordEnv["RUST_LOG"]) + + val panel = customDialogBuilder.createMirrordKubeDialog(pods, fileOpsCheckbox, remoteDnsCheckbox, ephemeralContainerCheckBox, agentRustLog, rustLog) + val dialogBuilder = customDialogBuilder.getDialogBuilder(panel) + + // SUCCESS: set the respective environment variables + if (dialogBuilder.show() == DialogWrapper.OK_EXIT_CODE && pods.selectedValue != null) { + mirrordEnv["MIRRORD_AGENT_IMPERSONATED_POD_NAME"] = pods.selectedValue as String + mirrordEnv["MIRRORD_FILE_OPS"] = fileOpsCheckbox.isSelected.toString() + mirrordEnv["MIRRORD_EPHEMERAL_CONTAINER"] = ephemeralContainerCheckBox.isSelected.toString() + mirrordEnv["MIRRORD_REMOTE_DNS"] = remoteDnsCheckbox.isSelected.toString() + mirrordEnv["MIRRORD_AGENT_RUST_LOG"] = agentRustLog.text.toString() + + val envMap = getRunConfigEnv(env) + envMap.putAll(mirrordEnv) + + envSet = true + } + } + } + // FAILURE: Just call the parent implementation + super.processStarting(executorId, env) + } + + override fun processTerminating(executorId: String, env: ExecutionEnvironment, handler: ProcessHandler) { + // NOTE: If the option was enabled, and we actually set the env, i.e. cancel was not clicked on the dialog, + // we clear up the Environment, because we don't want mirrord to run again if the user hits debug again + // with mirrord toggled off. + if (enabled and envSet) { + val envMap = getRunConfigEnv(env) + for (key in mirrordEnv.keys) { + if (mirrordEnv.containsKey(key)) { + envMap.remove(key) + } + } + } + super.processTerminating(executorId, env, handler) + } + + private fun getRunConfigEnv(env: ExecutionEnvironment): LinkedHashMap { + val envMethod = env.runProfile.javaClass.getMethod("getEnvs") + return envMethod.invoke(env.runProfile) as LinkedHashMap + } +} \ No newline at end of file diff --git a/intellij-ext/src/main/kotlin/icons/MirrordIcons.kt b/intellij-ext/src/main/kotlin/icons/MirrordIcons.kt new file mode 100644 index 00000000000..02351e10705 --- /dev/null +++ b/intellij-ext/src/main/kotlin/icons/MirrordIcons.kt @@ -0,0 +1,8 @@ +package icons + +import com.intellij.openapi.util.IconLoader + +object MirrordIcons { + @JvmField + val mirrordIcon = IconLoader.getIcon("/META-INF/pluginIcon.svg", javaClass) +} \ No newline at end of file diff --git a/intellij-ext/src/main/resources/META-INF/plugin.xml b/intellij-ext/src/main/resources/META-INF/plugin.xml new file mode 100644 index 00000000000..f9a8504b962 --- /dev/null +++ b/intellij-ext/src/main/resources/META-INF/plugin.xml @@ -0,0 +1,34 @@ + + + com.metalbear.mirrord + mirrord + MetalBear + + + + com.intellij.modules.lang + + + + + + + + + + + + + + + + + diff --git a/intellij-ext/src/main/resources/META-INF/pluginIcon.svg b/intellij-ext/src/main/resources/META-INF/pluginIcon.svg new file mode 100644 index 00000000000..ceaaf74b104 --- /dev/null +++ b/intellij-ext/src/main/resources/META-INF/pluginIcon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/intellij-ext/src/main/resources/META-INF/usage.gif b/intellij-ext/src/main/resources/META-INF/usage.gif new file mode 100644 index 00000000000..607a50d2253 Binary files /dev/null and b/intellij-ext/src/main/resources/META-INF/usage.gif differ diff --git a/intellij-ext/src/test/kotlin/com/metalbear/mirrord/MyPluginTest.kt b/intellij-ext/src/test/kotlin/com/metalbear/mirrord/MyPluginTest.kt new file mode 100644 index 00000000000..6c5c4a3e7a5 --- /dev/null +++ b/intellij-ext/src/test/kotlin/com/metalbear/mirrord/MyPluginTest.kt @@ -0,0 +1,31 @@ +package com.metalbear.mirrord + +import com.intellij.ide.highlighter.XmlFileType +import com.intellij.psi.xml.XmlFile +import com.intellij.testFramework.TestDataPath +import com.intellij.testFramework.fixtures.BasePlatformTestCase +import com.intellij.util.PsiErrorElementUtil + +@TestDataPath("\$CONTENT_ROOT/src/test/testData") +class MyPluginTest : BasePlatformTestCase() { + + fun testXMLFile() { + val psiFile = myFixture.configureByText(XmlFileType.INSTANCE, "bar") + val xmlFile = assertInstanceOf(psiFile, XmlFile::class.java) + + assertFalse(PsiErrorElementUtil.hasErrors(project, xmlFile.virtualFile)) + + assertNotNull(xmlFile.rootTag) + + xmlFile.rootTag?.let { + assertEquals("foo", it.name) + assertEquals("bar", it.value.text) + } + } + + override fun getTestDataPath() = "src/test/testData/rename" + + fun testRename() { + myFixture.testRename("foo.xml", "foo_after.xml", "a2") + } +} diff --git a/intellij-ext/src/test/testData/rename/foo.xml b/intellij-ext/src/test/testData/rename/foo.xml new file mode 100644 index 00000000000..b21e9f28640 --- /dev/null +++ b/intellij-ext/src/test/testData/rename/foo.xml @@ -0,0 +1,3 @@ + + 1>Foo + diff --git a/intellij-ext/src/test/testData/rename/foo_after.xml b/intellij-ext/src/test/testData/rename/foo_after.xml new file mode 100644 index 00000000000..980ca960f1a --- /dev/null +++ b/intellij-ext/src/test/testData/rename/foo_after.xml @@ -0,0 +1,3 @@ + + Foo +