Skip to content

Commit

Permalink
feat: move from sqlite to json for data storage
Browse files Browse the repository at this point in the history
  • Loading branch information
DeeStarks committed Aug 13, 2022
1 parent bd44d23 commit 87f9c2a
Show file tree
Hide file tree
Showing 17 changed files with 222 additions and 427 deletions.
28 changes: 6 additions & 22 deletions app/cli/cli.go
Original file line number Diff line number Diff line change
@@ -1,29 +1,13 @@
package cli

import (
"database/sql"

"github.com/DeeStarks/conoid/config"
"github.com/DeeStarks/conoid/utils"
_ "github.com/mattn/go-sqlite3"
type (
ICLICommands interface {
Services() *ServiceCommand
}
CLICommands struct{}
)

type ICLICommands interface {
Services() *ServiceCommand
}

type CLICommands struct {
defaultDB *sql.DB
}

// Accept and process CLI commands.
func NewCLICommands() ICLICommands {
// Connect to the default db
defaultDB, err := sql.Open("sqlite3", config.DEFAULT_DB)
if err != nil {
utils.Log("Could not connect DB:", err)
}
return &CLICommands{
defaultDB: defaultDB,
}
return &CLICommands{}
}
78 changes: 36 additions & 42 deletions app/cli/services.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package cli

import (
"database/sql"
"encoding/json"
"fmt"
"os"
Expand All @@ -11,25 +10,20 @@ import (
port "github.com/DeeStarks/conoid/domain/ports"
"github.com/DeeStarks/conoid/utils"
"github.com/aquasecurity/table"
"github.com/google/uuid"
)

type ServiceCommand struct {
defaultDB *sql.DB
}
type ServiceCommand struct{}

func (cmd *CLICommands) Services() *ServiceCommand {
return &ServiceCommand{
defaultDB: cmd.defaultDB,
}
return &ServiceCommand{}
}

type ServiceProcess struct {
Pid string
Name string
Status string
Type string
Listeners []string
Listeners []interface{}
RootDirectory string
RemoteServer string
Tunnelled bool
Expand All @@ -38,10 +32,10 @@ type ServiceProcess struct {

// List running services
func (c *ServiceCommand) ListRunning() {
domainPort := port.NewDomainPort(c.defaultDB)
domainPort := port.NewDomainPort()
processes, err := domainPort.ServiceProcesses().RetrieveRunning()
if err != nil {
fmt.Println("Error retrieve running services:", err)
fmt.Println("Error retrieving running services:", err)
return
}

Expand All @@ -52,7 +46,12 @@ func (c *ServiceCommand) ListRunning() {
t.SetHeaders("NAME", "TYPE", "LISTENING ON", "ROOT", "REMOTE ADDRESS", "TUNNELLED", "CREATED")
for _, p := range processes {
created_at := utils.TimeAgo(p.CreatedAt, time.Now().Unix())
listeners := strings.Join(p.Listeners, ", ")

assertListeners := make([]string, len(p.Listeners))
for i, l := range p.Listeners {
assertListeners[i] = l.(string)
}
listeners := strings.Join(assertListeners, ", ")

// Handle booleans
tunnelled := "False"
Expand All @@ -72,7 +71,7 @@ func (c *ServiceCommand) ListRunning() {

// List all services
func (c *ServiceCommand) ListAll() {
domainPort := port.NewDomainPort(c.defaultDB)
domainPort := port.NewDomainPort()
processes, err := domainPort.ServiceProcesses().RetrieveAll()
if err != nil {
fmt.Println("Error retrieving services:", err)
Expand All @@ -86,7 +85,12 @@ func (c *ServiceCommand) ListAll() {
t.SetHeaders("NAME", "STATUS", "TYPE", "LISTENING ON", "ROOT", "REMOTE ADDRESS", "TUNNELLED", "CREATED")
for _, p := range processes {
created_at := utils.TimeAgo(p.CreatedAt, time.Now().Unix())
listeners := strings.Join(p.Listeners, ", ")

assertListeners := make([]string, len(p.Listeners))
for i, l := range p.Listeners {
assertListeners[i] = l.(string)
}
listeners := strings.Join(assertListeners, ", ")

// Handle booleans
tunnelled := "False"
Expand Down Expand Up @@ -117,7 +121,7 @@ func (c *ServiceCommand) Add(conf utils.AppConf, update bool) {
}

// Ensure service doesn't already exist
domainPort := port.NewDomainPort(c.defaultDB)
domainPort := port.NewDomainPort()
processes, err := domainPort.ServiceProcesses().RetrieveAll()
if err != nil {
fmt.Println(err)
Expand Down Expand Up @@ -156,26 +160,8 @@ func (c *ServiceCommand) Add(conf utils.AppConf, update bool) {
var mapConf map[string]interface{}
json.Unmarshal(jsondata, &mapConf)

// Change the "tunnelled" field from boolean type to int
if mapConf["tunnelled"].(bool) {
mapConf["tunnelled"] = 1
} else {
mapConf["tunnelled"] = 0
}

// Join the "listeners" slice and save in the database as string type
if s, ok := mapConf["listeners"].([]interface{}); ok {
ss := make([]string, len(s))
for i, v := range s {
ss[i] = fmt.Sprintf("%v", v)
}
mapConf["listeners"] = strings.Join(ss, ", ")
}

if !update {
// Generate pid, status, and created at
mapConf["pid"] = strings.ReplaceAll(uuid.New().String(), "-", "") // Stripping hyphens
mapConf["status"] = 1
mapConf["status"] = true
mapConf["created_at"] = time.Now().Unix()

_, err = domainPort.ServiceProcesses().Create(mapConf)
Expand All @@ -198,10 +184,10 @@ func (c *ServiceCommand) Add(conf utils.AppConf, update bool) {
// Retrieve details of a servive
func (c *ServiceCommand) Get(name string) {
// Retrieve from db
domainPort := port.NewDomainPort(c.defaultDB)
domainPort := port.NewDomainPort()
service, err := domainPort.ServiceProcesses().Get(name)
if err != nil {
fmt.Printf("Could not retrieve service: \"%s\"\n", name)
fmt.Println(err)
return
}

Expand All @@ -215,13 +201,20 @@ func (c *ServiceCommand) Get(name string) {
status = "Running"
}

// Type assertion on the service listeners: interface{} -> string
assertListeners := make([]string, len(service.Listeners))
for i, l := range service.Listeners {
assertListeners[i] = l.(string)
}
listeners := strings.Join(assertListeners, ", ")

// Show table
t := table.New(os.Stdout)
t.SetDividers(table.UnicodeDividers)
t.AddRow("NAME", service.Name)
t.AddRow("STATUS", status)
t.AddRow("TYPE", strings.Title(service.Type)+" rendering")
t.AddRow("SERVING FROM", strings.Join(service.Listeners, ", "))
t.AddRow("SERVING FROM", listeners)
if service.Type == "static" {
t.AddRow("DOCUMENT ROOT", service.RootDirectory)
}
Expand All @@ -234,7 +227,7 @@ func (c *ServiceCommand) Get(name string) {
// Start a stopped servive
func (c *ServiceCommand) Start(name string) {
// Retrieve from db
domainPort := port.NewDomainPort(c.defaultDB)
domainPort := port.NewDomainPort()
service, err := domainPort.ServiceProcesses().Get(name)
if err != nil {
fmt.Printf("No such service: \"%s\"\n", name)
Expand All @@ -249,7 +242,7 @@ func (c *ServiceCommand) Start(name string) {

// Change status
_, err = domainPort.ServiceProcesses().Update(name, map[string]interface{}{
"status": 1,
"status": true,
})
if err != nil {
panic(err)
Expand All @@ -260,7 +253,7 @@ func (c *ServiceCommand) Start(name string) {
// Stop a running servive
func (c *ServiceCommand) Stop(name string) {
// Retrieve from db
domainPort := port.NewDomainPort(c.defaultDB)
domainPort := port.NewDomainPort()
service, err := domainPort.ServiceProcesses().Get(name)
if err != nil {
fmt.Printf("No such service: \"%s\"\n", name)
Expand All @@ -275,10 +268,11 @@ func (c *ServiceCommand) Stop(name string) {

// Change status
_, err = domainPort.ServiceProcesses().Update(name, map[string]interface{}{
"status": 0,
"status": false,
})
if err != nil {
panic(err)
fmt.Println("Error:", err)
return
}
fmt.Println("Service stopped")
}
8 changes: 2 additions & 6 deletions app/server.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package app

import (
"database/sql"
"fmt"
"io"
"net"
Expand All @@ -10,24 +9,21 @@ import (
"github.com/DeeStarks/conoid/app/tools"
"github.com/DeeStarks/conoid/config"
"github.com/DeeStarks/conoid/utils"
_ "github.com/mattn/go-sqlite3"
)

type Server struct {
services IServices
defaultDB *sql.DB
host string
port string
openConns chan<- net.Conn
}

func NewServer(connCh chan<- net.Conn, defaultDB *sql.DB) *Server {
func NewServer(connCh chan<- net.Conn) *Server {
// initialize and start running Services
services := InitServices(defaultDB)
services := InitServices()

return &Server{
services: services,
defaultDB: defaultDB,
openConns: connCh,
}
}
Expand Down
21 changes: 9 additions & 12 deletions app/services.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package app

import (
"database/sql"
"fmt"
"net"
"net/http"
Expand All @@ -17,8 +16,7 @@ type (
RunningServices map[string][]string

Services struct {
running RunningServices
defaultDB *sql.DB
running RunningServices
}

IServices interface {
Expand All @@ -30,10 +28,9 @@ type (
}
)

func InitServices(defaultDB *sql.DB) IServices {
func InitServices() IServices {
return &Services{
running: RunningServices{},
defaultDB: defaultDB,
running: RunningServices{},
}
}

Expand All @@ -45,7 +42,7 @@ func (s *Services) ServeServices(conoidHost, conoidPort string, connCh chan<- ne
s.running[fmt.Sprintf("%s:%s", conoidHost, conoidPort)] = []string{fmt.Sprintf("%s:%s", welcomeHost, welcomePort)}

// Serve registered running services
dbPort := port.NewDomainPort(s.defaultDB)
dbPort := port.NewDomainPort()
services, err := dbPort.ServiceProcesses().RetrieveRunning()
if err != nil {
utils.Log("Could not serve:", err)
Expand All @@ -62,7 +59,7 @@ func (s *Services) ServeServices(conoidHost, conoidPort string, connCh chan<- ne
host, port := s.ServeStatic(service.RootDirectory, portNo)
addr := fmt.Sprintf("%s:%s", host, port)
_, err := dbPort.ServiceProcesses().Update(service.Name, map[string]interface{}{
"listeners": addr,
"listeners": []string{addr},
})
if err != nil {
utils.Log("Could not update service state:", err)
Expand All @@ -73,17 +70,17 @@ func (s *Services) ServeServices(conoidHost, conoidPort string, connCh chan<- ne
servers := []string{}
// Connect to all listening servers
for _, addr := range service.Listeners {
_, err := s.ConnectToServer(addr)
_, err := s.ConnectToServer(addr.(string))
if err != nil {
utils.Logf("Could not connect to \"%s\" at: %s; Stopping...\n", service.Name, addr)
// Update service state
dbPort.ServiceProcesses().Update(service.Name, map[string]interface{}{
"status": 0,
"status": false,
})
continue
}
// Append servers to listening servers
servers = append(servers, addr)
servers = append(servers, addr.(string))
}
serverAddrs = servers
}
Expand All @@ -108,7 +105,7 @@ func (s *Services) ServeServices(conoidHost, conoidPort string, connCh chan<- ne

// Update service's remote_server
_, err = dbPort.ServiceProcesses().Update(service.Name, map[string]interface{}{
"remote_server": host.FullURL(),
"server": host.FullURL(),
})
if err != nil {
panic(err)
Expand Down
11 changes: 2 additions & 9 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package cmd

import (
"database/sql"
"fmt"
"net"
"os"
Expand All @@ -28,15 +27,9 @@ var (
return
}

// Connect to the default db
defaultDB, err := sql.Open("sqlite3", config.DEFAULT_DB)
if err != nil {
panic(err)
}

// Get the number of services that are tunnelled
var tunnelled int
rec, err := port.NewDomainPort(defaultDB).ServiceProcesses().RetrieveRunning()
rec, err := port.NewDomainPort().ServiceProcesses().RetrieveRunning()
if err != nil {
panic(err)
}
Expand All @@ -55,7 +48,7 @@ var (

// Start server if no argumentss were passed or the first argument is "up"
if len(args) <= 0 || args[0] == "start" {
go app.NewServer(openConnsCh, defaultDB).Serve()
go app.NewServer(openConnsCh).Serve()
}

// We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)
Expand Down
Loading

0 comments on commit 87f9c2a

Please sign in to comment.