"New Epics". We eat the elephant in parts

"New Epics". We eat the elephant in parts

In this article, I will set up a working environment for developing the game "Epics", and will also break the game itself into parts suitable for use in OpenFaaS. I will do all the manipulations on Linux, I will deploy Kubernetes in minikube using VirtualBox. My work machine has 2 processor cores and 12GB of RAM; I use an SSD as the system disk. I will use debian 8 as my main development system, with emacs, sudo, git and virtualbox packages installed, everything else will be installed by downloading from GitHub and other sources. We will install these applications in /usr/local/bin unless otherwise specified. Let's get started!

Preparing the working environment

Installing Go

We follow the instructions from the official website:

$ curl -L0 https://dl.google.com/go/go1.13.5.linux-amd64.tar.gz -o go.tar.gz
$ sudo tar -C /usr/local -xzf go.tar.gz
$ echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.profile

Checking functionality:

$ mkdir -p ~/go/src/hello && cd ~/go/src/hello
$ echo 'package main

import "fmt"

func main() {
fmt.Printf("hello, worldn")
}' > hello.go
$ go build
$ ./hello
hello, world

Installing faas-cli

We follow the instructions from the official website:

$ curl -sSL https://cli.openfaas.com | sudo -E sh
x86_64
Downloading package https://github.com/openfaas/faas-cli/releases/download/0.11.3/faas-cli as /tmp/faas-cli
Download complete.

Running with sufficient permissions to attempt to move faas-cli to /usr/local/bin
New version of faas-cli installed to /usr/local/bin
Creating alias 'faas' for 'faas-cli'.
  ___                   _____           ____
 / _  _ __   ___ _ __ |  ___|_ _  __ _/ ___|
| | | | '_  / _  '_ | |_ / _` |/ _` ___ 
| |_| | |_) |  __/ | | |  _| (_| | (_| |___) |
 ___/| .__/ ___|_| |_|_|  __,_|__,_|____/
      |_|

CLI:
 commit:  73004c23e5a4d3fdb7352f953247473477477a64
 version: 0.11.3

Additionally, you can enable bash-completion:

faas-cli completion --shell bash | sudo tee /etc/bash_completion.d/faas-cli

Installing and Configuring Kubernetes

For development, minikube is enough, so install it and kubelet in /usr/local/bin, and install helm to install applications:

$ curl https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64 -o minikube && chmod +x minikube && sudo mv minikube /usr/local/bin/
$ curl https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl -o kubectl && chmod +x kubectl && sudo mv kubectl /usr/local/bin/
$ curl https://get.helm.sh/helm-v3.0.2-linux-amd64.tar.gz | tar -xzvf - linux-amd64/helm --strip-components=1; sudo mv helm /usr/local/bin

Launch minikube:

$ minikube start
  minikube v1.6.2 on Debian 8.11
  Automatically selected the 'virtualbox' driver (alternates: [])
  Downloading VM boot image ...
    > minikube-v1.6.0.iso.sha256: 65 B / 65 B [--------------] 100.00% ? p/s 0s
    > minikube-v1.6.0.iso: 150.93 MiB / 150.93 MiB [-] 100.00% 5.67 MiB p/s 27s
  Creating virtualbox VM (CPUs=2, Memory=8192MB, Disk=20000MB) ...
  Preparing Kubernetes v1.17.0 on Docker '19.03.5' ...
  Downloading kubeadm v1.17.0
  Downloading kubelet v1.17.0
  Pulling images ...
  Launching Kubernetes ...  Waiting for cluster to come online ...
  Done! kubectl is now configured to use "minikube"

We check:

$ kubectl get pods --all-namespaces
NAMESPACE     NAME                               READY   STATUS    RESTARTS   AGE
kube-system   coredns-6955765f44-knlcb           1/1     Running   0          29m
kube-system   coredns-6955765f44-t9cpn           1/1     Running   0          29m
kube-system   etcd-minikube                      1/1     Running   0          28m
kube-system   kube-addon-manager-minikube        1/1     Running   0          28m
kube-system   kube-apiserver-minikube            1/1     Running   0          28m
kube-system   kube-controller-manager-minikube   1/1     Running   0          28m
kube-system   kube-proxy-hv2wc                   1/1     Running   0          29m
kube-system   kube-scheduler-minikube            1/1     Running   0          28m
kube-system   storage-provisioner                1/1     Running   1          29m

Installing OpenFaaS

The developers recommend creating 2 namespaces to work with:

$ kubectl apply -f https://raw.githubusercontent.com/openfaas/faas-netes/master/namespaces.yml
namespace/openfaas created
namespace/openfaas-fn created

Add a repository for helm:

$ helm repo add openfaas https://openfaas.github.io/faas-netes/
"openfaas" has been added to your repositories

The chart has the ability to set a password before installation, let's use it and save the access data as a k8s secret:

$ PASSWORD=verysecurerandompasswordstring
$ kubectl -n openfaas create secret generic basic-auth --from-literal=basic-auth-user=admin --from-literal=basic-auth-password="$PASSWORD"
secret/basic-auth created

Let's deploy:

$ helm repo update
Hang tight while we grab the latest from your chart repositories...
...Successfully got an update from the "openfaas" chart repository
Update Complete.  Happy Helming!
$ helm upgrade openfaas --install openfaas/openfaas --namespace openfaas --set functionNamespace=openfaas-fn --set generateBasicAuth=false
Release "openfaas" does not exist. Installing it now.
NAME: openfaas
LAST DEPLOYED: Fri Dec 25 10:28:22 2019
NAMESPACE: openfaas
STATUS: deployed
REVISION: 1
TEST SUITE: None
NOTES:
To verify that openfaas has started, run:

  kubectl -n openfaas get deployments -l "release=openfaas, app=openfaas"

After some time, we run the proposed command:

$ kubectl -n openfaas get deployments -l "release=openfaas, app=openfaas"
NAME                READY   UP-TO-DATE   AVAILABLE   AGE
alertmanager        1/1     1            1           114s
basic-auth-plugin   1/1     1            1           114s
faas-idler          1/1     1            1           114s
gateway             1/1     1            1           114s
nats                1/1     1            1           114s
prometheus          1/1     1            1           114s
queue-worker        1/1     1            1           114s

Checking functionality:

$ kubectl rollout status -n openfaas deploy/gateway
deployment "gateway" successfully rolled out
$ kubectl port-forward -n openfaas svc/gateway 8080:8080 &
[1] 6985
Forwarding from 127.0.0.1:8080 -> 8080
$ echo -n $PASSWORD | faas-cli login --username admin --password-stdin
Calling the OpenFaaS server to validate the credentials...
Handling connection for 8080
WARNING! Communication is not secure, please consider using HTTPS. Letsencrypt.org offers free SSL/TLS certificates.
credentials saved for admin http://127.0.0.1:8080
$ faas-cli list
Function                        Invocations     Replicas

Installing Mongodb

We install everything using helm:

$ helm repo add stable https://kubernetes-charts.storage.googleapis.com/
"stable" has been added to your repositories
$ helm install stable/mongodb --generate-name
NAME: mongodb-1577466908
LAST DEPLOYED: Fri Dec 25 11:15:11 2019
NAMESPACE: default
STATUS: deployed
REVISION: 1
TEST SUITE: None
NOTES:
** Please be patient while the chart is being deployed **

MongoDB can be accessed via port 27017 on the following DNS name from within your cluster:

    mongodb-1577466908.default.svc.cluster.local

To get the root password run:

    export MONGODB_ROOT_PASSWORD=$(kubectl get secret --namespace default mongodb-1577466908 -o jsonpath="{.data.mongodb-root-password}" | base64 --decode)

To connect to your database run the following command:

    kubectl run --namespace default mongodb-1577466908-client --rm --tty -i --restart='Never' --image bitnami/mongodb --command -- mongo admin --host mongodb-1577466908 --authenticationDatabase admin -u root -p $MONGODB_ROOT_PASSWORD

To connect to your database from outside the cluster execute the following commands:

    kubectl port-forward --namespace default svc/mongodb-1577466908 27017:27017 &
    mongo --host 127.0.0.1 --authenticationDatabase admin -p $MONGODB_ROOT_PASSWORD

We check:

kubectl run --namespace default mongodb-1577466908-client --rm --tty -i --restart='Never' --image bitnami/mongodb --command -- mongo admin --host mongodb-1577466908 --authenticationDatabase admin -u root -p $(kubectl get secret --namespace default mongodb-1577466908 -o jsonpath="{.data.mongodb-root-password}" | base64 --decode)
If you don't see a command prompt, try pressing enter.

> db.version();
4.0.14

Press ctrl+D to exit the container.

Setting up emacs

In principle, everything was already configured according to this article, so I won’t go into detail.

Breaking down the game into functions

Interaction with functions is carried out via the http protocol, end-to-end authentication between different functions is provided by JWT. Mongodb is used to store tokens, as well as game state, player data, sequences of moves of all games and other information. Let's take a closer look at the most interesting features.

Register

The input of this function is JSON with the game nickname and password. When this function is called, it is checked that this alias is not in the database; if the check is successful, the alias and password hash are inserted into the database. Registration is required to actively participate in the game.

Sign In

The function input is JSON with a game nickname and password; if there is an nickname in the database and the password is successfully verified with the one previously saved in the database, a JWT is returned, which must be passed to other functions when they are called. Various service records are also inserted into the database, for example, last login time, etc.

View a list of games

Any unauthorized user can request a list of all games except active ones. An authorized user also sees a list of active games. The result of the function is JSON containing lists of games (game ID, human-readable name, etc.).

Creating a game

The function works only with authorized users; the maximum number of players is accepted at the input, as well as game parameters (for example, which characters to activate in this game, the maximum number of players, etc.). A separate parameter of the game is the presence of a password for joining, which allows you to create non-public games. By default, a public game is created. The result of the function is JSON, which contains a creation success field, a unique game identifier, and other parameters.

Joining a game

The function works only with authorized users, the input is the game ID and its password, if this is a non-public game, the output is JSON with the game parameters. The authorized user who joined the game, as well as the creator of the game, are hereinafter called game participants.

Viewing game events

Any unauthorized user can request a list of events for inactive games, and an authorized user can receive a list of events for any active game. An additional parameter to the function can be the event number that the user already has. In this case, only those events that occurred later will be returned in the list. By periodically launching this function, an authorized user watches what is happening in the game. This function also returns an action request, which the user can respond to using the game's event dispatch function.

Sending a game event

The function works only for game participants: it is possible to start the game, make a move, vote, write a text message that is displayed in the list of game events, etc.
The authorized user who created the game starts distributing roles to all participants in the game, including themselves, they must confirm their role using the same function. Once all roles are confirmed, the game automatically switches to night mode.

Game statistics

The function works only for game participants; it shows the state of the game, the list and number of players (nicknames), roles and their status (move made or not), as well as other information. As with the previous function, everything works only for game participants.

Periodically launched functions

If the game has not been launched for some time specified when creating the game, it will be automatically removed from the list of active games using the clear function.

Another periodic task is the forced switching of the game mode from night to day and back for games for which this did not happen during the turn (for example, a player who needs to react to a game event did not send his solution for some reason).

Announcement

  • Introduction
  • Setting up a development environment, splitting a task into functions
  • Backend work
  • Frontend work
  • CICD setup, testing organization
  • Starting a trial game session
  • Results

Source: habr.com

Add a comment