mirror of
https://github.com/aljazceru/nigiri.git
synced 2026-02-23 07:14:29 +01:00
Changes for new version of esplora image (#62)
* changes for new version of esplora image * add electrs port and esplora url env vars in compose yaml files * wrap viper methods into Config type and use constants package * add controller to interact with nigiri resources: * .env for docker-compose * docker daemon * json config file * add use of constants and config packages and change start flag from --port to --env * add package for global constants and variables * add use of controller and constants packages instead of local methods and vars * bump version * use contants in logs command tests
This commit is contained in:
committed by
Marco Argentieri
parent
d0b3676c14
commit
e02c2fdd0d
@@ -3,12 +3,11 @@ package cmd
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/mitchellh/go-homedir"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/vulpemventures/nigiri/cli/config"
|
||||
"github.com/vulpemventures/nigiri/cli/constants"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -18,38 +17,25 @@ var (
|
||||
flagAttachLiquid bool
|
||||
flagLiquidService bool
|
||||
flagEnv string
|
||||
|
||||
defaultPorts = map[string]map[string]int{
|
||||
"bitcoin": {
|
||||
"node": 18443,
|
||||
"electrs_rpc": 60401,
|
||||
"chopsticks": 3000,
|
||||
"esplora": 5000,
|
||||
},
|
||||
"liquid": {
|
||||
"node": 7041,
|
||||
"electrs_rpc": 51401,
|
||||
"chopsticks": 3001,
|
||||
"esplora": 5001,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
var RootCmd = &cobra.Command{
|
||||
Use: "nigiri",
|
||||
Short: "Nigiri lets you manage a full dockerized bitcoin environment",
|
||||
Long: "Nigiri lets you create your dockerized environment with a bitcoin and optionally a liquid node + block explorer powered by an electrum server for every network",
|
||||
Version: "0.0.3",
|
||||
Version: "0.0.4",
|
||||
}
|
||||
|
||||
func init() {
|
||||
defaultDir := getDefaultDir()
|
||||
ports, _ := json.Marshal(defaultPorts)
|
||||
c := &config.Config{}
|
||||
viper := c.Viper()
|
||||
defaultDir := c.GetPath()
|
||||
defaultJSON, _ := json.Marshal(constants.DefaultEnv)
|
||||
|
||||
RootCmd.PersistentFlags().StringVar(&flagDatadir, "datadir", defaultDir, "Set nigiri default directory")
|
||||
StartCmd.PersistentFlags().StringVar(&flagNetwork, "network", "regtest", "Set bitcoin network - regtest only for now")
|
||||
StartCmd.PersistentFlags().BoolVar(&flagAttachLiquid, "liquid", false, "Enable liquid sidechain")
|
||||
StartCmd.PersistentFlags().StringVar(&flagEnv, "ports", string(ports), "Set services ports in JSON format")
|
||||
StartCmd.PersistentFlags().StringVar(&flagEnv, "env", string(defaultJSON), "Set compose env in JSON format")
|
||||
StopCmd.PersistentFlags().BoolVar(&flagDelete, "delete", false, "Stop and delete nigiri")
|
||||
LogsCmd.PersistentFlags().BoolVar(&flagLiquidService, "liquid", false, "Set to see logs of a liquid service")
|
||||
|
||||
@@ -57,18 +43,12 @@ func init() {
|
||||
RootCmd.AddCommand(StopCmd)
|
||||
RootCmd.AddCommand(LogsCmd)
|
||||
|
||||
viper := config.Viper()
|
||||
viper.BindPFlag(config.Datadir, RootCmd.PersistentFlags().Lookup("datadir"))
|
||||
viper.BindPFlag(config.Network, StartCmd.PersistentFlags().Lookup("network"))
|
||||
viper.BindPFlag(config.AttachLiquid, StartCmd.PersistentFlags().Lookup("liquid"))
|
||||
viper.BindPFlag(constants.Datadir, RootCmd.PersistentFlags().Lookup("datadir"))
|
||||
viper.BindPFlag(constants.Network, StartCmd.PersistentFlags().Lookup("network"))
|
||||
viper.BindPFlag(constants.AttachLiquid, StartCmd.PersistentFlags().Lookup("liquid"))
|
||||
|
||||
cobra.OnInitialize(func() {
|
||||
log.SetOutput(os.Stdout)
|
||||
log.SetLevel(log.InfoLevel)
|
||||
})
|
||||
}
|
||||
|
||||
func getDefaultDir() string {
|
||||
home, _ := homedir.Expand("~")
|
||||
return filepath.Join(home, ".nigiri")
|
||||
}
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"reflect"
|
||||
|
||||
"github.com/vulpemventures/nigiri/cli/config"
|
||||
"github.com/vulpemventures/nigiri/cli/constants"
|
||||
"github.com/vulpemventures/nigiri/cli/controller"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
@@ -18,42 +17,39 @@ var LogsCmd = &cobra.Command{
|
||||
PreRunE: logsChecks,
|
||||
}
|
||||
|
||||
var services = map[string]bool{
|
||||
"node": true,
|
||||
"electrs": true,
|
||||
"esplora": true,
|
||||
"chopsticks": true,
|
||||
}
|
||||
|
||||
func logsChecks(cmd *cobra.Command, args []string) error {
|
||||
datadir, _ := cmd.Flags().GetString("datadir")
|
||||
isLiquidService, _ := cmd.Flags().GetBool("liquid")
|
||||
|
||||
if !isDatadirOk(datadir) {
|
||||
return fmt.Errorf("Invalid datadir, it must be an absolute path: %s", datadir)
|
||||
}
|
||||
if len(args) != 1 {
|
||||
return fmt.Errorf("Invalid number of args, expected 1, got: %d", len(args))
|
||||
}
|
||||
|
||||
service := args[0]
|
||||
if !services[service] {
|
||||
return fmt.Errorf("Invalid service, must be one of %s. Got: %s", reflect.ValueOf(services).MapKeys(), service)
|
||||
}
|
||||
isRunning, err := nigiriIsRunning()
|
||||
ctl, err := controller.NewController()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !isRunning {
|
||||
return fmt.Errorf("Nigiri is not running")
|
||||
|
||||
if err := ctl.ParseDatadir(datadir); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(args) != 1 {
|
||||
return constants.ErrInvalidArgs
|
||||
}
|
||||
|
||||
if err := config.ReadFromFile(datadir); err != nil {
|
||||
service := args[0]
|
||||
if err := ctl.ParseServiceName(service); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if isLiquidService && isLiquidService != config.GetBool(config.AttachLiquid) {
|
||||
return fmt.Errorf("Nigiri has been started with no Liquid sidechain.\nPlease stop and restart it using the --liquid flag")
|
||||
if isRunning, err := ctl.IsNigiriRunning(); err != nil {
|
||||
return err
|
||||
} else if !isRunning {
|
||||
return constants.ErrNigiriNotRunning
|
||||
}
|
||||
|
||||
if err := ctl.ReadConfigFile(datadir); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if isLiquidService && isLiquidService != ctl.GetConfigBoolField(constants.AttachLiquid) {
|
||||
return constants.ErrNigiriLiquidNotEnabled
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -64,10 +60,15 @@ func logs(cmd *cobra.Command, args []string) error {
|
||||
datadir, _ := cmd.Flags().GetString("datadir")
|
||||
isLiquidService, _ := cmd.Flags().GetBool("liquid")
|
||||
|
||||
serviceName := getServiceName(service, isLiquidService)
|
||||
composePath := getPath(datadir, "compose")
|
||||
envPath := getPath(datadir, "env")
|
||||
env := loadEnv(envPath)
|
||||
ctl, err := controller.NewController()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
serviceName := ctl.GetServiceName(service, isLiquidService)
|
||||
composePath := ctl.GetResourcePath(datadir, "compose")
|
||||
envPath := ctl.GetResourcePath(datadir, "env")
|
||||
env := ctl.LoadComposeEnvironment(envPath)
|
||||
|
||||
bashCmd := exec.Command("docker-compose", "-f", composePath, "logs", serviceName)
|
||||
bashCmd.Stdout = os.Stdout
|
||||
@@ -80,19 +81,3 @@ func logs(cmd *cobra.Command, args []string) error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func getServiceName(name string, liquid bool) string {
|
||||
service := name
|
||||
if service == "node" {
|
||||
service = "bitcoin"
|
||||
}
|
||||
if liquid {
|
||||
if service == "bitcoin" {
|
||||
service = "liquid"
|
||||
} else {
|
||||
service = fmt.Sprintf("%s-liquid", service)
|
||||
}
|
||||
}
|
||||
|
||||
return service
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package cmd
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/vulpemventures/nigiri/cli/constants"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -41,7 +43,7 @@ func TestLogLiquidServices(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestLogShouldFail(t *testing.T) {
|
||||
expectedError := "Nigiri is not running"
|
||||
expectedError := constants.ErrNigiriNotRunning.Error()
|
||||
|
||||
err := testCommand("logs", serviceList[0], bitcoin)
|
||||
if err == nil {
|
||||
@@ -65,7 +67,7 @@ func TestStartBitcoinAndLogNigiriServicesShouldFail(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
expectedError := "Nigiri has been started with no Liquid sidechain.\nPlease stop and restart it using the --liquid flag"
|
||||
expectedError := constants.ErrNigiriLiquidNotEnabled.Error()
|
||||
|
||||
err := testCommand("logs", serviceList[0], liquid)
|
||||
if err == nil {
|
||||
|
||||
327
cli/cmd/start.go
327
cli/cmd/start.go
@@ -1,25 +1,16 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/vulpemventures/nigiri/cli/config"
|
||||
"github.com/docker/docker/api/types"
|
||||
"github.com/docker/docker/client"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/vulpemventures/nigiri/cli/constants"
|
||||
"github.com/vulpemventures/nigiri/cli/controller"
|
||||
)
|
||||
|
||||
const listAll = true
|
||||
|
||||
var StartCmd = &cobra.Command{
|
||||
Use: "start",
|
||||
Short: "Build and start Nigiri",
|
||||
@@ -30,27 +21,30 @@ var StartCmd = &cobra.Command{
|
||||
func startChecks(cmd *cobra.Command, args []string) error {
|
||||
network, _ := cmd.Flags().GetString("network")
|
||||
datadir, _ := cmd.Flags().GetString("datadir")
|
||||
ports, _ := cmd.Flags().GetString("ports")
|
||||
env, _ := cmd.Flags().GetString("env")
|
||||
|
||||
// check flags
|
||||
if !isNetworkOk(network) {
|
||||
return fmt.Errorf("Invalid network: %s", network)
|
||||
}
|
||||
|
||||
if !isDatadirOk(datadir) {
|
||||
return fmt.Errorf("Invalid datadir, it must be an absolute path: %s", datadir)
|
||||
}
|
||||
if !isEnvOk(ports) {
|
||||
return fmt.Errorf("Invalid env JSON, it must contain a \"bitcoin\" object with at least one service specified. It can optionally contain a \"liquid\" object with at least one service specified.\nGot: %s", ports)
|
||||
}
|
||||
|
||||
// if nigiri is already running return error
|
||||
isRunning, err := nigiriIsRunning()
|
||||
ctl, err := controller.NewController()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if isRunning {
|
||||
return fmt.Errorf("Nigiri is already running, please stop it first")
|
||||
|
||||
if err := ctl.ParseNetwork(network); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := ctl.ParseDatadir(datadir); err != nil {
|
||||
return err
|
||||
}
|
||||
composeEnv, err := ctl.ParseEnv(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// if nigiri is already running return error
|
||||
if isRunning, err := ctl.IsNigiriRunning(); err != nil {
|
||||
return err
|
||||
} else if isRunning {
|
||||
return constants.ErrNigiriAlreadyRunning
|
||||
}
|
||||
|
||||
// scratch datadir if not exists
|
||||
@@ -60,65 +54,77 @@ func startChecks(cmd *cobra.Command, args []string) error {
|
||||
|
||||
// if datadir is set we must copy the resources directory from ~/.nigiri
|
||||
// to the new one
|
||||
if datadir != getDefaultDir() {
|
||||
if err := copyResources(datadir); err != nil {
|
||||
if datadir != ctl.GetDefaultDatadir() {
|
||||
if err := ctl.NewDatadirFromDefault(datadir); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// if nigiri not exists, we need to write the configuration file and then
|
||||
// read from it to get viper updated, otherwise we just read from it.
|
||||
exists, err := nigiriExistsAndNotRunning()
|
||||
if err != nil {
|
||||
if isStopped, err := ctl.IsNigiriStopped(); err != nil {
|
||||
return err
|
||||
}
|
||||
if !exists {
|
||||
filedir := getPath(datadir, "config")
|
||||
if err := config.WriteConfig(filedir); err != nil {
|
||||
} else if isStopped {
|
||||
if err := ctl.ReadConfigFile(datadir); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
filedir := ctl.GetResourcePath(datadir, "config")
|
||||
if err := ctl.WriteConfigFile(filedir); err != nil {
|
||||
return err
|
||||
}
|
||||
// .env must be in the directory where docker-compose is run from, not where YAML files are placed
|
||||
// https://docs.docker.com/compose/env-file/
|
||||
filedir = getPath(datadir, "env")
|
||||
if err := writeComposeEnvFile(filedir, ports); err != nil {
|
||||
filedir = ctl.GetResourcePath(datadir, "env")
|
||||
if err := ctl.WriteComposeEnvironment(filedir, composeEnv); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := config.ReadFromFile(datadir); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func start(cmd *cobra.Command, args []string) error {
|
||||
datadir, _ := cmd.Flags().GetString("datadir")
|
||||
liquidEnabled, _ := cmd.Flags().GetBool("liquid")
|
||||
|
||||
bashCmd, err := getStartBashCmd(datadir)
|
||||
ctl, err := controller.NewController()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
datadir, _ := cmd.Flags().GetString("datadir")
|
||||
liquidEnabled := ctl.GetConfigBoolField(constants.AttachLiquid)
|
||||
|
||||
envPath := ctl.GetResourcePath(datadir, "env")
|
||||
composePath := ctl.GetResourcePath(datadir, "compose")
|
||||
|
||||
bashCmd := exec.Command("docker-compose", "-f", composePath, "up", "-d")
|
||||
if isStopped, err := ctl.IsNigiriStopped(); err != nil {
|
||||
return err
|
||||
} else if isStopped {
|
||||
bashCmd = exec.Command("docker-compose", "-f", composePath, "start")
|
||||
}
|
||||
bashCmd.Stdout = os.Stdout
|
||||
bashCmd.Stderr = os.Stderr
|
||||
bashCmd.Env = ctl.LoadComposeEnvironment(envPath)
|
||||
|
||||
if err := bashCmd.Run(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
path := getPath(datadir, "env")
|
||||
ports, err := readComposeEnvFile(path)
|
||||
path := ctl.GetResourcePath(datadir, "env")
|
||||
env, err := ctl.ReadComposeEnvironment(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
prettyPrintServices := func(chain string, services map[string]int) {
|
||||
fmt.Printf("%s services:\n", chain)
|
||||
fmt.Printf("%s services:\n", strings.Title(chain))
|
||||
for name, port := range services {
|
||||
formatName := fmt.Sprintf("%s:", name)
|
||||
fmt.Printf(" %-14s localhost:%d\n", formatName, port)
|
||||
}
|
||||
}
|
||||
|
||||
for chain, services := range ports {
|
||||
for chain, services := range env["ports"].(map[string]map[string]int) {
|
||||
if chain == "bitcoin" {
|
||||
prettyPrintServices(chain, services)
|
||||
} else if liquidEnabled {
|
||||
@@ -128,226 +134,3 @@ func start(cmd *cobra.Command, args []string) error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
var images = map[string]bool{
|
||||
"vulpemventures/bitcoin:latest": true,
|
||||
"vulpemventures/liquid:latest": true,
|
||||
"vulpemventures/electrs:latest": true,
|
||||
"vulpemventures/electrs-liquid:latest": true,
|
||||
"vulpemventures/esplora:latest": true,
|
||||
"vulpemventures/esplora-liquid:latest": true,
|
||||
"vulpemventures/nigiri-chopsticks:latest": true,
|
||||
}
|
||||
|
||||
func copyResources(datadir string) error {
|
||||
defaultDatadir := getDefaultDir()
|
||||
cmd := exec.Command("cp", "-R", filepath.Join(defaultDatadir, "resources"), datadir)
|
||||
return cmd.Run()
|
||||
|
||||
}
|
||||
|
||||
func nigiriExists(listAll bool) (bool, error) {
|
||||
cli, err := client.NewEnvClient()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{All: listAll})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
for _, container := range containers {
|
||||
if images[container.Image] {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func isNetworkOk(network string) bool {
|
||||
var ok bool
|
||||
for _, n := range []string{"regtest"} {
|
||||
if network == n {
|
||||
ok = true
|
||||
}
|
||||
}
|
||||
|
||||
return ok
|
||||
}
|
||||
|
||||
func isDatadirOk(datadir string) bool {
|
||||
return filepath.IsAbs(datadir)
|
||||
}
|
||||
|
||||
func isEnvOk(stringifiedJSON string) bool {
|
||||
var parsedJSON map[string]map[string]int
|
||||
err := json.Unmarshal([]byte(stringifiedJSON), &parsedJSON)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
if len(parsedJSON) <= 0 {
|
||||
return false
|
||||
}
|
||||
if len(parsedJSON["bitcoin"]) <= 0 {
|
||||
return false
|
||||
}
|
||||
if parsedJSON["bitcoin"]["node"] <= 0 &&
|
||||
parsedJSON["bitcoin"]["electrs"] <= 0 &&
|
||||
parsedJSON["bitcoin"]["esplora"] <= 0 &&
|
||||
parsedJSON["bitcoin"]["chopsticks"] <= 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
if len(parsedJSON["liquid"]) > 0 &&
|
||||
parsedJSON["liquid"]["node"] <= 0 &&
|
||||
parsedJSON["liquid"]["electrs"] <= 0 &&
|
||||
parsedJSON["liquid"]["esplora"] <= 0 &&
|
||||
parsedJSON["liquid"]["chopsticks"] <= 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func getPath(datadir, t string) string {
|
||||
viper := config.Viper()
|
||||
|
||||
if t == "compose" {
|
||||
network := viper.GetString("network")
|
||||
attachLiquid := viper.GetBool("attachLiquid")
|
||||
if attachLiquid {
|
||||
network += "-liquid"
|
||||
}
|
||||
return filepath.Join(datadir, "resources", fmt.Sprintf("docker-compose-%s.yml", network))
|
||||
}
|
||||
|
||||
if t == "env" {
|
||||
return filepath.Join(datadir, ".env")
|
||||
}
|
||||
|
||||
if t == "config" {
|
||||
return filepath.Join(datadir, "nigiri.config.json")
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func nigiriIsRunning() (bool, error) {
|
||||
listOnlyRunningContainers := !listAll
|
||||
return nigiriExists(listOnlyRunningContainers)
|
||||
}
|
||||
|
||||
func nigiriExistsAndNotRunning() (bool, error) {
|
||||
return nigiriExists(listAll)
|
||||
}
|
||||
|
||||
func getStartBashCmd(datadir string) (*exec.Cmd, error) {
|
||||
composePath := getPath(datadir, "compose")
|
||||
envPath := getPath(datadir, "env")
|
||||
env := loadEnv(envPath)
|
||||
|
||||
bashCmd := exec.Command("docker-compose", "-f", composePath, "up", "-d")
|
||||
|
||||
isStopped, err := nigiriExistsAndNotRunning()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if isStopped {
|
||||
bashCmd = exec.Command("docker-compose", "-f", composePath, "start")
|
||||
}
|
||||
bashCmd.Stdout = os.Stdout
|
||||
bashCmd.Stderr = os.Stderr
|
||||
bashCmd.Env = env
|
||||
|
||||
return bashCmd, nil
|
||||
}
|
||||
|
||||
func writeComposeEnvFile(path string, stringifiedJSON string) error {
|
||||
defaultJSON, _ := json.Marshal(defaultPorts)
|
||||
env := map[string]map[string]int{}
|
||||
json.Unmarshal([]byte(stringifiedJSON), &env)
|
||||
|
||||
if stringifiedJSON != string(defaultJSON) {
|
||||
env = mergeComposeEnvFiles([]byte(stringifiedJSON))
|
||||
}
|
||||
|
||||
fileContent := ""
|
||||
for chain, services := range env {
|
||||
for k, v := range services {
|
||||
fileContent += fmt.Sprintf("%s_%s_PORT=%d\n", strings.ToUpper(chain), strings.ToUpper(k), v)
|
||||
}
|
||||
}
|
||||
|
||||
return ioutil.WriteFile(path, []byte(fileContent), os.ModePerm)
|
||||
}
|
||||
|
||||
func readComposeEnvFile(path string) (map[string]map[string]int, error) {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
scanner.Split(bufio.ScanLines)
|
||||
|
||||
ports := map[string]map[string]int{
|
||||
"bitcoin": map[string]int{},
|
||||
"liquid": map[string]int{},
|
||||
}
|
||||
// Each line is in the format PREFIX_SERVICE_NAME_SUFFIX=value
|
||||
// PREFIX is either 'BITCOIN' or 'LIQUID', while SUFFIX is always 'PORT'
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
splitLine := strings.Split(line, "=")
|
||||
key := splitLine[0]
|
||||
value, _ := strconv.Atoi(splitLine[1])
|
||||
chain := "bitcoin"
|
||||
if strings.HasPrefix(key, strings.ToUpper("liquid")) {
|
||||
chain = "liquid"
|
||||
}
|
||||
|
||||
suffix := "_PORT"
|
||||
prefix := strings.ToUpper(fmt.Sprintf("%s_", chain))
|
||||
trimmedKey := strings.ToLower(strings.TrimSuffix(strings.TrimPrefix(key, prefix), suffix))
|
||||
ports[chain][trimmedKey] = value
|
||||
}
|
||||
|
||||
return ports, nil
|
||||
}
|
||||
|
||||
func mergeComposeEnvFiles(rawJSON []byte) map[string]map[string]int {
|
||||
newPorts := map[string]map[string]int{}
|
||||
json.Unmarshal(rawJSON, &newPorts)
|
||||
|
||||
mergedPorts := map[string]map[string]int{}
|
||||
for chain, services := range defaultPorts {
|
||||
mergedPorts[chain] = make(map[string]int)
|
||||
for name, port := range services {
|
||||
newPort := newPorts[chain][name]
|
||||
if newPort > 0 && newPort != port {
|
||||
mergedPorts[chain][name] = newPort
|
||||
} else {
|
||||
mergedPorts[chain][name] = port
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return mergedPorts
|
||||
}
|
||||
|
||||
func loadEnv(path string) []string {
|
||||
content, _ := ioutil.ReadFile(path)
|
||||
lines := strings.Split(string(content), "\n")
|
||||
env := os.Environ()
|
||||
for _, line := range lines {
|
||||
if line != "" {
|
||||
env = append(env, line)
|
||||
}
|
||||
}
|
||||
|
||||
return env
|
||||
}
|
||||
|
||||
@@ -3,6 +3,9 @@ package cmd
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/vulpemventures/nigiri/cli/constants"
|
||||
"github.com/vulpemventures/nigiri/cli/controller"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -37,7 +40,7 @@ func TestStartStopBitcoin(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestStopBeforeStartShouldFail(t *testing.T) {
|
||||
expectedError := "Nigiri is neither running nor stopped, please create it first"
|
||||
expectedError := constants.ErrNigiriNotRunning.Error()
|
||||
|
||||
err := testCommand("stop", "", !delete)
|
||||
if err == nil {
|
||||
@@ -47,6 +50,7 @@ func TestStopBeforeStartShouldFail(t *testing.T) {
|
||||
t.Fatalf("Expected error: %s, got: %s", expectedError, err)
|
||||
}
|
||||
|
||||
expectedError = constants.ErrNigiriNotExisting.Error()
|
||||
err = testCommand("stop", "", delete)
|
||||
if err == nil {
|
||||
t.Fatal("Should return error when trying to delete before starting")
|
||||
@@ -57,7 +61,7 @@ func TestStopBeforeStartShouldFail(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestStartAfterStartShouldFail(t *testing.T) {
|
||||
expectedError := "Nigiri is already running, please stop it first"
|
||||
expectedError := constants.ErrNigiriAlreadyRunning.Error()
|
||||
|
||||
if err := testCommand("start", "", bitcoin); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -85,30 +89,48 @@ func TestStartAfterStartShouldFail(t *testing.T) {
|
||||
}
|
||||
|
||||
func testStart(t *testing.T, flag bool) {
|
||||
ctl, err := controller.NewController()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := testCommand("start", "", flag); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if isRunning, _ := nigiriIsRunning(); !isRunning {
|
||||
t.Fatal("Nigiri should be started but services have not been found among running containers")
|
||||
if isRunning, err := ctl.IsNigiriRunning(); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if !isRunning {
|
||||
t.Fatal("Nigiri should have been started but services have not been found among running containers")
|
||||
}
|
||||
}
|
||||
|
||||
func testStop(t *testing.T) {
|
||||
fmt.Println(!delete)
|
||||
ctl, err := controller.NewController()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := testCommand("stop", "", !delete); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if isStopped, _ := nigiriExistsAndNotRunning(); !isStopped {
|
||||
t.Fatal("Nigiri should be stopped but services have not been found among stopped containers")
|
||||
if isStopped, err := ctl.IsNigiriStopped(); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if !isStopped {
|
||||
t.Fatal("Nigiri should have been stopped but services have not been found among stopped containers")
|
||||
}
|
||||
}
|
||||
|
||||
func testDelete(t *testing.T) {
|
||||
ctl, err := controller.NewController()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := testCommand("stop", "", delete); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if isStopped, _ := nigiriExistsAndNotRunning(); isStopped {
|
||||
t.Fatal("Nigiri should be terminated at this point but services have found among stopped containers")
|
||||
if isStopped, err := ctl.IsNigiriStopped(); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if isStopped {
|
||||
t.Fatal("Nigiri should have been terminated at this point but services have been found among stopped containers")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
119
cli/cmd/stop.go
119
cli/cmd/stop.go
@@ -2,13 +2,12 @@ package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/vulpemventures/nigiri/cli/config"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/vulpemventures/nigiri/cli/constants"
|
||||
"github.com/vulpemventures/nigiri/cli/controller"
|
||||
)
|
||||
|
||||
var StopCmd = &cobra.Command{
|
||||
@@ -20,24 +19,36 @@ var StopCmd = &cobra.Command{
|
||||
|
||||
func stopChecks(cmd *cobra.Command, args []string) error {
|
||||
datadir, _ := cmd.Flags().GetString("datadir")
|
||||
delete, _ := cmd.Flags().GetBool("delete")
|
||||
|
||||
if !isDatadirOk(datadir) {
|
||||
return fmt.Errorf("Invalid datadir, it must be an absolute path: %s", datadir)
|
||||
}
|
||||
|
||||
if _, err := os.Stat(datadir); os.IsNotExist(err) {
|
||||
return fmt.Errorf("Datadir do not exists: %s", datadir)
|
||||
}
|
||||
|
||||
nigiriExists, err := nigiriExistsAndNotRunning()
|
||||
ctl, err := controller.NewController()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !nigiriExists {
|
||||
return fmt.Errorf("Nigiri is neither running nor stopped, please create it first")
|
||||
|
||||
if err := ctl.ParseDatadir(datadir); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := config.ReadFromFile(datadir); err != nil {
|
||||
if _, err := os.Stat(datadir); os.IsNotExist(err) {
|
||||
return constants.ErrDatadirNotExisting
|
||||
}
|
||||
|
||||
if isRunning, err := ctl.IsNigiriRunning(); err != nil {
|
||||
return err
|
||||
} else if !isRunning {
|
||||
if delete {
|
||||
if isStopped, err := ctl.IsNigiriStopped(); err != nil {
|
||||
return err
|
||||
} else if !isStopped {
|
||||
return constants.ErrNigiriNotExisting
|
||||
}
|
||||
} else {
|
||||
return constants.ErrNigiriNotRunning
|
||||
}
|
||||
}
|
||||
|
||||
if err := ctl.ReadConfigFile(datadir); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
@@ -47,40 +58,15 @@ func stop(cmd *cobra.Command, args []string) error {
|
||||
delete, _ := cmd.Flags().GetBool("delete")
|
||||
datadir, _ := cmd.Flags().GetString("datadir")
|
||||
|
||||
bashCmd := getStopBashCmd(datadir, delete)
|
||||
if err := bashCmd.Run(); err != nil {
|
||||
ctl, err := controller.NewController()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if delete {
|
||||
fmt.Println("Removing data from volumes...")
|
||||
if err := cleanVolumes(datadir); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
configFile := getPath(datadir, "config")
|
||||
envFile := getPath(datadir, "env")
|
||||
|
||||
fmt.Println("Removing configuration file...")
|
||||
if err := os.Remove(configFile); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("Removing environmet file...")
|
||||
if err := os.Remove(envFile); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("Nigiri has been cleaned up successfully.")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func getStopBashCmd(datadir string, delete bool) *exec.Cmd {
|
||||
composePath := getPath(datadir, "compose")
|
||||
envPath := getPath(datadir, "env")
|
||||
env := loadEnv(envPath)
|
||||
composePath := ctl.GetResourcePath(datadir, "compose")
|
||||
configPath := ctl.GetResourcePath(datadir, "config")
|
||||
envPath := ctl.GetResourcePath(datadir, "env")
|
||||
env := ctl.LoadComposeEnvironment(envPath)
|
||||
|
||||
bashCmd := exec.Command("docker-compose", "-f", composePath, "stop")
|
||||
if delete {
|
||||
@@ -90,34 +76,27 @@ func getStopBashCmd(datadir string, delete bool) *exec.Cmd {
|
||||
bashCmd.Stderr = os.Stderr
|
||||
bashCmd.Env = env
|
||||
|
||||
return bashCmd
|
||||
}
|
||||
|
||||
// cleanVolumes navigates into <datadir>/resources/volumes/<network>
|
||||
// and deletes all files and directories but the *.conf config files.
|
||||
func cleanVolumes(datadir string) error {
|
||||
network := config.GetString(config.Network)
|
||||
attachLiquid := config.GetBool(config.AttachLiquid)
|
||||
if attachLiquid {
|
||||
network = fmt.Sprintf("liquid%s", network)
|
||||
}
|
||||
volumedir := filepath.Join(datadir, "resources", "volumes", network)
|
||||
|
||||
subdirs, err := ioutil.ReadDir(volumedir)
|
||||
if err != nil {
|
||||
if err := bashCmd.Run(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, d := range subdirs {
|
||||
volumedir := filepath.Join(volumedir, d.Name())
|
||||
subsubdirs, _ := ioutil.ReadDir(volumedir)
|
||||
for _, sd := range subsubdirs {
|
||||
if sd.IsDir() {
|
||||
if err := os.RemoveAll(filepath.Join(volumedir, sd.Name())); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if delete {
|
||||
fmt.Println("Removing data from volumes...")
|
||||
if err := ctl.CleanResourceVolumes(datadir); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("Removing configuration file...")
|
||||
if err := os.Remove(configPath); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("Removing environmet file...")
|
||||
if err := os.Remove(envPath); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("Nigiri has been cleaned up successfully.")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
Reference in New Issue
Block a user