Browse Source

venus-client

master
zeus 4 years ago
parent
commit
6c01da5454
  1. 31
      .gitignore
  2. 16
      builders-update.sh
  3. 8
      client/css/app.b2f70a29.css
  4. 10
      client/css/chunk-vendors.d0de25b8.css
  5. BIN
      client/favicon.ico
  6. BIN
      client/fonts/themify.2c454669.eot
  7. BIN
      client/fonts/themify.a1ecc3b8.woff
  8. BIN
      client/fonts/themify.e23a7dca.ttf
  9. BIN
      client/img/docker.7b56657d.png
  10. BIN
      client/img/hybrid-1.852eef88.png
  11. BIN
      client/img/loading.f4404720.gif
  12. BIN
      client/img/penguinfledgling2.d4cb3ed7.png
  13. 362
      client/img/themify.9c8e96ec.svg
  14. BIN
      client/img/warning.f9cebb9b.png
  15. 1
      client/index.html
  16. 2
      client/js/app.629eff8d.js
  17. 1
      client/js/app.629eff8d.js.map
  18. 110
      client/js/chunk-vendors.1ae3a34a.js
  19. 1
      client/js/chunk-vendors.1ae3a34a.js.map
  20. 40
      files/VuetableCssConfig.js
  21. 10
      files/get-base-ca
  22. 9
      files/get-swarmlab-ca
  23. 379
      files/serve.js
  24. 16
      files/status-1.sh
  25. 65
      files/status.sh
  26. 15
      git-update.sh
  27. 29
      hybrid/scripts/add-nic-veth-pair.sh
  28. 26
      hybrid/scripts/add-nic.sh
  29. 9
      hybrid/scripts/create-keys.sh
  30. 24
      hybrid/scripts/expose-netns.sh
  31. 279
      install.sh
  32. 66
      install/install-CentOS.sh
  33. 59
      install/install-ubuntu.sh
  34. 159
      install/install-wg.sh
  35. 371
      llo/connect-new.js
  36. 11
      llo/runconfig.js
  37. 11
      myconfig/runconfig.js
  38. 20
      package.json
  39. 64
      start
  40. 4
      stop
  41. 47
      update-agent.sh

31
.gitignore

@ -0,0 +1,31 @@
.DS_Store
node_modules
hybrid/connect/
hybrid/keys.json
venuslog/logs/
venuslog/
venuslog/*
venuslog
logs
package-lock.json
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

16
builders-update.sh

@ -0,0 +1,16 @@
#!/bin/sh
REPOSRC=$1
LOCALREPO=$2
# We do it this way so that we can abstract if from just git later on
LOCALREPO_VC_DIR=$LOCALREPO/.git
cd builders
if [ ! -d $LOCALREPO_VC_DIR ]
then
git clone $REPOSRC $LOCALREPO
else
cd $LOCALREPO
git pull $REPOSRC
fi

8
client/css/app.b2f70a29.css

File diff suppressed because one or more lines are too long

10
client/css/chunk-vendors.d0de25b8.css

File diff suppressed because one or more lines are too long

BIN
client/favicon.ico

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

BIN
client/fonts/themify.2c454669.eot

Binary file not shown.

BIN
client/fonts/themify.a1ecc3b8.woff

Binary file not shown.

BIN
client/fonts/themify.e23a7dca.ttf

Binary file not shown.

BIN
client/img/docker.7b56657d.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

BIN
client/img/hybrid-1.852eef88.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

BIN
client/img/loading.f4404720.gif

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

BIN
client/img/penguinfledgling2.d4cb3ed7.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

362
client/img/themify.9c8e96ec.svg

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 229 KiB

BIN
client/img/warning.f9cebb9b.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

1
client/index.html

@ -0,0 +1 @@
<!DOCTYPE html><html lang=""><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Vue App</title><link href="/css/app.b2f70a29.css" rel="preload" as="style"><link href="/css/chunk-vendors.d0de25b8.css" rel="preload" as="style"><link href="/js/app.629eff8d.js" rel="preload" as="script"><link href="/js/chunk-vendors.1ae3a34a.js" rel="preload" as="script"><link href="/css/chunk-vendors.d0de25b8.css" rel="stylesheet"><link href="/css/app.b2f70a29.css" rel="stylesheet"></head><body><div id="app"></div><script src="/js/chunk-vendors.1ae3a34a.js"></script><script src="/js/app.629eff8d.js"></script></body></html>

2
client/js/app.629eff8d.js

File diff suppressed because one or more lines are too long

1
client/js/app.629eff8d.js.map

File diff suppressed because one or more lines are too long

110
client/js/chunk-vendors.1ae3a34a.js

File diff suppressed because one or more lines are too long

1
client/js/chunk-vendors.1ae3a34a.js.map

File diff suppressed because one or more lines are too long

40
files/VuetableCssConfig.js

@ -0,0 +1,40 @@
export default {
table: {
tableWrapper: '',
tableHeaderClass: 'mb-0',
tableBodyClass: 'mb-0',
tableClass: 'table table-bordered table-hover table-sm table-condensed whitespace',
loadingClass: 'loading',
ascendingIcon: 'fa fa-chevron-up',
descendingIcon: 'fa fa-chevron-down',
ascendingClass: 'sorted-asc',
descendingClass: 'sorted-desc',
sortableIcon: 'fa fa-sort',
detailRowClass: 'vuetable-detail-row',
handleIcon: 'fa fa-bars text-secondary',
renderIcon: function(classes, options) {
return `<i class="${classes.join(" ")}" ${options}></span>`;
}
},
paginationInfo: {
infoClass: 'pull-left float-left align-self-end'
},
pagination: {
wrapperClass: "pagination pull-right float-right",
activeClass: "active",
disabledClass: "disabled",
pageClass: "btn btn-border",
linkClass: "btn btn-border",
paginationClass: "pagination",
paginationInfoClass: "float-left",
//pagination-info-class=""
//pagination-component-class=""
dropdownClass: "form-control",
icons: {
first: "",
prev: "",
next: "",
last: ""
}
}
}

10
files/get-base-ca

@ -0,0 +1,10 @@
registry_address=registry.vlabs.uniwa.gr
registry_port=5080
mkdir -p /etc/docker/certs.d/$registry_address:$registry_port
openssl s_client -showcerts -connect $registry_address:$registry_port < /dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > /etc/docker/certs.d/$registry_address:$registry_port/ca.crt
registry_address=registry.vlabs.uniwa.gr
registry_port=5043
mkdir -p /etc/docker/certs.d/$registry_address:$registry_port
openssl s_client -showcerts -connect $registry_address:$registry_port < /dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > /etc/docker/certs.d/$registry_address:$registry_port/ca.crt

9
files/get-swarmlab-ca

@ -0,0 +1,9 @@
registry_address=hub.swarmlab.io
registry_port=5443
mkdir -p /etc/docker/certs.d/$registry_address:$registry_port
openssl s_client -showcerts -connect $registry_address:$registry_port < /dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > /etc/docker/certs.d/$registry_address:$registry_port/ca.crt
registry_port=5480
mkdir -p /etc/docker/certs.d/$registry_address:$registry_port
openssl s_client -showcerts -connect $registry_address:$registry_port < /dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > /etc/docker/certs.d/$registry_address:$registry_port/ca.crt

379
files/serve.js

@ -0,0 +1,379 @@
const {
info,
error,
hasProjectYarn,
hasProjectPnpm,
openBrowser,
IpcMessenger
} = require('@vue/cli-shared-utils')
const defaults = {
host: '0.0.0.0',
//port: 8080,
port: 3088,
https: false
}
module.exports = (api, options) => {
api.registerCommand('serve', {
description: 'start development server',
usage: 'vue-cli-service serve [options] [entry]',
options: {
'--open': `open browser on server start`,
'--copy': `copy url to clipboard on server start`,
'--stdin': `close when stdin ends`,
'--mode': `specify env mode (default: development)`,
'--host': `specify host (default: ${defaults.host})`,
'--port': `specify port (default: ${defaults.port})`,
'--https': `use https (default: ${defaults.https})`,
'--public': `specify the public network URL for the HMR client`,
'--skip-plugins': `comma-separated list of plugin names to skip for this run`
}
}, async function serve (args) {
info('Starting development server...')
// although this is primarily a dev server, it is possible that we
// are running it in a mode with a production env, e.g. in E2E tests.
const isInContainer = checkInContainer()
const isProduction = process.env.NODE_ENV === 'production'
const url = require('url')
const { chalk } = require('@vue/cli-shared-utils')
const webpack = require('webpack')
const WebpackDevServer = require('webpack-dev-server')
const portfinder = require('portfinder')
const prepareURLs = require('../util/prepareURLs')
const prepareProxy = require('../util/prepareProxy')
const launchEditorMiddleware = require('launch-editor-middleware')
const validateWebpackConfig = require('../util/validateWebpackConfig')
const isAbsoluteUrl = require('../util/isAbsoluteUrl')
// configs that only matters for dev server
api.chainWebpack(webpackConfig => {
if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') {
webpackConfig
.devtool('eval-cheap-module-source-map')
webpackConfig
.plugin('hmr')
.use(require('webpack/lib/HotModuleReplacementPlugin'))
// https://github.com/webpack/webpack/issues/6642
// https://github.com/vuejs/vue-cli/issues/3539
webpackConfig
.output
.globalObject(`(typeof self !== 'undefined' ? self : this)`)
if (!process.env.VUE_CLI_TEST && options.devServer.progress !== false) {
webpackConfig
.plugin('progress')
.use(require('webpack/lib/ProgressPlugin'))
}
}
})
// resolve webpack config
const webpackConfig = api.resolveWebpackConfig()
// check for common config errors
validateWebpackConfig(webpackConfig, api, options)
// load user devServer options with higher priority than devServer
// in webpack config
const projectDevServerOptions = Object.assign(
webpackConfig.devServer || {},
options.devServer
)
// expose advanced stats
if (args.dashboard) {
const DashboardPlugin = require('../webpack/DashboardPlugin')
;(webpackConfig.plugins = webpackConfig.plugins || []).push(new DashboardPlugin({
type: 'serve'
}))
}
// entry arg
const entry = args._[0]
if (entry) {
webpackConfig.entry = {
app: api.resolve(entry)
}
}
// resolve server options
const useHttps = args.https || projectDevServerOptions.https || defaults.https
const protocol = useHttps ? 'https' : 'http'
const host = args.host || process.env.HOST || projectDevServerOptions.host || defaults.host
portfinder.basePort = args.port || process.env.PORT || projectDevServerOptions.port || defaults.port
const port = await portfinder.getPortPromise()
const rawPublicUrl = args.public || projectDevServerOptions.public
const publicUrl = rawPublicUrl
? /^[a-zA-Z]+:\/\//.test(rawPublicUrl)
? rawPublicUrl
: `${protocol}://${rawPublicUrl}`
: null
const urls = prepareURLs(
protocol,
host,
port,
isAbsoluteUrl(options.publicPath) ? '/' : options.publicPath
)
const localUrlForBrowser = publicUrl || urls.localUrlForBrowser
const proxySettings = prepareProxy(
projectDevServerOptions.proxy,
api.resolve('public')
)
// inject dev & hot-reload middleware entries
if (!isProduction) {
const sockPath = projectDevServerOptions.sockPath || '/sockjs-node'
const sockjsUrl = publicUrl
// explicitly configured via devServer.public
? `?${publicUrl}&sockPath=${sockPath}`
: isInContainer
// can't infer public network url if inside a container...
// use client-side inference (note this would break with non-root publicPath)
? ``
// otherwise infer the url
: `?` + url.format({
protocol,
port,
hostname: urls.lanUrlForConfig || 'localhost'
}) + `&sockPath=${sockPath}`
const devClients = [
// dev server client
require.resolve(`webpack-dev-server/client`) + sockjsUrl,
// hmr client
require.resolve(projectDevServerOptions.hotOnly
? 'webpack/hot/only-dev-server'
: 'webpack/hot/dev-server')
// TODO custom overlay client
// `@vue/cli-overlay/dist/client`
]
if (process.env.APPVEYOR) {
devClients.push(`webpack/hot/poll?500`)
}
// inject dev/hot client
addDevClientToEntry(webpackConfig, devClients)
}
// create compiler
const compiler = webpack(webpackConfig)
// handle compiler error
compiler.hooks.failed.tap('vue-cli-service serve', msg => {
error(msg)
process.exit(1)
})
// create server
const server = new WebpackDevServer(compiler, Object.assign({
logLevel: 'silent',
clientLogLevel: 'silent',
historyApiFallback: {
disableDotRule: true,
rewrites: genHistoryApiFallbackRewrites(options.publicPath, options.pages)
},
contentBase: api.resolve('public'),
watchContentBase: !isProduction,
hot: !isProduction,
injectClient: false,
compress: isProduction,
publicPath: options.publicPath,
overlay: isProduction // TODO disable this
? false
: { warnings: false, errors: true }
}, projectDevServerOptions, {
https: useHttps,
proxy: proxySettings,
// eslint-disable-next-line no-shadow
before (app, server) {
// launch editor support.
// this works with vue-devtools & @vue/cli-overlay
app.use('/__open-in-editor', launchEditorMiddleware(() => console.log(
`To specify an editor, specify the EDITOR env variable or ` +
`add "editor" field to your Vue project config.\n`
)))
// allow other plugins to register middlewares, e.g. PWA
api.service.devServerConfigFns.forEach(fn => fn(app, server))
// apply in project middlewares
projectDevServerOptions.before && projectDevServerOptions.before(app, server)
},
// avoid opening browser
open: false
}))
;['SIGINT', 'SIGTERM'].forEach(signal => {
process.on(signal, () => {
server.close(() => {
process.exit(0)
})
})
})
if (args.stdin) {
process.stdin.on('end', () => {
server.close(() => {
process.exit(0)
})
})
process.stdin.resume()
}
// on appveyor, killing the process with SIGTERM causes execa to
// throw error
if (process.env.VUE_CLI_TEST) {
process.stdin.on('data', data => {
if (data.toString() === 'close') {
console.log('got close signal!')
server.close(() => {
process.exit(0)
})
}
})
}
return new Promise((resolve, reject) => {
// log instructions & open browser on first compilation complete
let isFirstCompile = true
compiler.hooks.done.tap('vue-cli-service serve', stats => {
if (stats.hasErrors()) {
return
}
let copied = ''
if (isFirstCompile && args.copy) {
try {
require('clipboardy').writeSync(localUrlForBrowser)
copied = chalk.dim('(copied to clipboard)')
} catch (_) {
/* catch exception if copy to clipboard isn't supported (e.g. WSL), see issue #3476 */
}
}
const networkUrl = publicUrl
? publicUrl.replace(/([^/])$/, '$1/')
: urls.lanUrlForTerminal
console.log()
console.log(` App running at:`)
console.log(` - Local: ${chalk.cyan(urls.localUrlForTerminal)} ${copied}`)
if (!isInContainer) {
console.log(` - Network: ${chalk.cyan(networkUrl)}`)
} else {
console.log()
console.log(chalk.yellow(` It seems you are running Vue CLI inside a container.`))
if (!publicUrl && options.publicPath && options.publicPath !== '/') {
console.log()
console.log(chalk.yellow(` Since you are using a non-root publicPath, the hot-reload socket`))
console.log(chalk.yellow(` will not be able to infer the correct URL to connect. You should`))
console.log(chalk.yellow(` explicitly specify the URL via ${chalk.blue(`devServer.public`)}.`))
console.log()
}
console.log(chalk.yellow(` Access the dev server via ${chalk.cyan(
`${protocol}://localhost:<your container's external mapped port>${options.publicPath}`
)}`))
}
console.log()
if (isFirstCompile) {
isFirstCompile = false
if (!isProduction) {
const buildCommand = hasProjectYarn(api.getCwd()) ? `yarn build` : hasProjectPnpm(api.getCwd()) ? `pnpm run build` : `npm run build`
console.log(` Note that the development build is not optimized.`)
console.log(` To create a production build, run ${chalk.cyan(buildCommand)}.`)
} else {
console.log(` App is served in production mode.`)
console.log(` Note this is for preview or E2E testing only.`)
}
console.log()
if (args.open || projectDevServerOptions.open) {
const pageUri = (projectDevServerOptions.openPage && typeof projectDevServerOptions.openPage === 'string')
? projectDevServerOptions.openPage
: ''
openBrowser(localUrlForBrowser + pageUri)
}
// Send final app URL
if (args.dashboard) {
const ipc = new IpcMessenger()
ipc.send({
vueServe: {
url: localUrlForBrowser
}
})
}
// resolve returned Promise
// so other commands can do api.service.run('serve').then(...)
resolve({
server,
url: localUrlForBrowser
})
} else if (process.env.VUE_CLI_TEST) {
// signal for test to check HMR
console.log('App updated')
}
})
server.listen(port, host, err => {
if (err) {
reject(err)
}
})
})
})
}
function addDevClientToEntry (config, devClient) {
const { entry } = config
if (typeof entry === 'object' && !Array.isArray(entry)) {
Object.keys(entry).forEach((key) => {
entry[key] = devClient.concat(entry[key])
})
} else if (typeof entry === 'function') {
config.entry = entry(devClient)
} else {
config.entry = devClient.concat(entry)
}
}
// https://stackoverflow.com/a/20012536
function checkInContainer () {
if ('CODESANDBOX_SSE' in process.env) {
return true
}
const fs = require('fs')
if (fs.existsSync(`/proc/1/cgroup`)) {
const content = fs.readFileSync(`/proc/1/cgroup`, 'utf-8')
return /:\/(lxc|docker|kubepods(\.slice)?)\//.test(content)
}
}
function genHistoryApiFallbackRewrites (baseUrl, pages = {}) {
const path = require('path')
const multiPageRewrites = Object
.keys(pages)
// sort by length in reversed order to avoid overrides
// eg. 'page11' should appear in front of 'page1'
.sort((a, b) => b.length - a.length)
.map(name => ({
from: new RegExp(`^/${name}`),
to: path.posix.join(baseUrl, pages[name].filename || `${name}.html`)
}))
return [
...multiPageRewrites,
{ from: /./, to: path.posix.join(baseUrl, 'index.html') }
]
}
module.exports.defaultModes = {
serve: 'development'
}

16
files/status-1.sh

@ -0,0 +1,16 @@
#!/bin/bash
net=wg0
test_time=2
T1=$(cat /sys/class/net/$net/statistics/tx_bytes)
sleep $test_time
T2=$(cat /sys/class/net/$net/statistics/tx_bytes)
#echo "t2=$T2 t1=$T1"
tot=$(( (T2 - T1)))
if [ $tot -eq 0 ]; then
echo "1"
fi

65
files/status.sh

@ -0,0 +1,65 @@
#!/bin/bash
if [ -z ${1} ] ; then
echo "usage: status.sh interface "
exit
fi
CHECK="off";
ACTIVITY="off";
net=${1}
ping_c=2 # stop after sending packets
ping_i=1 # set interval in seconds
ping_w=2 # timeout in seconds
ping_iptmp=$(ip addr show $net | grep -o "inet [0-9]*\.[0-9]*\.[0-9]*" | grep -o "[0-9]*\.[0-9]*\.[0-9]*")
ping_ip="$ping_iptmp.1"
#ping_ip=10.13.13.1
if [[ -d /sys/class/net/$net ]]; then
CHECK="on";
T1=$(cat /sys/class/net/$net/statistics/tx_bytes)
ping -I $net -c $ping_c -i $ping_i -w $ping_w $ping_ip &> /dev/null
T2=$(cat /sys/class/net/$net/statistics/tx_bytes)
tot=$(( (T2 - T1)))
if [ $tot -ne 0 ]; then
ACTIVITY="on";
fi
fi
#echo "check $CHECK activity $ACTIVITY"
if [ "$CHECK" == "on" ] && [ "$ACTIVITY" == "on" ] ; then
hybridswarm='Online'
else
hybridswarm='NotOnline'
fi
dockerswarm=$(docker info --format "{{json .}}" | jq .Swarm.LocalNodeState)
tempswarm="${dockerswarm%\"}"
tempswarm="${tempswarm#\"}"
dockerswarm=$tempswarm
if [ "$dockerswarm" == "active" ] ; then
dockerswarmid=$(docker info --format "{{json .}}" | jq .Swarm.NodeID)
tempswarm1="${dockerswarmid%\"}"
tempswarm1="${tempswarm1#\"}"
swarmlabid=$tempswarm1
else
swarmlabid="-1";
fi
if [ -z "$dockerswarm" ] ; then
dockerswarm=none
fi
jq \
--arg key0 'swarmlab' --arg swarmlab $dockerswarm \
--arg key1 'hybrid' --arg hybrid $hybridswarm \
--arg key2 'swarmlabid' --arg swarmlabid $swarmlabid \
'. | .[$key0]=$swarmlab | .[$key1]=$hybrid | .[$key2]=$swarmlabid' <<<'{}'

15
git-update.sh

@ -0,0 +1,15 @@
#!/bin/sh
REPOSRC=$1
LOCALREPO=$2
# We do it this way so that we can abstract if from just git later on
LOCALREPO_VC_DIR=$LOCALREPO/.git
if [ ! -d $LOCALREPO_VC_DIR ]
then
git clone $REPOSRC $LOCALREPO
else
cd $LOCALREPO
git pull $REPOSRC
fi

29
hybrid/scripts/add-nic-veth-pair.sh

@ -0,0 +1,29 @@
#!/bin/sh
if [ $# -lt 3 ]; then
echo "This script will create a veth pair, attach one end to an OVS bridge,"
echo "and another end to the specified container as a virtual NIC."
echo ""
echo "Usage: $0 <CONTAINER> <VETH> <PEER> <OVS BRIDGE>"
echo "Example: $0 test-container-1 veth-1 peer-1 br-int"
exit 1
fi
CONTAINER=$1
VETH=$2
PEER=$3
OVS_BR=$4
NETNS=`sudo docker inspect -f '{{.State.Pid}}' $CONTAINER`
echo "add veth pair[$VETH <--> $PEER] to container[$CONTAINER] in netns[$NETNS]"
ip link delete $VETH || true
ip link add $VETH type veth peer name $PEER
echo "add port to ovs bridge $OVS_BR"
ovs-vsctl add-port $OVS_BR $VETH
echo "move $PEER to netns $NETNS"
ip link set $PEER netns $NETNS
ip netns exec $NETNS ip link set dev $PEER up
echo "done"

26
hybrid/scripts/add-nic.sh

@ -0,0 +1,26 @@
#!/bin/sh
if [ $# -lt 3 ]; then
echo "This script will add an OVS internal port to an OVS bridge,"
echo "then assign the port to the specified container as a virtual NIC."
echo ""
echo "Usage: $0 <CONTAINER> <NIC NAME> <OVS BRIDGE>"
echo "Example: $0 test-container-1 vnic-1 br-int"
exit 1
fi
CONTAINER=$1
PORT=$2
OVS_BR=$3
NETNS=`sudo docker inspect -f '{{.State.Pid}}' $CONTAINER`
echo "add port[$PORT] to container[$CONTAINER] in netns[$NETNS]"
echo "add port to ovs bridge $OVS_BR"
ovs-vsctl add-port $OVS_BR $PORT -- set Interface $PORT type=internal
#ovs-vsctl add-port br-int vnic-1 -- set Interface vnic-1 type=internal
echo "move $PORT to netns $NETNS"
ip link set $PORT netns $NETNS
ip netns exec $NETNS ip link set dev $PORT up
echo "done"

9
hybrid/scripts/create-keys.sh

@ -0,0 +1,9 @@
wg genkey | tee ./privatekey | wg pubkey > ./publickey
privatekey=$(head -1 ./privatekey)
publickey=$(head -1 ./publickey)
jq --arg key0 'private' --arg private $privatekey --arg key1 'public' --arg public $publickey '. | .[$key0]=$private | .[$key1]=$public ' <<<'{}' | tee ./keys.json

24
hybrid/scripts/expose-netns.sh

@ -0,0 +1,24 @@
#!/bin/bash
if [ $# -ne 1 ]; then
echo "Usage: $0 <container id or name>"
exit 1
fi
echo "expose container $1 netns"
NETNS=`sudo docker inspect -f '{{.State.Pid}}' $1`
if [ ! -d /var/run/netns ]; then
mkdir /var/run/netns
fi
if [ -f /var/run/netns/$NETNS ]; then
rm -rf /var/run/netns/$NETNS
fi
ln -s /proc/$NETNS/ns/net /var/run/netns/$NETNS
echo "done. netns: $NETNS"
echo "============================="
echo "current network namespaces: "
echo "============================="
ip netns

279
install.sh

@ -0,0 +1,279 @@
#!/bin/bash
if [[ $EUID -ne 0 ]]; then
wdir=$PWD
wdir_connect="$wdir/hybrid/connect"
toolsok='ok'
# create wdir connect dir
if [ ! -d $wdir_connect ];then
mkdir -p $wdir_connect
fi
#check for jq
if ! command -v jq &> /dev/null
then
toolsok='no'
echo "jq could not be found"
exit
fi
# check version >15
if ! command -v node &> /dev/null
then
toolsok='no'
echo ""
echo "No node found"
echo ""
echo "Install: https://github.com/nodesource/distributions"
echo "Install it and try again!"
echo ""
echo "-----------USING UBUNTU------------"
echo "curl -sL https://deb.nodesource.com/setup_15.x | sudo -E bash -"
echo "sudo apt-get install -y nodejs"
echo ""
exit
else
nodeversion=$(node -v | cut -d'.' -f1)
nodeversion="${nodeversion#v}"
if [ $nodeversion -lt 15 ];then
echo ""
echo "node version < 15"
echo ""
echo "Update: https://github.com/nodesource/distributions"
echo "Update it and try again!"
echo ""
echo "-----------USING UBUNTU------------"
echo "curl -sL https://deb.nodesource.com/setup_15.x | sudo -E bash -"
echo "sudo apt-get install -y nodejs"
echo ""
toolsok='no'
exit
fi
fi
#check for docker
if ! command -v docker &> /dev/null
then
echo ""
echo "Cannot find docker"
echo ""
echo "Install it and try again!"
echo "http://docs.swarmlab.io/SwarmLab-HowTos/labs/Howtos/docker/install.adoc.html"
echo ""
echo "-----------USING UBUNTU------------"
echo "curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -"
echo "sudo add-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable\""
echo "sudo apt update"
echo "sudo apt install -y docker-ce"
echo "sudo usermod -aG docker [USERNAME]"
echo ""
toolsok='no'
exit
else
#check if docker UP
dockerserverdown=$(docker info --format "{{json .}}" | jq .ServerErrors)
if [[ $dockerversion == *denied* ]]; then
echo ""
echo "docker server is down"
echo ""
docker info --format "{{json .}}" | jq .ServerErrors
echo ""
echo "-----------USING UBUNTU------------"
echo ""
echo "Using the following commands you can enable and run docker server";
echo "sudo systemctl enable docker"
echo "sudo systemctl start docker"
echo "sudo systemctl status docker"
echo ""
echo "After adding to the group (usermod command) your shell needs to be restarted. If you dont know what this means please just logout and log in again.";
echo ""
toolsok='no'
exit
fi
#check docker version
dockerversion=$(docker info --format "{{json .}}" | jq .ServerVersion | cut -d'.' -f1)
if [[ ! -z $dockerversion && $dockerversion != 'null' ]] ;then
dockerversion="${dockerversion#\"}"
if [ $dockerversion -lt 19 ];then
echo ""
echo "docker version < 19"
echo ""
echo "Update docker and try again!"
echo "http://docs.swarmlab.io/SwarmLab-HowTos/labs/Howtos/docker/install.adoc.html"
echo ""
echo "-----------USING UBUNTU------------"
echo "curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -"
echo "sudo add-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable\""
echo "sudo apt update"
echo "sudo apt install -y docker-ce"
echo "sudo usermod -aG docker [USERNAME]"
echo ""
toolsok='no'
exit
fi
else
echo ""
echo "-----------USING UBUNTU------------"
echo ""
echo "Using the following commands you can enable and run docker server";
echo "sudo systemctl enable docker"
echo "sudo systemctl start docker"
echo "sudo systemctl status docker"
echo ""
echo "After adding to the group (usermod command) your shell needs to be restarted. If you dont know what this means please just logout and log in again.";
echo ""
toolsok='no'
exit
fi
fi
#check for docker-compose
if ! command -v docker-compose &> /dev/null
then
echo ""
echo "Cannot find docker-compose"
echo "Install it and try again!"
echo "http://docs.swarmlab.io/SwarmLab-HowTos/labs/Howtos/docker/install.adoc.html"
echo ""
echo "-----------USING UBUNTU------------"
echo ""
echo "sudo curl -L "https://github.com/docker/compose/releases/download/1.27.4/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose"
echo "sudo chmod +x /usr/local/bin/docker-compose"
echo "sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose"
echo ""
toolsok='no'
exit
else
dockercomposeversion=$(docker-compose -f $wdir/test/run.yml config --services)
if [ $dockercomposeversion != 'swarmlabclient' ];then
echo ""
echo "Cannot find docker-compose"
echo "Install it and try again!"
echo "http://docs.swarmlab.io/SwarmLab-HowTos/labs/Howtos/docker/install.adoc.html"
echo ""
echo "-----------USING UBUNTU------------"
echo ""
echo "sudo curl -L "https://github.com/docker/compose/releases/download/1.27.4/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose"
echo "sudo chmod +x /usr/local/bin/docker-compose"
echo "sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose"
echo ""
toolsok='no'
exit
fi
fi
#check for wireguard
if ! command -v wg &> /dev/null
then
echo ""
/bin/bash ./install/install-wg.sh
echo ""
# echo "Cannot find wg"
# echo "Install it and try again!"
# echo "https://www.wireguard.com/install/"
# echo ""
# echo "-----------USING UBUNTU------------"
# echo ""
# echo "sudo apt install wireguard"
# echo ""
toolsok='no'
exit
fi
#check for pm2
if ! command -v pm2 &> /dev/null
then
toolsok='no'
echo "pm2 could not be found"
echo "sudo npm install -g pm2"
exit
fi
# npm install
#if [ $toolsok == 'ok' ];then
# npm install
# npm audit fix
#fi
if [ $toolsok == 'ok' ];then
npm install
npm audit fix
cd $wdir
fi
if [ $toolsok == 'ok' ];then
#cp -f $wdir/files/VuetableCssConfig.js $wdir/node_modules/vuetable-2/src/components/VuetableCssConfig.js
#cp -f $wdir/files/serve.js $wdir/node_modules/@vue/cli-service/lib/commands/serve.js
cp -f $wdir/files/status.sh $wdir/hybrid/connect/status.sh
cp -f $wdir/files/get-swarmlab-ca $wdir/hybrid/connect/get-swarmlab-ca
cp -f $wdir/files/get-base-ca $wdir/hybrid/connect/get-base-ca
mkdir -p $wdir/venuslog/logs
mkdir -p $wdir/logs
cat << FOE > $wdir/ecosystem.config.js
module.exports = {
"apps": [
{
"name" : "venusclient",
"autorestart" : true,
"watch" : true,
"cwd" : "$wdir",
"script" : "./llo/connect-new.js",
"run_as_user" : "node",
"args" : "start",
"pid_file" : "$wdir/venuslog/pid.pid",
"log_type" : "json",
"log_file" : "$wdir/venuslog/logs/logfile",
"error_file" : "$wdir/venuslog/logs/errorfile",
"out_file" : "$wdir/venuslog/logs/outfile",
"log_date_format": "YYYY-MM-DD HH:mm Z",
"merge_logs" : true,
"exec_mode" : "fork",
"max_restarts": 10,
"max_memory_restart": "500M",
"restart_delay": 1000
},
]
}
FOE
fi
sudo bash ./hybrid/connect/get-base-ca
sudo bash ./hybrid/connect/get-swarmlab-ca
docker pull hub.swarmlab.io:5480/venusclient:latest
#echo $nodeversion
#echo $dockerversion
#echo $dockercomposeversion
#echo $wdir
#echo $wdir_connect
echo "-------------------------"
echo " --------READY------- "
echo "-------------------------"
echo " Start Server: ./start "
echo ""
echo " Stop Server: ./stop "
echo ""
else
echo ""
echo "-------------------------"
echo "Run ./install.sh as Non-Root User"
echo "-------------------------"
echo ""
fi

66
install/install-CentOS.sh

@ -0,0 +1,66 @@
#!/bin/bash
#################################
# set USERNAME #
#################################
USERNAME=
if [ -z "$USERNAME" ]; then
# ------------------------
# Not Tested
# ------------------------
# ------------------------
# install wireguard jq
# ------------------------
sudo yum install -y yum-utils
sudo yum install elrepo-release epel-release
sudo yum install kmod-wireguard wireguard-tools
# ------------------------
# install node version 15
# ------------------------
curl -sL https://deb.nodesource.com/setup_15.x | sudo -E bash -
yum install -y nodejs
# ------------------------
# install docker
# ------------------------
sudo yum-config-manager \
--add-repo \
https://download.docker.com/linux/centos/docker-ce.repo
sudo yum install docker-ce docker-ce-cli containerd.io
sudo systemctl start docker
sudo usermod -aG docker $USERNAME
# ------------------------
# install docker-compose
# ------------------------
sudo curl -L "https://github.com/docker/compose/releases/download/1.27.4/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
# ------------------------
# install pm2
# ------------------------
sudo npm install -g pm2
echo ""
echo "run ./install.sh"
echo ""
else
echo ""
echo "set USERNAME first"
echo ""
fi

59
install/install-ubuntu.sh

@ -0,0 +1,59 @@
#!/bin/bash
#################################
# set USERNAME #
#################################
USERNAME=
if [ -z "$USERNAME" ]; then
# ------------------------
# install wireguard jq
# ------------------------
sudo apt update
sudo apt install wireguard jq
# ------------------------
# install node version 15
# ------------------------
curl -sL https://deb.nodesource.com/setup_15.x | sudo -E bash -
sudo apt-get install -y nodejs
# ------------------------
# install docker
# ------------------------
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
sudo apt update
sudo apt install -y docker-ce
sudo usermod -aG docker $USERNAME
# ------------------------
# install docker-compose
# ------------------------
sudo curl -L "https://github.com/docker/compose/releases/download/1.27.4/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
# ------------------------
# install pm2
# ------------------------
sudo npm install -g pm2
echo ""
echo "run ./install.sh"
echo ""
else
echo ""
echo "set USERNAME first"
echo ""
fi

159
install/install-wg.sh

@ -0,0 +1,159 @@
#!/bin/bash
OS=$(cat /proc/version);
if [[ $OS =~ "Ubuntu" ]]; then
echo ""
echo "sudo apt update; sudo apt install wireguard"
echo ""
elif [[ $OS =~ "Debian" ]]; then
echo ""
echo "sudo apt update; sudo apt install wireguard"
echo ""
elif [[ $OS =~ "Red Hat" ]]; then
echo ""
echo "Red Hat 8"
echo ""
echo "*Method 1: the easiest way is via ELRepo's pre-built module:"
echo ""
echo "sudo yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm https://www.elrepo.org/elrepo-release-8.el8.elrepo.noarch.rpm"
echo "sudo yum install kmod-wireguard wireguard-tools"
echo ""
echo "*Method 2: users running non-standard kernels may wish to use the DKMS package instead:"
echo ""
echo "sudo yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm"
echo "sudo subscription-manager repos --enable codeready-builder-for-rhel-8-$(arch)-rpms"
echo "sudo yum copr enable jdoss/wireguard"
echo "sudo yum install wireguard-dkms wireguard-tools"
echo ""
echo ""
echo "Red Hat 7"
echo ""
echo "Method 1: the easiest way is via ELRepo's pre-built module:"
echo ""
echo "sudo yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm https://www.elrepo.org/elrepo-release-7.el7.elrepo.noarch.rpm"
echo "sudo yum install kmod-wireguard wireguard-tools"
echo ""
echo "Method 2: users running non-standard kernels may wish to use the DKMS package instead:"
echo ""
echo "sudo yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm"
echo "sudo curl -o /etc/yum.repos.d/jdoss-wireguard-epel-7.repo https://copr.fedorainfracloud.org/coprs/jdoss/wireguard/repo/epel-7/jdoss-wireguard-epel-7.repo"
echo "sudo yum install wireguard-dkms wireguard-tools"
echo ""
elif [[ $OS =~ "CentOS" ]]; then
echo ""
echo "CentOS 8"
echo ""
echo "*Method 1: a signed module is available as built-in to CentOS's kernel-plus:"
echo ""
echo "sudo yum install yum-utils epel-release"
echo "sudo yum-config-manager --setopt=centosplus.includepkgs="kernel-plus, kernel-plus-*" --setopt=centosplus.enabled=1 --save"
echo "sudo sed -e 's/^DEFAULTKERNEL=kernel-core$/DEFAULTKERNEL=kernel-plus-core/' -i /etc/sysconfig/kernel"
echo "sudo yum install kernel-plus wireguard-tools"
echo "sudo reboot"
echo ""
echo "*Method 2: the easiest way is via ELRepo's pre-built module:"
echo ""
echo "sudo yum install elrepo-release epel-release"
echo "sudo yum install kmod-wireguard wireguard-tools"
echo ""
echo "*Method 3: users running non-standard kernels may wish to use the DKMS package instead:"
echo ""
echo "sudo yum install epel-release"
echo "sudo yum config-manager --set-enabled PowerTools"
echo "sudo yum copr enable jdoss/wireguard"
echo "sudo yum install wireguard-dkms wireguard-tools"
echo ""
echo "CentOS 7"
echo ""
echo " Method 1: a signed module is available as built-in to CentOS's kernel-plus:"
echo ""
echo " sudo yum install yum-utils epel-release"
echo " sudo yum-config-manager --setopt=centosplus.includepkgs=kernel-plus --enablerepo=centosplus --save"
echo " sudo sed -e 's/^DEFAULTKERNEL=kernel$/DEFAULTKERNEL=kernel-plus/' -i /etc/sysconfig/kernel"
echo " sudo yum install kernel-plus wireguard-tools"
echo " sudo reboot"
echo ""
echo "Method 2: users wishing to stick with the standard kernel may use ELRepo's pre-built module:"
echo ""
echo " sudo yum install epel-release elrepo-release"
echo " sudo yum install yum-plugin-elrepo"
echo " sudo yum install kmod-wireguard wireguard-tools"
echo ""
echo "Method 3: users running non-standard kernels may wish to use the DKMS package instead:"
echo ""
echo " sudo yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm"
echo " sudo curl -o /etc/yum.repos.d/jdoss-wireguard-epel-7.repo https://copr.fedorainfracloud.org/coprs/jdoss/wireguard/repo/epel-7/jdoss-wireguard-epel-7.repo"
echo " sudo yum install wireguard-dkms wireguard-tools"
echo ""
elif [[ $OS =~ "Fedora" ]]; then
echo ""
echo "sudo dnf install wireguard-tools"
echo ""
elif [[ $OS =~ "Mageia" ]]; then
echo ""
echo "sudo urpmi wireguard-tools"
echo ""
elif [[ $OS =~ "SUSE" ]]; then
echo ""
echo "sudo zypper install wireguard-tools"
echo ""
elif [[ $OS =~ "Arch" ]]; then
echo ""
echo "sudo pacman -S wireguard-tools"
echo ""
echo "Users of kernels < 5.6 may also choose wireguard-lts or wireguard-dkms+linux-headers, depending on which kernel is used."
echo ""
elif [[ $OS =~ "Alpine" ]]; then
echo ""
echo "apk add -U wireguard-tools"
echo ""
elif [[ $OS =~ "Gentoo" ]]; then
echo ""
echo "emerge wireguard-tools"
echo ""
elif [[ $OS =~ "Oracle" ]]; then
echo ""
echo "Oracle 8"
echo ""
echo "sudo dnf install oraclelinux-developer-release-el8"
echo "sudo dnf config-manager --disable ol8_developer"
echo "sudo dnf config-manager --enable ol8_developer_UEKR6"
echo "sudo dnf config-manager --save --setopt=ol8_developer_UEKR6.includepkgs='wireguard-tools*'"
echo "sudo dnf install wireguard-tools"
echo ""
echo "Oracle 7"
echo ""
echo "sudo yum install oraclelinux-developer-release-el7"
echo "sudo yum-config-manager --disable ol7_developer"
echo "sudo yum-config-manager --enable ol7_developer_UEKR6"
echo "sudo yum-config-manager --save --setopt=ol7_developer_UEKR6.includepkgs='wireguard-tools*'"
echo "sudo yum install wireguard-tools"
echo ""
elif [[ $OS =~ "Slackware" ]]; then
echo ""
echo " Run with root privileges"
echo ""
echo "for i in wireguard-linux-compat wireguard-tools; "
echo "do "
echo ' wget https://slackbuilds.org/slackbuilds/14.2/network/$i.tar.gz && tar -xzf $i.tar.gz && cd $i && OUTPUT=$(pwd) ./$i.SlackBuild && sudo upgradepkg --install-new ./$i*.tgz && cd ..; '
echo "done"
echo ""
else
echo ""
echo "Can't find what distribution of linux your running!"
echo " see https://www.wireguard.com/install/"
echo ""
fi

371
llo/connect-new.js

@ -0,0 +1,371 @@
var fs = require('fs');
var express = require('express');
var http = require('http');
var app = express();
const cors = require('cors')
const helmet = require('helmet');
var allowedOrigins = [
'http://localhost:3080',
'http://localhost:3088',
'http://localhost:8085'
];
app.use(cors({
origin: function(origin, callback){ // allow requests with no origin
// (like mobile apps or curl requests)
if(!origin)
return callback(null, true);
if(allowedOrigins.indexOf(origin) === -1){
var msg = 'The CORS policy for this site does not ';
return callback(new Error(msg), false);
}
return callback(null, true);
}
}));
app.use(
helmet({
frameguard: false,
contentSecurityPolicy: false
})
);
app.use(express.json());
var serverPort = 8085;
var server = http.createServer(app);
const { spawn, exec, execSync } = require('child_process')
var static_options = {
dotfiles: 'ignore',
etag: false,
extensions: ['html'],
index: false,
redirect: false,
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now())
}
}
app.use('/', express.static('client', static_options))
/*
* **********************************************************
* create basic wg file server
* **********************************************************
*/
function wg_save_clientconf(res) {
/*
res.publickey
res.endpoint
res.serverip
res.netmask
res.privatekey
res.allowedips
res.interfaceip
res.endpointfpath
*/
var endpointfpath = `${res.serverip}:${res.endpoint}`
var peerconfig =`
[Interface]
PrivateKey = ${res.privatekey}
ListenPort = 51820
[Peer]
PublicKey = ${res.publickey}
Endpoint = ${endpointfpath}
AllowedIPs = ${res.allowedips}
#AllowedIPs = 10.1.0.0/24, 0.0.0.0/0, ::/0
PersistentKeepalive = 30
`
try {
fs.writeFileSync('./hybrid/connect/wg0.conf', peerconfig);
return 'ok'
} catch (error) {
var datajson = error.toString()
return datajson
}
}
/*
* **********************************************************
* create basic ifup linux
* **********************************************************
*/
function wg_save_ifup_linux(res) {
var mypath = process.cwd()
var DEV_NAME = res.dev_name
var INTERFACE_IP = res.INTERFACE_IP
var INTERFACE_IProute = res.INTERFACE_IProute
/*
res.publickey
res.endpoint
res.serverip
res.netmask
res.privatekey
res.allowedips
res.interfaceip
res.endpointfpath
*/
try {
const myExec = `
ip link set ${DEV_NAME} down
ip link del ${DEV_NAME}
sleep 1
ip link add ${DEV_NAME} type wireguard
wg setconf ${DEV_NAME} /settingsclient/wg0.conf
sleep 1
ip addr add ${INTERFACE_IP} dev ${DEV_NAME}
sysctl -w net.ipv4.conf.all.rp_filter=2
ip link set mtu 1420 up dev ${DEV_NAME}
ip link set up dev ${DEV_NAME}
ip route add default via ${INTERFACE_IProute} metric 2 table 200
ip route show table 200 | grep -w ${INTERFACE_IProute}
ip rule add table main suppress_prefixlength 0
`
fs.writeFileSync('./hybrid/connect/ifup_linux', myExec);
const myExec1 = `
ip link set ${DEV_NAME} down
ip link del ${DEV_NAME}
`
fs.writeFileSync('./hybrid/connect/ifdown_linux', myExec1);
return 'ok'
} catch (error) {
var datajson = error.toString()
return datajson
}
}
/*
* **********************************************************
* create basic run docker
* **********************************************************
*/
function wg_save_connect_linux(res) {
var mypath = process.cwd()
var DEV_NAME = res.dev_name
var INTERFACE_IP = res.INTERFACE_IP
var INTERFACE_IProute = res.INTERFACE_IProute
/*
res.publickey
res.endpoint
res.serverip
res.netmask
res.privatekey
res.allowedips
res.interfaceip
res.endpointfpath
*/
try {
const myExec = `
docker exec -it swarmlabwg /bin/bash -c "ip link set swarmlab0 down; ip link del swarmlab0"
sleep 1
docker stop swarmlabwg; docker container rm swarmlabwg
sleep 1
docker pull hub.swarmlab.io:5480/venusclient:latest
sleep 1
docker run -d \
--net=host \
--name=swarmlabwg \
--cap-add=NET_ADMIN \
--cap-add=SYS_MODULE \
-e PUID=1000 \
-e PGID=1000 \
-e TZ=Europe/Athens \
-p 51820:51820/udp \
-v ${mypath}/hybrid/connect:/settingsclient \
-v /lib/modules:/lib/modules \
--restart unless-stopped \
hub.swarmlab.io:5480/venusclient:latest
`
fs.writeFileSync('./hybrid/connect/swarmlabwg', myExec);
fs.writeFileSync('./hybrid/connect/swarmlabstatus', 'wgstatusclient=off');
const myExec1 = `
docker stop swarmlabwg; docker container rm swarmlabwg
sleep 1
`
fs.writeFileSync('./hybrid/connect/swarmlabwgdown', myExec1);
return 'ok'
} catch (error) {
var datajson = error.toString()
return datajson
}
}
app.post('/hybrid_join_start', (req, res, next) => {
var RES = new Object();
RES.publickey = req.body["publickey"]
RES.endpoint = req.body["endpointport"]
RES.serverip = req.body["serverip"]
RES.netmask = req.body["netmask"]
RES.privatekey = req.body["privatekey"]
RES.allowedips = req.body["allowedips"]
RES.interfaceip = req.body["peer_ip"]
RES.endpointfpath = `${RES.serverip}:${RES.endpoint}`
RES.dev_name = 'swarmlab0'
RES.INTERFACE_IP = `${RES.interfaceip}/${RES.netmask}`
RES.INTERFACE_IProute = `${RES.interfaceip}`
try {
// *****************************************
// *** save wg config file wg0.conf
// *****************************************
RES.serverconf = wg_save_clientconf(RES)
RES.serverrun = wg_save_ifup_linux(RES)
RES.serverconnect = wg_save_connect_linux(RES)
// *****************************************
// *** save wg ifup linux
// *****************************************
RES.error = false
RES.error_msg = "ok"
RES.action = "ok"
console.error('socket get from client' + JSON.stringify(RES))
res.json(RES)
} catch (error) {
var datajson = error.toString()
RES.error = true
RES.error_msg = datajson
RES.action = "no"
res.json(RES)
}
});
app.post('/hybrid_join_connect', (req, res, next) => {
var RES = new Object();
RES.action = req.body["action"]
try {
if(RES.action == "connect"){
fs.writeFileSync('./hybrid/connect/swarmlabstatus', 'wgstatusclient=on');
var showexecrm = `/bin/sh ./hybrid/connect/swarmlabwg`
execSync(showexecrm);
var showexec = `docker ps --format '{"ID":"{{ .ID }}", "Image": "{{ .Image }}", "Names":"{{ .Names }}", "Ports":"{{.Ports}}", "Networks":"{{.Networks}}", "Status":"{{.Status}}","RunningFor":"{{.RunningFor}}","CreatedAt":"{{.CreatedAt}}"}' | jq . -s `
exec(showexec, (err, stdout, stderr) => {
if (err) {
console.error(`exec error: ${err}`);
return;
}
var nn = []
var string = stdout.toString()
var datajson = JSON.parse(string);
var results = []
var filter = "swarmlabwg"
var grep = new RegExp(filter);
var datalenth = datajson.length
for (var i=0 ; i < datalenth ; i++)
{
if(grep.test(datajson[i]['Names'])){
results.push(datajson[i]);
}
}
RES.debug = datajson
if(results){
RES.error = false
RES.error_msg = "ok"
RES.action = "execok"
console.error('socket get from client ' + JSON.stringify(RES))
res.json(RES)
}else{
RES.error = false
RES.error_msg = "ok"
RES.action = "execno"
console.error('socket get from client ' + JSON.stringify(RES))
res.json(RES)
}
});
}else if( RES.action == "disconnect" ){
fs.writeFileSync('./hybrid/connect/swarmlabstatus', 'wgstatusclient=off');
var showexecrm1 = `/bin/sh ./hybrid/connect/swarmlabwgdown`
execSync(showexecrm1);
var showexec = `docker ps --format '{"ID":"{{ .ID }}", "Image": "{{ .Image }}", "Names":"{{ .Names }}", "Ports":"{{.Ports}}", "Networks":"{{.Networks}}", "Status":"{{.Status}}","RunningFor":"{{.RunningFor}}","CreatedAt":"{{.CreatedAt}}"}' | jq . -s `
exec(showexec, (err, stdout, stderr) => {
if (err) {
console.error(`exec error: ${err}`);
return;
}
var nn = []
var string = stdout.toString()
var datajson = JSON.parse(string);
var results = []
var filter = "swarmlabwg"
var grep = new RegExp(filter);
var datalenth = datajson.length
for (var i=0 ; i < datalenth ; i++)
{
if(grep.test(datajson[i]['Names'])){
results.push(datajson[i]);
}
}
RES.debug = datajson
if(results){
RES.error = false
RES.error_msg = "ok"
RES.action = "execok"
console.error('socket get from client ' + JSON.stringify(RES))
res.json(RES)
}else{
RES.error = false
RES.error_msg = "ok"
RES.action = "execno"
console.error('socket get from client ' + JSON.stringify(RES))
res.json(RES)
}
});
}
} catch (error) {
var datajson = error.toString()
RES.error = true
RES.error_msg = datajson
RES.action = "no"
res.json(RES)
}
});
server.listen(serverPort, function() {
console.log('server up and running at %s port', serverPort);
});

11
llo/runconfig.js

@ -0,0 +1,11 @@
var config = {};
config.mongo = {};
config.redis = {};
config.mongo.user = 'user1'
config.mongo.password= 'pass1'
config.redis.host = 'redisserver';
config.redis.port = 6379;
module.exports = config;

11
myconfig/runconfig.js

@ -0,0 +1,11 @@
var config = {};
config.mongo = {};
config.redis = {};
config.mongo.user = 'user1'
config.mongo.password= 'pass1'
config.redis.host = 'redisserver';
config.redis.port = 6379;
module.exports = config;

20
package.json

@ -0,0 +1,20 @@
{
"name": "swarmlab-venus",
"version": "1.0.0",
"description": "swarmlab-venus on node",
"main": "connect-new.js",
"scripts": {
"start": "node ./llo/connect-new.js"
},
"dependencies": {
"async": "^3.2.0",
"bufferutil": "^4.0.2",
"express": "^4.17.1",
"helmet": "^4.1.1",
"pm2": "^4.5.1",
"read-last-lines": "^1.7.2",
"simple-git": "^2.31.0",
"url-exist-sync": "^1.0.2",
"utf-8-validate": "^5.0.3"
}
}

64
start

@ -0,0 +1,64 @@
#!/bin/bash
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
TARGET="$(readlink "$SOURCE")"
if [[ $TARGET == /* ]]; then
#echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"
SOURCE="$TARGET"
else
DIR="$( dirname "$SOURCE" )"
#echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"
SOURCE="$DIR/$TARGET" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
fi
done
SRPATH="$( dirname "$SOURCE" )"
SFPATH="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
if [ "$SFPATH" != "$SRPATH" ]; then
RDIR=$SRPATH # relativ path directory
fi
cwdir=$PWD
wdir=$SFPATH
if [ "$cwdir" != "$wdir" ]; then
cd $wdir
fi
sudo /bin/bash ./hybrid/connect/get-swarmlab-ca > /dev/null 2>&1
sudo /bin/bash ./hybrid/connect/get-base-ca > /dev/null 2>&1
./update-agent.sh
docker pull hub.swarmlab.io:5480/venusclient:latest
pm2 stop venusclient > /dev/null 2>&1
sleep 1
pm2 start ecosystem.config.js --watch --ignore-watch="node_modules" > /dev/null 2>&1
sleep 3
pm2 stop venusclient > /dev/null 2>&1
sleep 3
pm2 start venusclient
txturl='\033[1;36m'
txturl1='\033[0;36m'
txtg='\033[0;32m'
NOCOLOR='\033[0m'
echo -e "$(
cat << EOM
${txtg} DONE build successfully ${NOCOLOR}
App running at:
- Local: ${txturl1} http://localhost:${txturl}8085/index.html
${NOCOLOR}
EOM
)"

4
stop

@ -0,0 +1,4 @@
pm2 stop hybridserver
sleep 1
pm2 status

47
update-agent.sh

@ -0,0 +1,47 @@
#!/bin/bash
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
TARGET="$(readlink "$SOURCE")"
if [[ $TARGET == /* ]]; then
#echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"
SOURCE="$TARGET"
else
DIR="$( dirname "$SOURCE" )"
#echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"
SOURCE="$DIR/$TARGET" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
fi
done
SRPATH="$( dirname "$SOURCE" )"
SFPATH="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
if [ "$SFPATH" != "$SRPATH" ]; then
RDIR=$SRPATH # relativ path directory
fi
cwdir=$PWD
wdir=$SFPATH
if [ "$cwdir" != "$wdir" ]; then
cd $wdir
fi
#echo $cwdir
git fetch
UPSTREAM=${1:-'@{u}'}
LOCAL=$(git rev-parse @)
REMOTE=$(git rev-parse "$UPSTREAM")
BASE=$(git merge-base @ "$UPSTREAM")
if [ $LOCAL = $REMOTE ]; then
echo "Up-to-date"
elif [ $LOCAL = $BASE ]; then
echo "Update swarmlab hybrid ..."
git pull origin
elif [ $REMOTE = $BASE ]; then
echo "Need to push"
else
echo "Diverged"
fi
cd $cwdir
Loading…
Cancel
Save