Repository: paolomainardi/additronk8s-retrogames-kubernetes-controller
Branch: main
Commit: 2709dd2aff4c
Files: 32
Total size: 82.7 KB
Directory structure:
gitextract_hq6e478a/
├── .github/
│ └── workflows/
│ ├── build-controller.yaml
│ └── build-engine.yml
├── .gitignore
├── LICENSE
├── Makefile
├── README.md
├── game-engine/
│ ├── .dockerignore
│ ├── Dockerfile
│ ├── conf/
│ │ ├── client.conf
│ │ ├── default.pa
│ │ ├── dosbox/
│ │ │ ├── dosbox.cli.conf.template
│ │ │ └── dosbox.conf.template
│ │ ├── novnc/
│ │ │ ├── background_patch.diff
│ │ │ └── vnc_lite.html
│ │ ├── supervisord.conf
│ │ └── webaudio.js
│ ├── entrypoint.sh
│ └── run.sh
├── k8s/
│ ├── manifests/
│ │ ├── crd-game-controller.yml
│ │ ├── game-controller-cluster-role-binding.yml
│ │ ├── game-controller-cluster-role.yml
│ │ ├── game-controller-sa.yml
│ │ ├── game-controller.yaml
│ │ └── namespace.yml
│ └── src/
│ └── game-controller/
│ ├── Dockerfile
│ ├── index.js
│ ├── lib/
│ │ ├── api-machinery.js
│ │ ├── crd-informer.js
│ │ ├── game-engine.js
│ │ └── util.js
│ └── package.json
└── skaffold.yml
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/workflows/build-controller.yaml
================================================
name: build-controller
on:
pull_request:
branches: main
push:
branches: main
tags:
- v*
jobs:
buildx:
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v2
-
name: Prepare
id: prepare
run: |
DOCKER_IMAGE=ghcr.io/paolomainardi/additronk8s-game-controller
DOCKER_PLATFORMS=linux/amd64,linux/arm/v7,linux/arm64
DOCKERFILE_PATH=./k8s/src/game-controller
VERSION=latest
if [[ $GITHUB_REF == refs/tags/* ]]; then
VERSION=${GITHUB_REF#refs/tags/v}
fi
if [ "${{ github.event_name }}" = "schedule" ]; then
VERSION=nightly
fi
TAGS="--tag ${DOCKER_IMAGE}:${VERSION}"
if [[ $VERSION =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
TAGS="$TAGS --tag ${DOCKER_IMAGE}:latest"
fi
echo ::set-output name=docker_image::${DOCKER_IMAGE}
echo ::set-output name=version::${VERSION}
echo ::set-output name=buildx_args::--platform ${DOCKER_PLATFORMS} \
--build-arg VERSION=${VERSION} \
--build-arg BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ') \
--build-arg VCS_REF=${GITHUB_SHA::8} \
${TAGS} --file ${DOCKERFILE_PATH}/Dockerfile ${DOCKERFILE_PATH}
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Docker Buildx (build)
run: |
docker buildx build --output "type=image,push=false" ${{ steps.prepare.outputs.buildx_args }}
- name: Log into GitHub Container Registry
run: echo "${{ secrets.GITHUB_TOKEN }}" | docker login https://ghcr.io -u ${{ github.actor }} --password-stdin
- name: Docker Buildx (push)
if: success() && github.event_name != 'pull_request'
run: |
docker buildx build --output "type=image,push=true" ${{ steps.prepare.outputs.buildx_args }}
- name: Inspect image
if: always() && github.event_name != 'pull_request'
run: |
docker buildx imagetools inspect ${{ steps.prepare.outputs.docker_image }}:${{ steps.prepare.outputs.version }}
================================================
FILE: .github/workflows/build-engine.yml
================================================
name: build-engine
on:
pull_request:
branches: main
push:
branches: main
tags:
- v*
jobs:
buildx:
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v2
-
name: Prepare
id: prepare
run: |
DOCKER_IMAGE=ghcr.io/paolomainardi/additronk8s-game-engine
DOCKER_PLATFORMS=linux/amd64,linux/arm/v7,linux/arm64
DOCKERFILE_PATH=./game-engine
VERSION=latest
if [[ $GITHUB_REF == refs/tags/* ]]; then
VERSION=${GITHUB_REF#refs/tags/v}
fi
if [ "${{ github.event_name }}" = "schedule" ]; then
VERSION=nightly
fi
TAGS="--tag ${DOCKER_IMAGE}:${VERSION}"
if [[ $VERSION =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
TAGS="$TAGS --tag ${DOCKER_IMAGE}:latest"
fi
echo ::set-output name=docker_image::${DOCKER_IMAGE}
echo ::set-output name=version::${VERSION}
echo ::set-output name=buildx_args::--platform ${DOCKER_PLATFORMS} \
--build-arg VERSION=${VERSION} \
--build-arg BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ') \
--build-arg VCS_REF=${GITHUB_SHA::8} \
${TAGS} --file ${DOCKERFILE_PATH}/Dockerfile ${DOCKERFILE_PATH}
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Docker Buildx (build)
run: |
docker buildx build --output "type=image,push=false" ${{ steps.prepare.outputs.buildx_args }}
- name: Log into GitHub Container Registry
run: echo "${{ secrets.GITHUB_TOKEN }}" | docker login https://ghcr.io -u ${{ github.actor }} --password-stdin
- name: Docker Buildx (push)
if: success() && github.event_name != 'pull_request'
run: |
docker buildx build --output "type=image,push=true" ${{ steps.prepare.outputs.buildx_args }}
- name: Inspect image
if: always() && github.event_name != 'pull_request'
run: |
docker buildx imagetools inspect ${{ steps.prepare.outputs.docker_image }}:${{ steps.prepare.outputs.version }}
================================================
FILE: .gitignore
================================================
games
node_modules
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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
http://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.
================================================
FILE: Makefile
================================================
all: run
SHELL := /bin/bash
ifndef GAME_DIR
GAME_DIR=MONKEY_FLOPPY
endif
ifndef GAME_EXE
GAME_EXE=MONEY.EXE
endif
build-game-engine:
docker build -t ghcr.io/paolomainardi/additronk8s-game-engine:latest game-engine
kind-load-game-engine: build-game-engine
kind load docker-image ghcr.io/paolomainardi/additronk8s-game-engine:latest --name retrogames-k8s-dev
run-game-engine: build
./game-engine/run.sh
run: create-kind-cluster kind-load-game-engine
skaffold run -n games --tail
dev: kind-load-game-engine
skaffold dev -n games --tail
create-kind-cluster:
kind delete cluster --name retrogames-k8s-dev || true
kind create cluster --name retrogames-k8s-dev
================================================
FILE: README.md
================================================
# AdditronK8S
[](https://github.com/paolomainardi/additronk8s-retrogames-kubernetes-controller/actions/workflows/build-controller.yaml) [](https://github.com/paolomainardi/additronk8s-retrogames-kubernetes-controller/actions/workflows/build-engine.yml)
## Description
AdditronK8S is a retro game machine build as a Kubernetes custom controller and
implemented in Javascript.
> The name `Additron` is a tribute to the great inventor and scientist [Josef Kates](https://en.wikipedia.org/wiki/Josef_Kates) who invented the [**first digital playing machine**](https://en.wikipedia.org/wiki/Bertie_the_Brain) to showcase his Additron tube invention.
I did this as a PoC [for a company talk](https://www2.slideshare.net/sparkfabrik/retro-gaming-machine-made-with-javascript-and-kubernetes) [(Video)](https://youtu.be/XlhSCWzgQ4k), to demonstrate how **powerful** can be the
**Kubernetes APIs** when used also to build custom applications.
I chose to use **Javascript** as it is an **officially supported client**
and also because I didn't find any project a bit more complex than a simple hello world, to implement a custom controller.
> Personal note: When developing for Kubernetes, you have to deal with tons of REST APIs and complex relationship between them, this is where the GO
ecosystem shines, you have framework and abstractions used to build Kubernetes
itself and you are sure to use top-notch quality code; so if you plan
to implement something serious with Kubernetes, my advice is to use GO as
a first class citizen language of your system.
One of the goal of this project was to use just **Kubernetes API without any external dependency** (neither the storage),
infact is noteworthy that `Configmaps` are (ab)used as a persistent storage layer, using a simple technique
of split/merge parts of files to save the games.
How it works (hand written schematic):

See it in action:
[](https://asciinema.org/a/yuUCC0i5BizfRPYoSBcGAP4Sc)
Here you can find the slides of my talk: https://www2.slideshare.net/sparkfabrik/retro-gaming-machine-made-with-javascript-and-kubernetes
## Technology
This project consists of 3 main components:
1. A Docker image to run games based on Dosbox + [noVNC + Pulseaudio/gStreamer](https://github.com/novnc/noVNC/issues/302)
2. A Javascript Kubernetes custom controller who implements the CRD and the needed logic to run the games.
3. A K3d Kubernetes cluster and Skaffold to manage it.
> WARNING: The code is not even close to be production ready, it is just a quick PoC to build a custom controller in Javascript.
## Quick start
You just need a working k8s cluster, with a working external connection.
To install it from the root, run the following commands:
```shell
kubectl apply -f k8s/manifests/namespace.yml
kubectl -n games apply -f k8s/manifests/crd-game-controller.yml
kubectl -n games apply -f k8s/manifests/game-controller-sa.yml
kubectl -n games apply -f k8s/manifests/game-controller-cluster-role.yml
kubectl -n games apply -f k8s/manifests/game-controller-cluster-role-binding.yml
kubectl -n games apply -f k8s/manifests/game-controller.yaml
```
Now you can run a demo game to test if everything is working as expected:
```shell
kubectl -n games apply -f k8s/games/quake.yml
```
> You can also tail the logs of the game-controller to ensure that it was successful
> in processing the location of your game zip file.
> ```shell
> kubectl -n games logs deployment/game-controller -f
> ```
Once you have the game up and running, you can access via the web browser by proxying
the game service, like this:
```
kubectl -n games port-forward svc/quake 8080:8080 8081:8081
```
Finally you can access the game console on: `https://localhost:8080`
At this stage you will be presented with the dosbox command line and
the command to run to execute the game.
> *IMPORTANT*: To start the audio websocket, before to start the game and inside the
> dosbox cli, you have to press `ALT + s` this will start once the needed websocket,
> to transport the audio from the pulseaudio server to your browser.
## Games
Files can be downloaded from any public http endpoint or from any public GCP cloud storage bucket.
The expect manifest to run a game is this:
```yaml
apiVersion: retro.sparkfabrik.com/v1
kind: Game
metadata:
name: game-name
spec:
name: "Game name human friendly"
zipUrl: "gs://my-gs-bucket/game.zip"
dir: "GAME"
exe: "GAME.EXE"
```
Where `dir` represent the directory of the unzipped game and `exe` the binary to run.
To be clear, this is a structure we expect:
```
unzip game.zip
> GAME
- GAME.EXE
- SOUND.MOD
- VIDEO.MOD
```
### Development
The development environment is based on `k3d` and `skaffold`,
by running `make dev` you will have end up with:
1. A k3d kubernetes cluster
2. Docker images loaded into the k3d cluster
3. Game controller up and running with live-reload in case of code changes
## References
* [Retro DOS Games on Kubernetes:](https://www.virtuallyghetto.com/2021/02/retro-dos-games-on-kubernetes.html) many thanks to [William Lam](https://twitter.com/lamw) for this great write-up.
================================================
FILE: game-engine/.dockerignore
================================================
games
================================================
FILE: game-engine/Dockerfile
================================================
FROM debian:10.7
ENV LANG=en_US.UTF-8 LANGUAGE=en_US.UTF-8 LC_ALL=C.UTF-8 DISPLAY=:0.0
# Install dependencies.
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install --yes --no-install-recommends \
bzip2 \
gstreamer1.0-plugins-good \
gstreamer1.0-pulseaudio \
gstreamer1.0-tools \
libglu1-mesa \
libgtk2.0-0 \
libncursesw5 \
libopenal1 \
libsdl-image1.2 \
libsdl-ttf2.0-0 \
libsdl1.2debian \
libsndfile1 \
novnc \
pulseaudio \
supervisor \
ucspi-tcp \
wget \
x11vnc \
xvfb \
dosbox \
procps \
gettext-base \
unzip \
patch \
&& rm -rf /var/lib/apt/lists/*
# Configure pulseaudio.
COPY conf/default.pa conf/client.conf /etc/pulse/
# Force vnc_lite.html to be used for novnc, to avoid having the directory listing page.
# Additionally, turn off the control bar. Finally, add a hook to start audio.
COPY conf/webaudio.js /usr/share/novnc/core/
COPY conf/novnc/vnc_lite.html /usr/share/novnc/vnc_lite.html
RUN ln -s /usr/share/novnc/vnc_lite.html /usr/share/novnc/index.html
# Add a patch to make the background customizable.
COPY conf/novnc/background_patch.diff /usr/share/novnc
RUN cd /usr/share/novnc && \
patch -p1 < background_patch.diff
# Configure supervisord.
COPY conf/supervisord.conf /etc/supervisor/supervisord.conf
# Run everything as standard user/group retrogames.
RUN groupadd retrogames \
&& useradd --create-home --gid retrogames retrogames
WORKDIR /home/retrogames
# Copy dosbox custom confs.
COPY conf/dosbox /dosbox/
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
# Copy games.
RUN mkdir /games && chown -R retrogames:retrogames /games
USER retrogames
#COPY --chown=retrogames:retrogames games /games
HEALTHCHECK CMD ps aux | grep dosbox | grep -v grep || exit 1
ENTRYPOINT [ "supervisord", "-c", "/etc/supervisor/supervisord.conf" ]
================================================
FILE: game-engine/conf/client.conf
================================================
default-server=unix:/tmp/pulseaudio.socket
================================================
FILE: game-engine/conf/default.pa
================================================
#!/usr/bin/pulseaudio -nF
load-module module-native-protocol-unix socket=/tmp/pulseaudio.socket auth-anonymous=1
load-module module-always-sink
================================================
FILE: game-engine/conf/dosbox/dosbox.cli.conf.template
================================================
set border 0
exec dosbox -conf ~/.dosbox/dosbox.conf -fullscreen
root@9fb8fc07e1da:~# cat .dosbox/dosbox.conf
# This is the configurationfile for DOSBox 0.74. (Please use the latest version of DOSBox)
# Lines starting with a # are commentlines and are ignored by DOSBox.
# They are used to (briefly) document the effect of each option.
[sdl]
# fullscreen: Start dosbox directly in fullscreen. (Press ALT-Enter to go back)
# fulldouble: Use double buffering in fullscreen. It can reduce screen flickering, but it can also result in a slow DOSBox.
# fullresolution: What resolution to use for fullscreen: original or fixed size (e.g. 1024x768).
# Using your monitor's native resolution with aspect=true might give the best results.
# If you end up with small window on a large screen, try an output different from surface.
# windowresolution: Scale the window to this size IF the output device supports hardware scaling.
# (output=surface does not!)
# output: What video system to use for output.
# Possible values: surface, overlay, opengl, openglnb.
# autolock: Mouse will automatically lock, if you click on the screen. (Press CTRL-F10 to unlock)
# sensitivity: Mouse sensitivity.
# waitonerror: Wait before closing the console if dosbox has an error.
# priority: Priority levels for dosbox. Second entry behind the comma is for when dosbox is not focused/minimized.
# pause is only valid for the second entry.
# Possible values: lowest, lower, normal, higher, highest, pause.
# mapperfile: File used to load/save the key/event mappings from. Resetmapper only works with the defaul value.
# usescancodes: Avoid usage of symkeys, might not work on all operating systems.
fullscreen=true
fulldouble=false
fullresolution=0x0
windowresolution=0x0
output=opengl
autolock=true
sensitivity=100
waitonerror=true
priority=higher,normal
mapperfile=mapper-0.74.map
usescancodes=false
[dosbox]
# language: Select another language file.
# machine: The type of machine tries to emulate.
# Possible values: hercules, cga, tandy, pcjr, ega, vgaonly, svga_s3, svga_et3000, svga_et4000, svga_paradise, vesa_nolfb, vesa_oldvbe.
# captures: Directory where things like wave, midi, screenshot get captured.
# memsize: Amount of memory DOSBox has in megabytes.
# This value is best left at its default to avoid problems with some games,
# though few games might require a higher value.
# There is generally no speed advantage when raising this value.
language=
machine=svga_s3
captures=capture
memsize=16
[render]
# frameskip: How many frames DOSBox skips before drawing one.
# aspect: Do aspect correction, if your output method doesn't support scaling this can slow things down!.
# scaler: Scaler used to enlarge/enhance low resolution modes.
# If 'forced' is appended, then the scaler will be used even if the result might not be desired.
# Possible values: none, normal2x, normal3x, advmame2x, advmame3x, advinterp2x, advinterp3x, hq2x, hq3x, 2xsai, super2xsai, supereagle, tv2x, tv3x, rgb2x, rgb3x, scan2x, scan3x.
frameskip=0
aspect=false
scaler=none
[cpu]
# core: CPU Core used in emulation. auto will switch to dynamic if available and appropriate.
# Possible values: auto, dynamic, normal, simple.
# cputype: CPU Type used in emulation. auto is the fastest choice.
# Possible values: auto, 386, 386_slow, 486_slow, pentium_slow, 386_prefetch.
# cycles: Amount of instructions DOSBox tries to emulate each millisecond.
# Setting this value too high results in sound dropouts and lags.
# Cycles can be set in 3 ways:
# 'auto' tries to guess what a game needs.
# It usually works, but can fail for certain games.
# 'fixed #number' will set a fixed amount of cycles. This is what you usually need if 'auto' fails.
# (Example: fixed 4000).
# 'max' will allocate as much cycles as your computer is able to handle.
#
# Possible values: auto, fixed, max.
# cycleup: Amount of cycles to decrease/increase with keycombo.(CTRL-F11/CTRL-F12)
# cycledown: Setting it lower than 100 will be a percentage.
core=auto
cputype=auto
cycles=auto
cycleup=10
cycledown=20
[mixer]
# nosound: Enable silent mode, sound is still emulated though.
# rate: Mixer sample rate, setting any device's rate higher than this will probably lower their sound quality.
# Possible values: 44100, 48000, 32000, 22050, 16000, 11025, 8000, 49716.
# blocksize: Mixer block size, larger blocks might help sound stuttering but sound will also be more lagged.
# Possible values: 1024, 2048, 4096, 8192, 512, 256.
# prebuffer: How many milliseconds of data to keep on top of the blocksize.
nosound=false
rate=44100
blocksize=1024
prebuffer=20
[midi]
# mpu401: Type of MPU-401 to emulate.
# Possible values: intelligent, uart, none.
# mididevice: Device that will receive the MIDI data from MPU-401.
# Possible values: default, win32, alsa, oss, coreaudio, coremidi, none.
# midiconfig: Special configuration options for the device driver. This is usually the id of the device you want to use.
# See the README/Manual for more details.
mpu401=intelligent
mididevice=default
midiconfig=
[sblaster]
# sbtype: Type of Soundblaster to emulate. gb is Gameblaster.
# Possible values: sb1, sb2, sbpro1, sbpro2, sb16, gb, none.
# sbbase: The IO address of the soundblaster.
# Possible values: 220, 240, 260, 280, 2a0, 2c0, 2e0, 300.
# irq: The IRQ number of the soundblaster.
# Possible values: 7, 5, 3, 9, 10, 11, 12.
# dma: The DMA number of the soundblaster.
# Possible values: 1, 5, 0, 3, 6, 7.
# hdma: The High DMA number of the soundblaster.
# Possible values: 1, 5, 0, 3, 6, 7.
# sbmixer: Allow the soundblaster mixer to modify the DOSBox mixer.
# oplmode: Type of OPL emulation. On 'auto' the mode is determined by sblaster type. All OPL modes are Adlib-compatible, except for 'cms'.
# Possible values: auto, cms, opl2, dualopl2, opl3, none.
# oplemu: Provider for the OPL emulation. compat might provide better quality (see oplrate as well).
# Possible values: default, compat, fast.
# oplrate: Sample rate of OPL music emulation. Use 49716 for highest quality (set the mixer rate accordingly).
# Possible values: 44100, 49716, 48000, 32000, 22050, 16000, 11025, 8000.
sbtype=sb16
sbbase=220
irq=7
dma=1
hdma=5
sbmixer=true
oplmode=auto
oplemu=default
oplrate=44100
[gus]
# gus: Enable the Gravis Ultrasound emulation.
# gusrate: Sample rate of Ultrasound emulation.
# Possible values: 44100, 48000, 32000, 22050, 16000, 11025, 8000, 49716.
# gusbase: The IO base address of the Gravis Ultrasound.
# Possible values: 240, 220, 260, 280, 2a0, 2c0, 2e0, 300.
# gusirq: The IRQ number of the Gravis Ultrasound.
# Possible values: 5, 3, 7, 9, 10, 11, 12.
# gusdma: The DMA channel of the Gravis Ultrasound.
# Possible values: 3, 0, 1, 5, 6, 7.
# ultradir: Path to Ultrasound directory. In this directory
# there should be a MIDI directory that contains
# the patch files for GUS playback. Patch sets used
# with Timidity should work fine.
gus=false
gusrate=44100
gusbase=240
gusirq=5
gusdma=3
ultradir=C:\ULTRASND
[speaker]
# pcspeaker: Enable PC-Speaker emulation.
# pcrate: Sample rate of the PC-Speaker sound generation.
# Possible values: 44100, 48000, 32000, 22050, 16000, 11025, 8000, 49716.
# tandy: Enable Tandy Sound System emulation. For 'auto', emulation is present only if machine is set to 'tandy'.
# Possible values: auto, on, off.
# tandyrate: Sample rate of the Tandy 3-Voice generation.
# Possible values: 44100, 48000, 32000, 22050, 16000, 11025, 8000, 49716.
# disney: Enable Disney Sound Source emulation. (Covox Voice Master and Speech Thing compatible).
pcspeaker=true
pcrate=44100
tandy=auto
tandyrate=44100
disney=true
[joystick]
# joysticktype: Type of joystick to emulate: auto (default), none,
# 2axis (supports two joysticks),
# 4axis (supports one joystick, first joystick used),
# 4axis_2 (supports one joystick, second joystick used),
# fcs (Thrustmaster), ch (CH Flightstick).
# none disables joystick emulation.
# auto chooses emulation depending on real joystick(s).
# (Remember to reset dosbox's mapperfile if you saved it earlier)
# Possible values: auto, 2axis, 4axis, 4axis_2, fcs, ch, none.
# timed: enable timed intervals for axis. Experiment with this option, if your joystick drifts (away).
# autofire: continuously fires as long as you keep the button pressed.
# swap34: swap the 3rd and the 4th axis. can be useful for certain joysticks.
# buttonwrap: enable button wrapping at the number of emulated buttons.
joysticktype=auto
timed=true
autofire=false
swap34=false
buttonwrap=false
[serial]
# serial1: set type of device connected to com port.
# Can be disabled, dummy, modem, nullmodem, directserial.
# Additional parameters must be in the same line in the form of
# parameter:value. Parameter for all types is irq (optional).
# for directserial: realport (required), rxdelay (optional).
# (realport:COM1 realport:ttyS0).
# for modem: listenport (optional).
# for nullmodem: server, rxdelay, txdelay, telnet, usedtr,
# transparent, port, inhsocket (all optional).
# Example: serial1=modem listenport:5000
# Possible values: dummy, disabled, modem, nullmodem, directserial.
# serial2: see serial1
# Possible values: dummy, disabled, modem, nullmodem, directserial.
# serial3: see serial1
# Possible values: dummy, disabled, modem, nullmodem, directserial.
# serial4: see serial1
# Possible values: dummy, disabled, modem, nullmodem, directserial.
serial1=dummy
serial2=dummy
serial3=disabled
serial4=disabled
[dos]
# xms: Enable XMS support.
# ems: Enable EMS support.
# umb: Enable UMB support.
# keyboardlayout: Language code of the keyboard layout (or none).
xms=true
ems=false
umb=true
keyboardlayout=auto
[ipx]
# ipx: Enable ipx over UDP/IP emulation.
ipx=false
[autoexec]
# Lines in this section will be run at startup.
# You can put your MOUNT lines here.
MOUNT C: /games
C:
================================================
FILE: game-engine/conf/dosbox/dosbox.conf.template
================================================
set border 0
exec dosbox -conf ~/.dosbox/dosbox.conf -fullscreen
root@9fb8fc07e1da:~# cat .dosbox/dosbox.conf
# This is the configurationfile for DOSBox 0.74. (Please use the latest version of DOSBox)
# Lines starting with a # are commentlines and are ignored by DOSBox.
# They are used to (briefly) document the effect of each option.
[sdl]
# fullscreen: Start dosbox directly in fullscreen. (Press ALT-Enter to go back)
# fulldouble: Use double buffering in fullscreen. It can reduce screen flickering, but it can also result in a slow DOSBox.
# fullresolution: What resolution to use for fullscreen: original or fixed size (e.g. 1024x768).
# Using your monitor's native resolution with aspect=true might give the best results.
# If you end up with small window on a large screen, try an output different from surface.
# windowresolution: Scale the window to this size IF the output device supports hardware scaling.
# (output=surface does not!)
# output: What video system to use for output.
# Possible values: surface, overlay, opengl, openglnb.
# autolock: Mouse will automatically lock, if you click on the screen. (Press CTRL-F10 to unlock)
# sensitivity: Mouse sensitivity.
# waitonerror: Wait before closing the console if dosbox has an error.
# priority: Priority levels for dosbox. Second entry behind the comma is for when dosbox is not focused/minimized.
# pause is only valid for the second entry.
# Possible values: lowest, lower, normal, higher, highest, pause.
# mapperfile: File used to load/save the key/event mappings from. Resetmapper only works with the defaul value.
# usescancodes: Avoid usage of symkeys, might not work on all operating systems.
fullscreen=true
fulldouble=false
fullresolution=0x0
windowresolution=0x0
output=opengl
autolock=true
sensitivity=100
waitonerror=true
priority=higher,normal
mapperfile=mapper-0.74.map
usescancodes=false
[dosbox]
# language: Select another language file.
# machine: The type of machine tries to emulate.
# Possible values: hercules, cga, tandy, pcjr, ega, vgaonly, svga_s3, svga_et3000, svga_et4000, svga_paradise, vesa_nolfb, vesa_oldvbe.
# captures: Directory where things like wave, midi, screenshot get captured.
# memsize: Amount of memory DOSBox has in megabytes.
# This value is best left at its default to avoid problems with some games,
# though few games might require a higher value.
# There is generally no speed advantage when raising this value.
language=
machine=svga_s3
captures=capture
memsize=16
[render]
# frameskip: How many frames DOSBox skips before drawing one.
# aspect: Do aspect correction, if your output method doesn't support scaling this can slow things down!.
# scaler: Scaler used to enlarge/enhance low resolution modes.
# If 'forced' is appended, then the scaler will be used even if the result might not be desired.
# Possible values: none, normal2x, normal3x, advmame2x, advmame3x, advinterp2x, advinterp3x, hq2x, hq3x, 2xsai, super2xsai, supereagle, tv2x, tv3x, rgb2x, rgb3x, scan2x, scan3x.
frameskip=0
aspect=false
scaler=none
[cpu]
# core: CPU Core used in emulation. auto will switch to dynamic if available and appropriate.
# Possible values: auto, dynamic, normal, simple.
# cputype: CPU Type used in emulation. auto is the fastest choice.
# Possible values: auto, 386, 386_slow, 486_slow, pentium_slow, 386_prefetch.
# cycles: Amount of instructions DOSBox tries to emulate each millisecond.
# Setting this value too high results in sound dropouts and lags.
# Cycles can be set in 3 ways:
# 'auto' tries to guess what a game needs.
# It usually works, but can fail for certain games.
# 'fixed #number' will set a fixed amount of cycles. This is what you usually need if 'auto' fails.
# (Example: fixed 4000).
# 'max' will allocate as much cycles as your computer is able to handle.
#
# Possible values: auto, fixed, max.
# cycleup: Amount of cycles to decrease/increase with keycombo.(CTRL-F11/CTRL-F12)
# cycledown: Setting it lower than 100 will be a percentage.
core=auto
cputype=auto
cycles=auto
cycleup=10
cycledown=20
[mixer]
# nosound: Enable silent mode, sound is still emulated though.
# rate: Mixer sample rate, setting any device's rate higher than this will probably lower their sound quality.
# Possible values: 44100, 48000, 32000, 22050, 16000, 11025, 8000, 49716.
# blocksize: Mixer block size, larger blocks might help sound stuttering but sound will also be more lagged.
# Possible values: 1024, 2048, 4096, 8192, 512, 256.
# prebuffer: How many milliseconds of data to keep on top of the blocksize.
nosound=false
rate=44100
blocksize=1024
prebuffer=20
[midi]
# mpu401: Type of MPU-401 to emulate.
# Possible values: intelligent, uart, none.
# mididevice: Device that will receive the MIDI data from MPU-401.
# Possible values: default, win32, alsa, oss, coreaudio, coremidi, none.
# midiconfig: Special configuration options for the device driver. This is usually the id of the device you want to use.
# See the README/Manual for more details.
mpu401=intelligent
mididevice=default
midiconfig=
[sblaster]
# sbtype: Type of Soundblaster to emulate. gb is Gameblaster.
# Possible values: sb1, sb2, sbpro1, sbpro2, sb16, gb, none.
# sbbase: The IO address of the soundblaster.
# Possible values: 220, 240, 260, 280, 2a0, 2c0, 2e0, 300.
# irq: The IRQ number of the soundblaster.
# Possible values: 7, 5, 3, 9, 10, 11, 12.
# dma: The DMA number of the soundblaster.
# Possible values: 1, 5, 0, 3, 6, 7.
# hdma: The High DMA number of the soundblaster.
# Possible values: 1, 5, 0, 3, 6, 7.
# sbmixer: Allow the soundblaster mixer to modify the DOSBox mixer.
# oplmode: Type of OPL emulation. On 'auto' the mode is determined by sblaster type. All OPL modes are Adlib-compatible, except for 'cms'.
# Possible values: auto, cms, opl2, dualopl2, opl3, none.
# oplemu: Provider for the OPL emulation. compat might provide better quality (see oplrate as well).
# Possible values: default, compat, fast.
# oplrate: Sample rate of OPL music emulation. Use 49716 for highest quality (set the mixer rate accordingly).
# Possible values: 44100, 49716, 48000, 32000, 22050, 16000, 11025, 8000.
sbtype=sb16
sbbase=220
irq=7
dma=1
hdma=5
sbmixer=true
oplmode=auto
oplemu=default
oplrate=44100
[gus]
# gus: Enable the Gravis Ultrasound emulation.
# gusrate: Sample rate of Ultrasound emulation.
# Possible values: 44100, 48000, 32000, 22050, 16000, 11025, 8000, 49716.
# gusbase: The IO base address of the Gravis Ultrasound.
# Possible values: 240, 220, 260, 280, 2a0, 2c0, 2e0, 300.
# gusirq: The IRQ number of the Gravis Ultrasound.
# Possible values: 5, 3, 7, 9, 10, 11, 12.
# gusdma: The DMA channel of the Gravis Ultrasound.
# Possible values: 3, 0, 1, 5, 6, 7.
# ultradir: Path to Ultrasound directory. In this directory
# there should be a MIDI directory that contains
# the patch files for GUS playback. Patch sets used
# with Timidity should work fine.
gus=false
gusrate=44100
gusbase=240
gusirq=5
gusdma=3
ultradir=C:\ULTRASND
[speaker]
# pcspeaker: Enable PC-Speaker emulation.
# pcrate: Sample rate of the PC-Speaker sound generation.
# Possible values: 44100, 48000, 32000, 22050, 16000, 11025, 8000, 49716.
# tandy: Enable Tandy Sound System emulation. For 'auto', emulation is present only if machine is set to 'tandy'.
# Possible values: auto, on, off.
# tandyrate: Sample rate of the Tandy 3-Voice generation.
# Possible values: 44100, 48000, 32000, 22050, 16000, 11025, 8000, 49716.
# disney: Enable Disney Sound Source emulation. (Covox Voice Master and Speech Thing compatible).
pcspeaker=true
pcrate=44100
tandy=auto
tandyrate=44100
disney=true
[joystick]
# joysticktype: Type of joystick to emulate: auto (default), none,
# 2axis (supports two joysticks),
# 4axis (supports one joystick, first joystick used),
# 4axis_2 (supports one joystick, second joystick used),
# fcs (Thrustmaster), ch (CH Flightstick).
# none disables joystick emulation.
# auto chooses emulation depending on real joystick(s).
# (Remember to reset dosbox's mapperfile if you saved it earlier)
# Possible values: auto, 2axis, 4axis, 4axis_2, fcs, ch, none.
# timed: enable timed intervals for axis. Experiment with this option, if your joystick drifts (away).
# autofire: continuously fires as long as you keep the button pressed.
# swap34: swap the 3rd and the 4th axis. can be useful for certain joysticks.
# buttonwrap: enable button wrapping at the number of emulated buttons.
joysticktype=auto
timed=true
autofire=false
swap34=false
buttonwrap=false
[serial]
# serial1: set type of device connected to com port.
# Can be disabled, dummy, modem, nullmodem, directserial.
# Additional parameters must be in the same line in the form of
# parameter:value. Parameter for all types is irq (optional).
# for directserial: realport (required), rxdelay (optional).
# (realport:COM1 realport:ttyS0).
# for modem: listenport (optional).
# for nullmodem: server, rxdelay, txdelay, telnet, usedtr,
# transparent, port, inhsocket (all optional).
# Example: serial1=modem listenport:5000
# Possible values: dummy, disabled, modem, nullmodem, directserial.
# serial2: see serial1
# Possible values: dummy, disabled, modem, nullmodem, directserial.
# serial3: see serial1
# Possible values: dummy, disabled, modem, nullmodem, directserial.
# serial4: see serial1
# Possible values: dummy, disabled, modem, nullmodem, directserial.
serial1=dummy
serial2=dummy
serial3=disabled
serial4=disabled
[dos]
# xms: Enable XMS support.
# ems: Enable EMS support.
# umb: Enable UMB support.
# keyboardlayout: Language code of the keyboard layout (or none).
xms=true
ems=false
umb=true
keyboardlayout=auto
[ipx]
# ipx: Enable ipx over UDP/IP emulation.
ipx=false
[autoexec]
# Lines in this section will be run at startup.
# You can put your MOUNT lines here.
@ECHO OFF
MOUNT C: /games
C:
CD ${GAME_DIR}
echo "To run this game just type: ${GAME_EXE} + enter"
================================================
FILE: game-engine/conf/novnc/background_patch.diff
================================================
diff --git a/core/rfb.js b/core/rfb.js
index 7c4e0c9..7217e7c 100644
--- a/core/rfb.js
+++ b/core/rfb.js
@@ -152,7 +152,7 @@ export default function RFB(target, url, options) {
this._screen.style.width = '100%';
this._screen.style.height = '100%';
this._screen.style.overflow = 'auto';
- this._screen.style.backgroundColor = 'rgb(40, 40, 40)';
+ this._screen.style.backgroundColor = 'black';
this._canvas = document.createElement('canvas');
this._canvas.style.margin = 'auto';
// Some browsers add an outline on focus
================================================
FILE: game-engine/conf/novnc/vnc_lite.html
================================================
<!DOCTYPE html>
<html>
<head>
<!--
noVNC example: lightweight example using minimal UI and features
Copyright (C) 2012 Joel Martin
Copyright (C) 2017 Samuel Mannehed for Cendio AB
noVNC is licensed under the MPL 2.0 (see LICENSE.txt)
This file is licensed under the 2-Clause BSD license (see LICENSE.txt).
Connect parameters are provided in query string:
http://example.com/?host=HOST&port=PORT&encrypt=1
or the fragment:
http://example.com/#host=HOST&port=PORT&encrypt=1
-->
<title>noVNC</title>
<meta charset="utf-8">
<!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame
Remove this if you use the .htaccess -->
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<!-- Icons (see Makefile for what the sizes are for) -->
<link rel="icon" sizes="16x16" type="image/png" href="app/images/icons/novnc-16x16.png">
<link rel="icon" sizes="24x24" type="image/png" href="app/images/icons/novnc-24x24.png">
<link rel="icon" sizes="32x32" type="image/png" href="app/images/icons/novnc-32x32.png">
<link rel="icon" sizes="48x48" type="image/png" href="app/images/icons/novnc-48x48.png">
<link rel="icon" sizes="60x60" type="image/png" href="app/images/icons/novnc-60x60.png">
<link rel="icon" sizes="64x64" type="image/png" href="app/images/icons/novnc-64x64.png">
<link rel="icon" sizes="72x72" type="image/png" href="app/images/icons/novnc-72x72.png">
<link rel="icon" sizes="76x76" type="image/png" href="app/images/icons/novnc-76x76.png">
<link rel="icon" sizes="96x96" type="image/png" href="app/images/icons/novnc-96x96.png">
<link rel="icon" sizes="120x120" type="image/png" href="app/images/icons/novnc-120x120.png">
<link rel="icon" sizes="144x144" type="image/png" href="app/images/icons/novnc-144x144.png">
<link rel="icon" sizes="152x152" type="image/png" href="app/images/icons/novnc-152x152.png">
<link rel="icon" sizes="192x192" type="image/png" href="app/images/icons/novnc-192x192.png">
<!-- Firefox currently mishandles SVG, see #1419039
<link rel="icon" sizes="any" type="image/svg+xml" href="app/images/icons/novnc-icon.svg">
-->
<!-- Repeated last so that legacy handling will pick this -->
<link rel="icon" sizes="16x16" type="image/png" href="app/images/icons/novnc-16x16.png">
<!-- Apple iOS Safari settings -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<!-- Home Screen Icons (favourites and bookmarks use the normal icons) -->
<link rel="apple-touch-icon" sizes="60x60" type="image/png" href="app/images/icons/novnc-60x60.png">
<link rel="apple-touch-icon" sizes="76x76" type="image/png" href="app/images/icons/novnc-76x76.png">
<link rel="apple-touch-icon" sizes="120x120" type="image/png" href="app/images/icons/novnc-120x120.png">
<link rel="apple-touch-icon" sizes="152x152" type="image/png" href="app/images/icons/novnc-152x152.png">
<!-- Stylesheets -->
<link rel="stylesheet" href="app/styles/lite.css">
<!--
<script type='text/javascript'
src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script>
-->
<!-- promise polyfills promises for IE11 -->
<script src="vendor/promise.js"></script>
<!-- ES2015/ES6 modules polyfill -->
<script type="module">
window._noVNC_has_module_support = true;
</script>
<script>
window.addEventListener("load", function () {
if (window._noVNC_has_module_support) return;
var loader = document.createElement("script");
loader.src = "vendor/browser-es-module-loader/dist/browser-es-module-loader.js";
document.head.appendChild(loader);
});
</script>
<!-- actual script modules -->
<script type="module" crossorigin="anonymous">
// Load supporting scripts
import * as WebUtil from './app/webutil.js';
import RFB from './core/rfb.js';
import WebAudio from './core/webaudio.js'
var rfb;
var desktopName;
let audioStarted = false;
function updateDesktopName(e) {
desktopName = e.detail.name;
}
function credentials(e) {
var html;
var form = document.createElement('form');
form.innerHTML = '<label></label>';
form.innerHTML += '<input type=password size=10 id="password_input">';
form.onsubmit = setPassword;
// bypass status() because it sets text content
document.getElementById('noVNC_status_bar').setAttribute("class", "noVNC_status_warn");
document.getElementById('noVNC_status').innerHTML = '';
document.getElementById('noVNC_status').appendChild(form);
document.getElementById('noVNC_status').querySelector('label').textContent = 'Password Required: ';
}
function setPassword() {
rfb.sendCredentials({ password: document.getElementById('password_input').value });
return false;
}
function sendCtrlAltDel() {
rfb.sendCtrlAltDel();
return false;
}
function machineShutdown() {
rfb.machineShutdown();
return false;
}
function machineReboot() {
rfb.machineReboot();
return false;
}
function machineReset() {
rfb.machineReset();
return false;
}
function status(text, level) {
switch (level) {
case 'normal':
case 'warn':
case 'error':
break;
default:
level = "warn";
}
document.getElementById('noVNC_status_bar').className = "noVNC_status_" + level;
document.getElementById('noVNC_status').textContent = text;
}
function connected(e) {
var wa = new WebAudio(`ws://${host}:8081/websockify`);
document.getElementsByTagName('canvas')[0].addEventListener('keydown', e => {
if (audioStarted) {
console.info("Audio already started.");
return;
}
// Start the sound with alt+(sS)
const key = e.key;
if (e.altKey && (key.toLowerCase() === "s" || e.code == 'KeyS')) {
e.preventDefault();
try {
wa.start();
audioStarted = true;
}
catch (e) {
console.error(e);
}
}
});
document.getElementById('sendCtrlAltDelButton').disabled = false;
if (WebUtil.getConfigVar('encrypt',
(window.location.protocol === "https:"))) {
status("Connected (encrypted) to " + desktopName, "normal");
} else {
status("Connected (unencrypted) to " + desktopName, "normal");
}
}
function disconnected(e) {
document.getElementById('sendCtrlAltDelButton').disabled = true;
updatePowerButtons();
if (e.detail.clean) {
status("Disconnected", "normal");
} else {
status("Something went wrong, connection is closed", "error");
}
}
function updatePowerButtons() {
var powerbuttons;
powerbuttons = document.getElementById('noVNC_power_buttons');
if (rfb.capabilities.power) {
powerbuttons.className = "noVNC_shown";
} else {
powerbuttons.className = "noVNC_hidden";
}
}
document.getElementById('sendCtrlAltDelButton').onclick = sendCtrlAltDel;
document.getElementById('machineShutdownButton').onclick = machineShutdown;
document.getElementById('machineRebootButton').onclick = machineReboot;
document.getElementById('machineResetButton').onclick = machineReset;
WebUtil.init_logging(WebUtil.getConfigVar('logging', 'warn'));
document.title = WebUtil.getConfigVar('title', 'noVNC');
// By default, use the host and port of server that served this file
var host = WebUtil.getConfigVar('host', window.location.hostname);
var port = WebUtil.getConfigVar('port', window.location.port);
// if port == 80 (or 443) then it won't be present and should be
// set manually
if (!port) {
if (window.location.protocol.substring(0, 5) == 'https') {
port = 443;
}
else if (window.location.protocol.substring(0, 4) == 'http') {
port = 80;
}
}
var password = WebUtil.getConfigVar('password', '');
var path = WebUtil.getConfigVar('path', 'websockify');
// If a token variable is passed in, set the parameter in a cookie.
// This is used by nova-novncproxy.
var token = WebUtil.getConfigVar('token', null);
if (token) {
// if token is already present in the path we should use it
path = WebUtil.injectParamIfMissing(path, "token", token);
WebUtil.createCookie('token', token, 1)
}
(function () {
status("Connecting", "normal");
if ((!host) || (!port)) {
status('Must specify host and port in URL', 'error');
}
var url;
if (WebUtil.getConfigVar('encrypt',
(window.location.protocol === "https:"))) {
url = 'wss';
} else {
url = 'ws';
}
url += '://' + host;
if (port) {
url += ':' + port;
}
url += '/' + path;
rfb = new RFB(document.body, url,
{
repeaterID: WebUtil.getConfigVar('repeaterID', ''),
shared: WebUtil.getConfigVar('shared', true),
credentials: { password: password }
}
);
rfb.viewOnly = WebUtil.getConfigVar('view_only', false);
rfb.addEventListener("connect", connected);
rfb.addEventListener("disconnect", disconnected);
rfb.addEventListener("capabilities", function () { updatePowerButtons(); });
rfb.addEventListener("credentialsrequired", credentials);
rfb.addEventListener("desktopname", updateDesktopName);
rfb.scaleViewport = WebUtil.getConfigVar('scale', false);
rfb.resizeSession = WebUtil.getConfigVar('resize', false);
})();
</script>
<style type="text/css">
#noVNC_status_bar {
display: none;
}
</style>
</head>
<body>
<div id="noVNC_status_bar">
<div id="noVNC_left_dummy_elem"></div>
<div id="noVNC_status">Loading</div>
<div id="noVNC_buttons">
<input type=button value="Send CtrlAltDel" id="sendCtrlAltDelButton" class="noVNC_shown">
<span id="noVNC_power_buttons" class="noVNC_hidden">
<input type=button value="Shutdown" id="machineShutdownButton">
<input type=button value="Reboot" id="machineRebootButton">
<input type=button value="Reset" id="machineResetButton">
</span>
</div>
</div>
</body>
</html>
================================================
FILE: game-engine/conf/supervisord.conf
================================================
[supervisord]
nodaemon=true
pidfile=/home/retrogames/supervisord.pid
logfile=/home/retrogames/supervisord.log
[program:x11vnc]
command=x11vnc -forever -shared
stdout_logfile=/home/retrogames/x11vnc.log
redirect_stderr=true
[program:xvfb]
command=Xvfb :0 -screen 0 "%(ENV_DISPLAY_SETTINGS)s" -listen tcp -ac
stdout_logfile=/home/retrogames/xvfb.log
redirect_stderr=true
[program:websockify_vnc]
command=websockify --web /usr/share/novnc 8080 localhost:5900
stdout_logfile=/home/retrogames/websockify-vnc.log
redirect_stderr=true
[program:pulseaudio]
command=/usr/bin/pulseaudio --disallow-module-loading -vvvv --disallow-exit --exit-idle-time=-1
stdout_logfile=/home/retrogames/pulseaudio.log
redirect_stderr=true
[program:audiostream]
command=tcpserver 127.0.0.1 5901 gst-launch-1.0 -q pulsesrc server=/tmp/pulseaudio.socket ! audio/x-raw, channels=2, rate=24000 ! cutter ! opusenc ! webmmux ! fdsink fd=1
stdout_logfile=/home/retrogames/audiostream.log
redirect_stderr=true
[program:websockify_audio]
command=websockify 8081 localhost:5901
stdout_logfile=/home/retrogames/websockify-audio.log
redirect_stderr=true
[program:dosbox]
command=/entrypoint.sh
stdout_logfile=/home/retrogames/retrogames.log
autostart=true
autorestart=unexpected
startsecs=10
startretries=3
exitcodes=0,255
redirect_stderr=true
================================================
FILE: game-engine/conf/webaudio.js
================================================
export default class WebAudio {
constructor(url) {
this.url = url
this.connected = false;
//constants for audio behavoir
this.maximumAudioLag = 1.5; //amount of seconds we can potentially be behind the server audio stream
this.syncLagInterval = 5000; //check every x milliseconds if we are behind the server audio stream
this.updateBufferEvery = 20; //add recieved data to the player buffer every x milliseconds
this.reduceBufferInterval = 500; //trim the output audio stream buffer every x milliseconds so we don't overflow
this.maximumSecondsOfBuffering = 1; //maximum amount of data to store in the play buffer
this.connectionCheckInterval = 500; //check the connection every x milliseconds
//register all our background timers. these need to be created only once - and will run independent of the object's streams/properties
setInterval(() => this.updateQueue(), this.updateBufferEvery);
setInterval(() => this.syncInterval(), this.syncLagInterval);
setInterval(() => this.reduceBuffer(), this.reduceBufferInterval);
setInterval(() => this.tryLastPacket(), this.connectionCheckInterval);
}
//registers all the event handlers for when this stream is closed - or when data arrives.
registerHandlers() {
this.mediaSource.addEventListener('sourceended', e => this.socketDisconnected(e))
this.mediaSource.addEventListener('sourceclose', e => this.socketDisconnected(e))
this.mediaSource.addEventListener('error', e => this.socketDisconnected(e))
this.buffer.addEventListener('error', e => this.socketDisconnected(e))
this.buffer.addEventListener('abort', e => this.socketDisconnected(e))
}
//starts the web audio stream. only call this method on button click.
start() {
if (!!this.connected) return;
if (!!this.audio) this.audio.remove();
this.queue = null;
this.mediaSource = new MediaSource()
this.mediaSource.addEventListener('sourceopen', e => this.onSourceOpen())
//first we need a media source - and an audio object that contains it.
this.audio = document.createElement('audio');
this.audio.src = window.URL.createObjectURL(this.mediaSource);
//start our stream - we can only do this on user input
this.audio.play();
}
wsConnect() {
if (!!this.socket) this.socket.close();
this.socket = new WebSocket(this.url, ['binary', 'base64'])
this.socket.binaryType = 'arraybuffer'
this.socket.addEventListener('message', e => this.websocketDataArrived(e), false);
}
//this is called when the media source contains data
onSourceOpen(e) {
this.buffer = this.mediaSource.addSourceBuffer('audio/webm; codecs="opus"')
this.registerHandlers();
this.wsConnect();
}
//whenever data arrives in our websocket this is called.
websocketDataArrived(e) {
this.lastPacket = Date.now();
this.connected = true;
this.queue = this.queue == null ? e.data : this.concat(this.queue, e.data);
}
//whenever a disconnect happens this is called.
socketDisconnected(e) {
console.log(e);
this.connected = false;
}
tryLastPacket() {
if (this.lastPacket == null) return;
if ((Date.now() - this.lastPacket) > 1000) {
this.socketDisconnected('timeout');
}
}
//this updates the buffer with the data from our queue
updateQueue() {
if (!(!!this.queue && !!this.buffer && !this.buffer.updating)) {
return;
}
this.buffer.appendBuffer(this.queue);
this.queue = null;
}
//reduces the stream buffer to the minimal size that we need for streaming
reduceBuffer() {
if (!(this.buffer && !this.buffer.updating && !!this.audio && !!this.audio.currentTime && this.audio.currentTime > 1)) {
return;
}
this.buffer.remove(0, this.audio.currentTime - 1);
}
//synchronizes the current time of the stream with the server
syncInterval() {
if (!(this.audio && this.audio.currentTime && this.audio.currentTime > 1 && this.buffer && this.buffer.buffered && this.buffer.buffered.length > 1)) {
return;
}
var currentTime = this.audio.currentTime;
var targetTime = this.buffer.buffered.end(this.buffer.buffered.length - 1);
if (targetTime > (currentTime + this.maximumAudioLag)) this.audio.fastSeek(targetTime);
}
//joins two data arrays - helper function
concat(buffer1, buffer2) {
var tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
tmp.set(new Uint8Array(buffer1), 0);
tmp.set(new Uint8Array(buffer2), buffer1.byteLength);
return tmp.buffer;
};
}
================================================
FILE: game-engine/entrypoint.sh
================================================
#!/bin/bash
set -e
export DOSCONF=$(dosbox -printconf)
export GAME_ROOT=${GAME_ROOT:-/games}
export DOSBOX_CLI=${DOSBOX_CLI:-n}
sleep 5
if [ -z ${GAME_DIR} ]
then
echo "You should pass the game directory you want to run, eg: \"GAME_DIR=DOOM\" exiting..."
exit 255
fi
if [ -z ${GAME_EXE} ]
then
echo "You should pass the game executable you want to run, eg: \"GAME_EXE=DOOM\" exiting..."
exit 255
fi
if [ ${DOSBOX_CLI} == 'n' ]; then
if [ ! -f ${GAME_ROOT}/${GAME_DIR}/${GAME_EXE} ]
then
echo "I cannot find the executable: ${GAME_ROOT}/${GAME_DIR}/${GAME_EXE}"
exit 255
fi
envsubst < /dosbox/dosbox.conf.template > ~/.dosbox/dosbox.conf
exec dosbox -conf ~/.dosbox/dosbox.conf
else
envsubst < /dosbox/dosbox.cli.conf.template > ~/.dosbox/dosbox.conf
exec dosbox -conf ~/.dosbox/dosbox.conf
fi
================================================
FILE: game-engine/run.sh
================================================
docker rm -f retrogames-k8s || true
docker run \
--detach \
--env DISPLAY_SETTINGS="1024x768x24" \
--env GAME_DIR=${1} \
--env GAME_EXE="${2}" \
--env DOSBOX_CLI="n" \
--publish 8080:8080 \
--publish 8081:8081 \
--rm \
-v $PWD/games:/games \
--name retrogames-k8s \
sparkfabrik/retro-games-k8s:1.0
xdg-open http://localhost:8080
================================================
FILE: k8s/manifests/crd-game-controller.yml
================================================
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
# name must match the spec fields below, and be in the form: <plural>.<group>
name: games.retro.sparkfabrik.com
spec:
# group name to use for REST API: /apis/<group>/<version>
group: retro.sparkfabrik.com
# list of versions supported by this CustomResourceDefinition
versions:
- name: v1
# Each version can be enabled/disabled by Served flag.
served: true
# One and only one version must be marked as the storage version.
storage: true
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
properties:
name:
type: string
zipUrl:
type: string
dir:
type: string
exe:
type: string
required:
- name
- zipUrl
- dir
- exe
status:
type: object
description: GameStatus defines the observed state of Game
properties:
gameState:
type: string
subresources:
status: {}
# The columns we see in the kubectl output.
additionalPrinterColumns:
- name: Game name
type: string
description: The game name
jsonPath: .spec.name
- name: GSURL
type: string
description: The zip url of this game
jsonPath: .spec.zipUrl
- name: status
type: string
description: The game status
jsonPath: .status.gameState
- name: age
type: date
description: Age
jsonPath: .metadata.creationTimestamp
scope: Namespaced
names:
plural: games
singular: game
kind: Game
shortNames:
- gm
================================================
FILE: k8s/manifests/game-controller-cluster-role-binding.yml
================================================
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: role-game-controller-binding
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: role-game-controller
subjects:
- kind: ServiceAccount
name: game-controller-service-account
namespace: games
================================================
FILE: k8s/manifests/game-controller-cluster-role.yml
================================================
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: role-game-controller
rules:
- apiGroups: ["retro.sparkfabrik.com"]
resources: ["games", "games/status"]
verbs: ["*"]
- apiGroups: ["",]
resources: ["configmaps", "events", "services"]
verbs: ["*"]
- apiGroups: ["apps"]
resources: ["deployments"]
verbs: ["*"]
================================================
FILE: k8s/manifests/game-controller-sa.yml
================================================
apiVersion: v1
kind: ServiceAccount
metadata:
name: game-controller-service-account
namespace: games
================================================
FILE: k8s/manifests/game-controller.yaml
================================================
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: game-controller
name: game-controller
spec:
replicas: 1
selector:
matchLabels:
app: game-controller
strategy:
type: Recreate
template:
metadata:
labels:
app: game-controller
spec:
serviceAccount: game-controller-service-account
containers:
- image: ghcr.io/paolomainardi/additronk8s-game-controller
name: additronk8s-game-controller
================================================
FILE: k8s/manifests/namespace.yml
================================================
apiVersion: "v1"
kind: Namespace
metadata:
name: "games"
================================================
FILE: k8s/src/game-controller/Dockerfile
================================================
FROM node:15-slim
WORKDIR /app
COPY package* ./
RUN npm install
COPY . .
CMD ["node", "index"]
================================================
FILE: k8s/src/game-controller/index.js
================================================
import * as k8s from "@kubernetes/client-node";
import * as crdInformer from "./lib/crd-informer.js";
// Connnect to k8s apis.
const kc = new k8s.KubeConfig();
kc.loadFromDefault();
console.log("\nWelcome to the Additron Machine\n");
// Start the informers.
crdInformer.start(kc, k8s);
================================================
FILE: k8s/src/game-controller/lib/api-machinery.js
================================================
import * as util from "./util.js";
export const createApiMachinery = (kc, k8s) => {
/**
* @type {import('@kubernetes/client-node').CustomObjectsApi}
*/
const customApi = kc.makeApiClient(k8s.CustomObjectsApi);
/**
* @type {import('@kubernetes/client-node').CoreV1Api}
*/
const coreApi = kc.makeApiClient(k8s.CoreV1Api);
/**
* @type {import('@kubernetes/client-node').AppsV1Api}
*/
const appsApi = kc.makeApiClient(k8s.AppsV1Api);
const apiMachinery = {
setOwner: function (owner) {
if (!owner) {
throw `Owner cannot be empty`;
}
this.owner = owner;
},
/**
*
*/
createCrdInformer: function () {
return k8s.makeInformer(
kc,
"/apis/retro.sparkfabrik.com/v1/games",
() => {
return customApi.listClusterCustomObject(
"retro.sparkfabrik.com",
"v1",
"games"
);
}
);
},
updateStatus: async function (status) {
const options = {
headers: { "Content-type": k8s.PatchUtils.PATCH_FORMAT_JSON_PATCH },
};
return await customApi.patchNamespacedCustomObjectStatus(
"retro.sparkfabrik.com",
"v1",
this.owner.metadata.namespace,
"games",
this.owner.metadata.name,
[
{
op: "replace",
path: "/status",
value: {
gameState: status,
},
},
],
undefined,
undefined,
undefined,
options
);
},
/**
*
* @param {*} configmap
*/
saveConfigMap: async function (configmap) {
return await coreApi.createNamespacedConfigMap(
this.owner.metadata.namespace,
configmap
);
},
/**
*
* @param {*} service
*/
saveService: async function (service) {
const res = await coreApi.createNamespacedService(
this.owner.metadata.namespace,
service
);
},
/**
*
* @param {*} deployment
*/
saveDeployment: async function (deployment) {
return await appsApi.createNamespacedDeployment(
this.owner.metadata.namespace,
deployment
);
},
saveServices: async () => {},
saveIngress: async () => {},
event: async function (options) {
const event = {
metadata: {
generateName: "game-event-",
},
involvedObject: {
kind: this.owner.kind,
name: this.owner.metadata.name,
uid: this.owner.metadata.uid,
namespace: this.owner.metadata.namespace,
},
reason: options.reason,
type: options.type || "Normal",
lastTimestamp: new Date(),
message: options.message,
};
await coreApi.createNamespacedEvent(this.owner.metadata.namespace, event);
},
/**
*
* @param {*} type
* @param {*} object
*/
save: async function (type, object) {
const funcName = `save${type}`;
if (!this.owner) {
throw `Owner cannot be empty`;
}
if (!object) {
throw `Object cannot be empty`;
}
if (typeof this[funcName] !== "function") {
throw `${funcName} is not a valid function, aborting.`;
}
const addLabels = util.addDefaultLabels(object, this.owner);
const final = util.addOwnerReference(addLabels, this.owner);
return await this[funcName](final);
},
};
return apiMachinery;
};
================================================
FILE: k8s/src/game-controller/lib/crd-informer.js
================================================
import { createApiMachinery } from "./api-machinery.js";
import { saveGame, deployGame } from "./game-engine.js";
/**
* @param {import('@kubernetes/client-node').KubeConfig} kc - Kubeconfig
* @param {import('@kubernetes/client-node')} k8s - K8s
*/
export const start = (kc, k8s) => {
const machine = createApiMachinery(kc, k8s);
const crdInformer = machine.createCrdInformer();
crdInformer.on("add", async (gameObject) => {
try {
if (process.env.DEBUG) {
console.log(JSON.stringify(gameObject, null, 2));
}
// TODO: Check if this game already exists.
machine.setOwner(gameObject);
// Get default variables.
const name = gameObject.spec.name;
// Download and save game.
console.log(`Reading cloud floppy disks of "${name}" in progress... 💾`);
const configmaps = await saveGame(gameObject, machine);
// Deploy game.
console.log(`Great! Game downloaded, now saving it locally.... ⌛`);
await deployGame(gameObject, configmaps, machine);
console.log(`Game ready... 🕹️`);
// Mark as ready.
await machine.updateStatus("Ready");
} catch (e) {
try {
await machine.updateStatus("Error");
} catch (e) {
console.error("Cannot update the status.");
} finally {
e.response?.body?.message
? console.error(e.response.body.message)
: console.error(e);
}
}
});
// TODO: Handle CRD updates.
crdInformer.on("update", async (obj) => {
if (process.env.DEBUG) {
console.log(JSON.stringify(gameObject, null, 2));
}
});
// TODO: Handle CRD deletes.
crdInformer.on("delete", async (obj) => {
if (process.env.DEBUG) {
console.log(JSON.stringify(gameObject, null, 2));
}
});
crdInformer.start();
};
================================================
FILE: k8s/src/game-controller/lib/game-engine.js
================================================
import * as path from "path";
import * as fs from "fs";
import * as util from "./util.js";
/**
*
* @param {*} files
* @param {*} gameObject
*/
const createConfigMapsSpec = async (files, gameObject) => {
let configmaps = [];
let index = 0;
for (const file of files) {
let filename = path.basename(file).toLowerCase();
let data = await fs.promises.readFile(file, { encoding: "base64" });
let configmap = {
metadata: {
name: `${gameObject.metadata.name}-${index}`,
},
binaryData: {
[filename]: data,
},
};
configmaps.push(configmap);
index++;
}
return configmaps;
};
/**
*
* @param {*} gameObject
*/
export async function downloadAndCreateConfigmapsSpec(gameObject) {
try {
const path = await util.download(gameObject);
const files = await util.splitFile(path);
const configmaps = await createConfigMapsSpec(files, gameObject);
return configmaps;
} catch (e) {
throw e;
}
}
/**
*
* @param {*} gameObject
*/
const createServiceSpec = (gameObject) => {
const name = gameObject.metadata.name;
const service = {
metadata: {
name: name,
labels: {
app: name,
},
},
spec: {
selector: {
app: name,
},
ports: [
{
name: "vnc",
protocol: "TCP",
port: 8080,
containerPort: 8080,
},
{
name: "audio",
protocol: "TCP",
port: 8081,
containerPort: 8081,
},
],
},
};
return service;
};
/**
*
* @param {*} name
* @param {*} configmaps
*/
const createDeploymentSpec = (gameObject, configmaps) => {
const name = gameObject.metadata.name;
const deployment = {
metadata: {
name: name,
labels: {
app: name,
},
},
spec: {
replicas: 1,
selector: {
matchLabels: {
app: name,
},
},
template: {
metadata: {
labels: {
app: name,
},
},
spec: {
initContainers: [
{
name: "hydrate-game",
image: "ghcr.io/paolomainardi/additronk8s-game-engine:latest",
imagePullPolicy: "Always",
command: [
"bash",
"-c",
"cd /split && ls | sort -n | xargs cat > /games/game.zip && cd /games && unzip game.zip && rm game.zip",
],
},
],
containers: [
{
name: "game-engine",
image: "ghcr.io/paolomainardi/additronk8s-game-engine:latest",
imagePullPolicy: "Always",
env: [
{
name: "GAME_DIR",
value: gameObject.spec.dir,
},
{
name: "GAME_EXE",
value: gameObject.spec.exe,
},
{
name: "DISPLAY_SETTINGS",
value: "1024x768x24",
},
],
ports: [
{
containerPort: 8080,
containerPort: 8081,
},
],
},
],
},
},
},
};
const deploymentWithVolumes = addDeploymentVolumes(deployment, configmaps);
return deploymentWithVolumes;
};
/**
*
* @param {*} deployment
* @param {*} configmaps
*/
const addDeploymentVolumes = (deployment, configmaps) => {
const deploymentClone = { ...deployment };
const volumes = [];
const volumeMounts = [];
configmaps.forEach((configmap, key) => {
volumes.push({
name: `configmap-volume-${key}`,
configMap: {
name: configmap.configmapName,
items: [
{
key: configmap.filename,
path: configmap.filename,
},
],
},
});
volumeMounts.push({
name: `configmap-volume-${key}`,
mountPath: `/split/${key}`,
subPath: configmap.filename,
});
});
// Add the final game volume.
const gamesVolume = {
name: `games-volume`,
emptyDir: {},
};
const gamesVolumeMount = {
name: "games-volume",
mountPath: "/games",
};
volumes.push(gamesVolume);
volumeMounts.push(gamesVolumeMount);
// Add all volumes to the init container.
deploymentClone["spec"]["template"]["spec"]["volumes"] = volumes;
deploymentClone["spec"]["template"]["spec"]["initContainers"][0][
"volumeMounts"
] = volumeMounts;
// Add only the game volume to the game engine.
deploymentClone["spec"]["template"]["spec"]["containers"][0][
"volumeMounts"
] = [gamesVolumeMount];
return deploymentClone;
};
/**
*
* @param {*} gameUrl
* @param {*} machine
*/
export const saveGame = async (gameObject, machine) => {
try {
await machine.event({
reason: "Downloading",
message: `Starting to download game "${gameObject.spec.name}" from: ${gameObject.spec.zipUrl}`,
});
const configmaps = await downloadAndCreateConfigmapsSpec(gameObject);
for (const configmap of configmaps) {
await machine.save("ConfigMap", configmap);
}
await machine.event({
reason: "Downloaded",
message: `Downloaded and splitted in ${configmaps.length} configmaps`,
});
return configmaps;
} catch (e) {
await machine.event({
reason: "Failed",
type: "Warning",
message: `Download of game failed cause: ${JSON.stringify(e.message)}`,
});
throw e;
}
};
/**
*
* @param {*} machine
*/
export const deployGame = async (gameObject, configmaps, machine) => {
try {
const configMapsNames = [];
configmaps.map((configmap) => {
const filename = Object.keys(configmap.binaryData).pop();
configMapsNames.push({
filename: filename,
configmapName: configmap.metadata.name,
});
});
// Create deployment.
const deployment = createDeploymentSpec(gameObject, configMapsNames);
await machine.save("Deployment", deployment);
// Create service.
const service = createServiceSpec(gameObject);
await machine.save("Service", service);
await machine.event({
reason: "Deployed",
message: `Deployment and service correctly created`,
});
} catch (e) {
await machine.event({
reason: "Failed",
type: "Warning",
message: `Failed to start the game cause: ${JSON.stringify(e.message)}`,
});
throw e;
}
};
================================================
FILE: k8s/src/game-controller/lib/util.js
================================================
import { Storage } from "@google-cloud/storage";
import axios from "axios";
import { URL } from "url";
import { promisify } from "util";
import { exec } from "child_process";
import * as path from "path";
import { sep } from "path";
import * as fs from "fs";
import * as os from "os";
export function addOwnerReference(api, owner) {
const newApi = { ...api };
newApi["metadata"]["ownerReferences"] = [
{
apiVersion: "retro.sparkfabrik.com/v1",
controller: true,
blockOwnerDeletion: true,
kind: "Game",
name: owner.metadata.name,
uid: owner.metadata.uid,
},
];
return newApi;
}
export function addDefaultLabels(api, owner) {
if (!api.metadata && owner.metadata) {
throw `Objects must contain a metadata property`;
}
const newApi = { ...api };
const defaultLabels = {
"sparkfabrik.com/game": owner.metadata.name,
};
newApi.metadata.labels = { ...newApi.metadata.labels, ...defaultLabels };
return newApi;
}
const mkTempDir = async () => {
return await promisify(fs.mkdtemp)(`${os.tmpdir()}${sep}`);
};
/**
*
* @param {*} gameObject
*/
export const download = async (gameObject) => {
const url = new URL(gameObject.spec.zipUrl);
const protocol = url.protocol;
if (protocol == "gs:") {
return await downloadFromGcs(url);
}
if (protocol === "http:" || protocol === "https:") {
return await downloadFromHttp(url);
}
throw new Error(`Not supported protocol: ${protocol}`);
};
/**
*
* @param {*} gameObject
*/
const downloadFromHttp = async (url) => {
const filename = url.pathname.substr(1, url.pathname.length).split('/').pop();
const dest = (await mkTempDir()) + `/${filename}`;
const response = await axios({
method: "get",
url: url.href,
responseType: "stream",
});
response.data.pipe(fs.createWriteStream(dest, response.data));
return new Promise((resolve, reject) => {
response.data.on("end", () => {
resolve(dest);
});
response.data.on("error", (err) => {
reject(err);
});
});
};
const downloadFromGcs = async (url) => {
const storage = new Storage();
const filename = url.pathname.substr(1, url.pathname.length);
const dest = (await mkTempDir()) + `/${filename}`;
await storage.bucket(url.host).file(filename).download({ destination: dest });
return dest;
};
/**
*
* @param {*} game
*/
export const splitFile = async (game) => {
if (!fs.statSync(game)) {
throw `${path} does not exists, cannot split the requested file.`;
}
const dir = path.dirname(game);
const file = path.basename(game);
await promisify(exec)(`cd ${dir}; split -d -b 1M ${file} ${file}-split`);
const { stdout } = await promisify(exec)(
`find ${dir} -name "${file}-split*" | sort`
);
const split = stdout.split(/[\r\n|\n|\r]/).filter(String);
return split;
};
================================================
FILE: k8s/src/game-controller/package.json
================================================
{
"name": "game-informer",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"type": "module",
"author": "",
"license": "ISC",
"dependencies": {
"@google-cloud/storage": "^5.6.0",
"@kubernetes/client-node": "^0.13.0",
"axios": "^0.21.1"
}
}
================================================
FILE: skaffold.yml
================================================
apiVersion: skaffold/v1
kind: Config
metadata:
name: additronk8s
build:
artifacts:
- image: ghcr.io/paolomainardi/additronk8s-game-controller
context: k8s/src/game-controller
docker:
dockerfile: Dockerfile
deploy:
kubectl:
manifests:
- ./k8s/manifests/namespace.yml
- ./k8s/manifests/*
gitextract_hq6e478a/ ├── .github/ │ └── workflows/ │ ├── build-controller.yaml │ └── build-engine.yml ├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── game-engine/ │ ├── .dockerignore │ ├── Dockerfile │ ├── conf/ │ │ ├── client.conf │ │ ├── default.pa │ │ ├── dosbox/ │ │ │ ├── dosbox.cli.conf.template │ │ │ └── dosbox.conf.template │ │ ├── novnc/ │ │ │ ├── background_patch.diff │ │ │ └── vnc_lite.html │ │ ├── supervisord.conf │ │ └── webaudio.js │ ├── entrypoint.sh │ └── run.sh ├── k8s/ │ ├── manifests/ │ │ ├── crd-game-controller.yml │ │ ├── game-controller-cluster-role-binding.yml │ │ ├── game-controller-cluster-role.yml │ │ ├── game-controller-sa.yml │ │ ├── game-controller.yaml │ │ └── namespace.yml │ └── src/ │ └── game-controller/ │ ├── Dockerfile │ ├── index.js │ ├── lib/ │ │ ├── api-machinery.js │ │ ├── crd-informer.js │ │ ├── game-engine.js │ │ └── util.js │ └── package.json └── skaffold.yml
SYMBOL INDEX (16 symbols across 3 files)
FILE: game-engine/conf/webaudio.js
class WebAudio (line 1) | class WebAudio {
method constructor (line 2) | constructor(url) {
method registerHandlers (line 24) | registerHandlers() {
method start (line 33) | start() {
method wsConnect (line 48) | wsConnect() {
method onSourceOpen (line 57) | onSourceOpen(e) {
method websocketDataArrived (line 64) | websocketDataArrived(e) {
method socketDisconnected (line 71) | socketDisconnected(e) {
method tryLastPacket (line 76) | tryLastPacket() {
method updateQueue (line 84) | updateQueue() {
method reduceBuffer (line 94) | reduceBuffer() {
method syncInterval (line 103) | syncInterval() {
method concat (line 115) | concat(buffer1, buffer2) {
FILE: k8s/src/game-controller/lib/game-engine.js
function downloadAndCreateConfigmapsSpec (line 34) | async function downloadAndCreateConfigmapsSpec(gameObject) {
FILE: k8s/src/game-controller/lib/util.js
function addOwnerReference (line 11) | function addOwnerReference(api, owner) {
function addDefaultLabels (line 26) | function addDefaultLabels(api, owner) {
Condensed preview — 32 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (90K chars).
[
{
"path": ".github/workflows/build-controller.yaml",
"chars": 2270,
"preview": "name: build-controller\n\non:\n pull_request:\n branches: main\n push:\n branches: main\n tags:\n - v*\n\njobs:\n "
},
{
"path": ".github/workflows/build-engine.yml",
"chars": 2250,
"preview": "name: build-engine\n\non:\n pull_request:\n branches: main\n push:\n branches: main\n tags:\n - v*\n\njobs:\n buil"
},
{
"path": ".gitignore",
"chars": 19,
"preview": "games\nnode_modules\n"
},
{
"path": "LICENSE",
"chars": 11357,
"preview": " Apache License\n Version 2.0, January 2004\n "
},
{
"path": "Makefile",
"chars": 672,
"preview": "all: run\n\nSHELL := /bin/bash\n\nifndef GAME_DIR\n\tGAME_DIR=MONKEY_FLOPPY\nendif\nifndef GAME_EXE\n\tGAME_EXE=MONEY.EXE\nendif\n\nb"
},
{
"path": "README.md",
"chars": 5509,
"preview": "# AdditronK8S\n\n[ {\n this.url = url\n\n this.connected = false;\n\n "
},
{
"path": "game-engine/entrypoint.sh",
"chars": 858,
"preview": "#!/bin/bash\nset -e\nexport DOSCONF=$(dosbox -printconf)\nexport GAME_ROOT=${GAME_ROOT:-/games}\nexport DOSBOX_CLI=${DOSBOX_"
},
{
"path": "game-engine/run.sh",
"chars": 353,
"preview": "docker rm -f retrogames-k8s || true\ndocker run \\\n --detach \\\n --env DISPLAY_SETTINGS=\"1024x768x24\" \\\n --env GAME_DIR="
},
{
"path": "k8s/manifests/crd-game-controller.yml",
"chars": 1902,
"preview": "apiVersion: apiextensions.k8s.io/v1\nkind: CustomResourceDefinition\nmetadata:\n # name must match the spec fields below, "
},
{
"path": "k8s/manifests/game-controller-cluster-role-binding.yml",
"chars": 306,
"preview": "apiVersion: rbac.authorization.k8s.io/v1\nkind: ClusterRoleBinding\nmetadata:\n name: role-game-controller-binding\nroleRef"
},
{
"path": "k8s/manifests/game-controller-cluster-role.yml",
"chars": 347,
"preview": "apiVersion: rbac.authorization.k8s.io/v1\nkind: ClusterRole\nmetadata:\n name: role-game-controller\nrules:\n- apiGroups: [\""
},
{
"path": "k8s/manifests/game-controller-sa.yml",
"chars": 105,
"preview": "apiVersion: v1\nkind: ServiceAccount\nmetadata:\n name: game-controller-service-account\n namespace: games\n"
},
{
"path": "k8s/manifests/game-controller.yaml",
"chars": 471,
"preview": "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n labels:\n app: game-controller\n name: game-controller\nspec:\n replic"
},
{
"path": "k8s/manifests/namespace.yml",
"chars": 58,
"preview": "apiVersion: \"v1\"\nkind: Namespace\nmetadata:\n name: \"games\""
},
{
"path": "k8s/src/game-controller/Dockerfile",
"chars": 97,
"preview": "FROM node:15-slim\n\nWORKDIR /app\n\nCOPY package* ./\nRUN npm install\n\nCOPY . .\nCMD [\"node\", \"index\"]"
},
{
"path": "k8s/src/game-controller/index.js",
"chars": 289,
"preview": "import * as k8s from \"@kubernetes/client-node\";\nimport * as crdInformer from \"./lib/crd-informer.js\";\n\n// Connnect to k8"
},
{
"path": "k8s/src/game-controller/lib/api-machinery.js",
"chars": 3524,
"preview": "import * as util from \"./util.js\";\n\nexport const createApiMachinery = (kc, k8s) => {\n /**\n * @type {import('@kubernet"
},
{
"path": "k8s/src/game-controller/lib/crd-informer.js",
"chars": 1812,
"preview": "import { createApiMachinery } from \"./api-machinery.js\";\nimport { saveGame, deployGame } from \"./game-engine.js\";\n\n/**\n "
},
{
"path": "k8s/src/game-controller/lib/game-engine.js",
"chars": 6524,
"preview": "import * as path from \"path\";\nimport * as fs from \"fs\";\nimport * as util from \"./util.js\";\n\n/**\n *\n * @param {*} files\n "
},
{
"path": "k8s/src/game-controller/lib/util.js",
"chars": 2835,
"preview": "import { Storage } from \"@google-cloud/storage\";\nimport axios from \"axios\";\nimport { URL } from \"url\";\nimport { promisif"
},
{
"path": "k8s/src/game-controller/package.json",
"chars": 358,
"preview": "{\n \"name\": \"game-informer\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\":"
},
{
"path": "skaffold.yml",
"chars": 319,
"preview": "apiVersion: skaffold/v1\nkind: Config\nmetadata:\n name: additronk8s\nbuild:\n artifacts:\n - image: ghcr.io/paolomainardi/"
}
]
About this extraction
This page contains the full source code of the paolomainardi/additronk8s-retrogames-kubernetes-controller GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 32 files (82.7 KB), approximately 22.1k tokens, and a symbol index with 16 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.