Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .mockery.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,6 @@ packages:
github.com/spacechunks/explorer/controlplane/user:
interfaces:
Repository:
github.com/spacechunks/explorer/controlplane/serverapi:
interfaces:
Client:
14 changes: 3 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
# The Chunk Explorer

The vision of this project is to create a space where anyone can host their Minecraft creations easily and make them discoverable for other people.
Currently, the focus is only on minigames, but future releases will extend the system for all types of experiences. Due to utilizing container checkpointing,
which enables us to eliminate the heavy startup cost of Minecraft servers, the server bill is substantially minimized, because now it's possible to run servers
on limited hardware like small cloud VMs.
Currently, the focus is only on minigames, but future releases will extend the system for all types of experiences.

**Note**: This is very much still a work in progress project, so technical aspects will possibly change quite often and break things.

Expand All @@ -15,16 +13,10 @@ The next steps are fixing bugs, that come up and investing time into stability a
Here are some examples of things, that are still missing:
* Configurable user limits
* Feature flags
* Improvements on the platformd side (component responsible for actually running the containers)
* Image GC
* TBD
* TBD
* TBD ;)

If there is a concrete roadmap it will be posted on our [Discord](http://discord.chunks.space/).

**Requirements**
* Linux kernel >= 6.6, tcx not supported (caused by `link.AttachTCX`)

**Limitations**
* Only single-platform OCI images can be built, so setups containing both `linux/arm64` and `linux/amd64` hosts is not possible as of now.

Expand All @@ -46,4 +38,4 @@ This installs the latest version of the CLI.
On Windows, use `explorerctl` instead of `explorer`.

## License
This project uses two different licenses: AGPLv3 and LGPLv3. Everything found under under the `api/` folder is licensed under LGPLv3 while everything else is covered by AGPLv3, if not stated otherwise.
This project uses two different licenses: AGPLv3 and LGPLv3. Everything found under the `api/` folder is licensed under LGPLv3 while everything else is covered by AGPLv3, if not stated otherwise.
8 changes: 8 additions & 0 deletions cmd/controlplane/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ func main() {
imagePlatform = fs.String("image-platform", "linux/amd64", "the platform that will be specified when pulling the base image. must match with all configured platformd hosts e.g. linux/amd64") //nolint:lll
checkJobTimeout = fs.Duration("checkpoint-job-timeout", 5*time.Minute, "when to abort the checkpointing job") //nolint:lll
checkStatusCheckInterval = fs.Duration("checkpoint-status-check-interval", 3*time.Second, "how often the status check endpoint for a checkpoint should be called") //nolint:lll
serverAPIEndpoint = fs.String("server-api-endpoint", "", "base url of the control plane server api used to manage minigame servers") //nolint:lll
instanceJobTimeout = fs.Duration("instance-job-timeout", 5*time.Minute, "when to abort the create instance job") //nolint:lll
instanceStatusInterval = fs.Duration("instance-status-check-interval", 3*time.Second, "how often the server status should be checked while creating an instance") //nolint:lll
bucket = fs.String("bucket", "explorer-data", "bucket to use for storing change sets and backend for content-addressable storage") //nolint:lll
accessKey = fs.String("access-key", "", "access key to use for accessing the bucket") //nolint:lll
secretKey = fs.String("secret-key", "", "secret key to use for accessing the bucket") //nolint:lll
Expand All @@ -72,6 +75,7 @@ func main() {
packTextureDir = fs.String("resource-pack-texture-dir", "", "path inside the resource pack to the directory where the textures will live. e.g. assets/mynamespace/textures/item") //nolint:lll
changeSetTarballMaxSize = fs.Uint64("change-set-tarball-max-size", 1073741824, "the maximum allowed size in bytes of the change set tarball") //nolint:lll
archiveInterval = fs.Duration("archive-interval", 3*time.Minute, "in what interval the deleted chunks and flavors should be archived") //nolint:lll
checkInstancesInterval = fs.Duration("check-instances-interval", 3*time.Minute, "in what interval running instances are checked against the server api") //nolint:lll
disableTracing = fs.Bool("disable-tracing", false, "disable open telemetry tracing") //nolint:lll
)
if err := ff.Parse(fs, os.Args[1:],
Expand All @@ -95,6 +99,9 @@ func main() {
ImagePlatform: *imagePlatform,
CheckpointJobTimeout: *checkJobTimeout,
CheckpointStatusCheckInterval: *checkStatusCheckInterval,
ServerAPIEndpoint: *serverAPIEndpoint,
InstanceJobTimeout: *instanceJobTimeout,
InstanceStatusCheckInterval: *instanceStatusInterval,
Bucket: *bucket,
AccessKey: *accessKey,
SecretKey: *secretKey,
Expand All @@ -114,6 +121,7 @@ func main() {
ResourcePackTextureDir: *packTextureDir,
ChangeSetTarballMaxSizeBytes: *changeSetTarballMaxSize,
ArchiveInterval: *archiveInterval,
CheckInstancesInterval: *checkInstancesInterval,
DisableTracing: *disableTracing,
}
ctx = context.Background()
Expand Down
218 changes: 218 additions & 0 deletions cmd/rebuildimages/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
/*
Explorer Platform, a platform for hosting and discovering Minecraft servers.
Copyright (C) 2024 Yannic Rieger <oss@76k.io>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

package main

import (
"context"
"flag"
"fmt"
"log/slog"
"os"

"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/riverqueue/river"
"github.com/riverqueue/river/riverdriver/riverpgxv5"
"github.com/spacechunks/explorer/controlplane/job"
"github.com/spacechunks/explorer/controlplane/postgres"
"github.com/spacechunks/explorer/internal/resource"
)

// noopCreateImageWorker exists only to satisfy river's requirement that a
// job kind be registered before it can be inserted. it is never actually
// run, since the client it's registered on is never started.
type noopCreateImageWorker struct {
river.WorkerDefaults[job.CreateImage]
}

func (*noopCreateImageWorker) Work(context.Context, *river.Job[job.CreateImage]) error {
return nil
}

type flavorVersion struct {
FlavorVersionID string
FlavorID string
FlavorName string
ChunkID string
ChunkName string
BaseImageURL string
}

func main() {
var (
logger = slog.New(slog.NewTextHandler(os.Stdout, nil))
fs = flag.NewFlagSet("rebuildimages", flag.ContinueOnError)
pgConnString = fs.String("postgres-dsn", "", "connection string in the form of postgres://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]") //nolint:lll
ociRegistry = fs.String("oci-registry", "", "registry to push the rebuilt images to")
flavorID = fs.String("flavor-id", "", "only rebuild versions belonging to this flavor. mutually exclusive with -flavor-version-id") //nolint:lll
flavorVersionID = fs.String("flavor-version-id", "", "only rebuild this specific flavor version. mutually exclusive with -flavor-id") //nolint:lll
)

if err := fs.Parse(os.Args[1:]); err != nil {
die(logger, "failed to parse flags", err)
}

if *pgConnString == "" {
die(logger, "postgres-dsn is required", nil)
}

if *ociRegistry == "" {
die(logger, "oci-registry is required", nil)
}

if *flavorID != "" && *flavorVersionID != "" {
die(logger, "-flavor-id and -flavor-version-id are mutually exclusive", nil)
}

ctx := context.Background()

pool, err := pgxpool.New(ctx, *pgConnString)
if err != nil {
die(logger, "failed to connect to database", err)
}
defer pool.Close()

// an insert-only river client. it is never started, so no queues need
// to be configured and the registered worker is never actually run.
// river just requires the job kind to be registered before it can be
// inserted. the control plane's own create_image worker is what picks
// up and processes the jobs enqueued below.
workers := river.NewWorkers()
if err := river.AddWorkerSafely[job.CreateImage](workers, &noopCreateImageWorker{}); err != nil {
die(logger, "failed to register worker", err)
}

riverClient, err := river.NewClient(riverpgxv5.New(pool), &river.Config{
Workers: workers,
})
if err != nil {
die(logger, "failed to create river client", err)
}

db := postgres.NewDB(logger, pool)
db.SetRiverClient(riverClient)

versions, err := listFlavorVersions(ctx, pool, *flavorID, *flavorVersionID)
if err != nil {
die(logger, "failed to list flavor versions", err)
}

logger.Info("found flavor versions to rebuild", "count", len(versions))

for _, v := range versions {
if err := db.InsertJob(ctx, v.FlavorVersionID, string(resource.FlavorVersionBuildStatusBuildImage), job.CreateImage{
FlavorVersionID: v.FlavorVersionID,
BaseImage: v.BaseImageURL,
OCIRegistry: *ociRegistry,
ChunkID: v.ChunkID,
ChunkName: v.ChunkName,
FlavorID: v.FlavorID,
FlavorName: v.FlavorName,
}); err != nil {
logger.Error(
"failed to enqueue image rebuild",
"flavor_version_id", v.FlavorVersionID,
"chunk_name", v.ChunkName,
"flavor_name", v.FlavorName,
"err", err,
)
continue
}

logger.Info(
"enqueued image rebuild",
"flavor_version_id", v.FlavorVersionID,
"chunk_name", v.ChunkName,
"flavor_name", v.FlavorName,
)
}
}

// listFlavorVersions returns every flavor version matching the given
// filters. passing an empty string for flavorID or flavorVersionID means
// "don't filter on this".
func listFlavorVersions(
ctx context.Context,
pool *pgxpool.Pool,
flavorID string,
flavorVersionID string,
) ([]flavorVersion, error) {
rows, err := pool.Query(ctx, `
SELECT
v.id,
f.id,
f.name,
c.id,
c.name,
mv.image_url
FROM flavor_versions v
JOIN flavors f ON f.id = v.flavor_id
JOIN chunks c ON c.id = f.chunk_id
JOIN minecraft_versions mv ON mv.version = v.minecraft_version
WHERE v.files_uploaded = true
AND f.deleted_at IS NULL
AND c.deleted_at IS NULL
AND (@flavor_id::uuid IS NULL OR f.id = @flavor_id::uuid)
AND (@flavor_version_id::uuid IS NULL OR v.id = @flavor_version_id::uuid)
ORDER BY v.id
`, pgx.NamedArgs{
"flavor_id": nullIfEmpty(flavorID),
"flavor_version_id": nullIfEmpty(flavorVersionID),
})
if err != nil {
return nil, fmt.Errorf("query flavor versions: %w", err)
}
defer rows.Close()

var versions []flavorVersion
for rows.Next() {
var v flavorVersion
if err := rows.Scan(
&v.FlavorVersionID,
&v.FlavorID,
&v.FlavorName,
&v.ChunkID,
&v.ChunkName,
&v.BaseImageURL,
); err != nil {
return nil, fmt.Errorf("scan flavor version: %w", err)
}
versions = append(versions, v)
}

if err := rows.Err(); err != nil {
return nil, err
}

return versions, nil
}

// nullIfEmpty returns nil for an empty string, so it can be used as a
// "no filter" value for a nullable query parameter.
func nullIfEmpty(s string) *string {
if s == "" {
return nil
}
return &s
}

func die(logger *slog.Logger, msg string, err error) {
logger.Error(msg, "err", err)
os.Exit(1)
}
4 changes: 4 additions & 0 deletions controlplane/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ type Config struct {
ImagePlatform string
CheckpointJobTimeout time.Duration
CheckpointStatusCheckInterval time.Duration
ServerAPIEndpoint string
InstanceJobTimeout time.Duration
InstanceStatusCheckInterval time.Duration
Bucket string
AccessKey string
SecretKey string
Expand All @@ -52,5 +55,6 @@ type Config struct {
ResourcePackTextureDir string
ChangeSetTarballMaxSizeBytes uint64
ArchiveInterval time.Duration
CheckInstancesInterval time.Duration
DisableTracing bool
}
14 changes: 12 additions & 2 deletions controlplane/instance/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,20 @@ import (
)

type Repository interface {
CreateInstance(ctx context.Context, instance resource.Instance, nodeID string) (resource.Instance, error)
CreateInstance(ctx context.Context, instance resource.Instance) (resource.Instance, error)
ListInstances(ctx context.Context, pageSize int, afterID *string) ([]resource.Instance, error)
GetInstanceByID(ctx context.Context, id string) (resource.Instance, error)
GetInstancesByNodeID(ctx context.Context, id string) ([]resource.Instance, error)

// UpdateInstance updates the address and port of the instance with the given id.
UpdateInstance(ctx context.Context, id string, address string, port uint16) error

// UpdateInstanceServerID updates the server id of the instance with the given id.
UpdateInstanceServerID(ctx context.Context, id string, serverID string) error

// ListRunningInstancesWithServerID returns the id and server id of all
// instances that are in [resource.InstanceStateRunning] state and have
// a server id assigned.
ListRunningInstancesWithServerID(ctx context.Context) ([]resource.InstanceServerRef, error)

// ApplyStatusReports updates instances rows that are not in [instance.InstanceStateDeleted] state.
// all other instances will be removed from the table.
Expand Down
23 changes: 0 additions & 23 deletions controlplane/instance/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,29 +105,6 @@ func (s *Server) RunFlavorVersion(
}, nil
}

func (s *Server) DiscoverInstances(
ctx context.Context,
req *instancev1alpha1.DiscoverInstanceRequest,
) (*instancev1alpha1.DiscoverInstanceResponse, error) {
if req.GetNodeKey() == "" {
return nil, apierrs.ErrNodeKeyMissing
}

instances, err := s.service.DiscoverInstances(ctx, req.GetNodeKey())
if err != nil {
return nil, fmt.Errorf("discovering instances: %w", err)
}

ret := make([]*instancev1alpha1.Instance, 0, len(instances))
for _, ins := range instances {
ret = append(ret, codec.InstanceToTransport(ins))
}

return &instancev1alpha1.DiscoverInstanceResponse{
Instances: ret,
}, nil
}

func (s *Server) ReceiveInstanceStatusReports(
ctx context.Context,
req *instancev1alpha1.ReceiveInstanceStatusReportsRequest,
Expand Down
Loading