rhosus

Форк
0
/
root.go 
154 строки · 4.5 Кб
1
/*
2
 * Copyright (c) 2022.
3
 * Licensed to the Parasource Foundation under one or more contributor license agreements.  See the NOTICE file distributed with this work for additional information regarding copyright ownership.  The Parasource licenses this file to you under the Parasource License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
4
 * You may obtain a copy of the License at http://www.parasource.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.
5
 * See the License for the specific language governing permissions and limitations under the License.
6
 */
7

8
package main
9

10
import (
11
	"fmt"
12
	rhosusnode "github.com/parasource/rhosus/rhosus/node"
13
	"github.com/parasource/rhosus/rhosus/util"
14
	"github.com/parasource/rhosus/rhosus/util/uuid"
15
	"github.com/rs/zerolog/log"
16
	"github.com/spf13/cobra"
17
	"github.com/spf13/viper"
18
	"io"
19
	"os"
20
	"path"
21
	"runtime"
22
)
23

24
const (
25
	uuidFileName = "datanode.uuid"
26
)
27

28
var configDefaults = map[string]interface{}{
29
	"gomaxprocs":       0,
30
	"service_addr":     "127.0.0.1:5400",
31
	"rhosus_path":      "/var/lib/rhosus",
32
	"shutdown_timeout": 30,
33
}
34

35
func init() {
36
	rootCmd.Flags().String("service_addr", "127.0.0.1:5400", "data node service address")
37
	rootCmd.Flags().String("etcd_addr", "127.0.0.1:2379", "etcd service discovery address")
38
	rootCmd.Flags().String("rhosus_path", "/var/lib/rhosus", "rhosus root path")
39
	rootCmd.Flags().Int("shutdown_timeout", 30, "node shutdown timeout")
40

41
	viper.BindPFlag("service_addr", rootCmd.Flags().Lookup("service_addr"))
42
	viper.BindPFlag("etcd_addr", rootCmd.Flags().Lookup("etcd_addr"))
43
	viper.BindPFlag("rhosus_path", rootCmd.Flags().Lookup("rhosus_path"))
44
	viper.BindPFlag("shutdown_timeout", rootCmd.Flags().Lookup("shutdown_timeout"))
45
}
46

47
var rootCmd = &cobra.Command{
48
	Use: "rhosusd",
49
	Run: func(cmd *cobra.Command, args []string) {
50

51
		printWelcome()
52

53
		for k, v := range configDefaults {
54
			viper.SetDefault(k, v)
55
		}
56

57
		bindEnvs := []string{
58
			"service_addr", "rhosus_path", "shutdown_timeout", "etcd_addr",
59
		}
60
		for _, env := range bindEnvs {
61
			err := viper.BindEnv(env)
62
			if err != nil {
63
				log.Fatal().Err(err).Msg("error binding env variable")
64
			}
65
		}
66

67
		if os.Getenv("GOMAXPROCS") == "" {
68
			if viper.IsSet("gomaxprocs") && viper.GetInt("gomaxprocs") > 0 {
69
				runtime.GOMAXPROCS(viper.GetInt("gomaxprocs"))
70
			} else {
71
				runtime.GOMAXPROCS(runtime.NumCPU())
72
			}
73
		}
74

75
		v := viper.GetViper()
76

77
		serviceAddr := v.GetString("service_addr")
78
		etcdAddr := v.GetString("etcd_addr")
79

80
		rhosusPath := v.GetString("rhosus_path")
81

82
		// If rhosus home directory does not exist already,
83
		// we create a new one
84
		if ok := util.FileExists(rhosusPath); !ok {
85
			err := os.Mkdir(rhosusPath, 0755)
86
			if err != nil {
87
				log.Fatal().Err(err).Msg("error creating rhosus home directory")
88
			}
89
		}
90
		if err := util.TestDirWritable(rhosusPath); err != nil {
91
			log.Fatal().Err(err).Msg("rhosus home directory is not writable")
92
		}
93

94
		nodeId := getId(rhosusPath, true)
95

96
		config := rhosusnode.Config{
97
			ID:          nodeId,
98
			EtcdAddress: etcdAddr,
99
			Address:     serviceAddr,
100
			RhosusPath:  rhosusPath,
101
		}
102

103
		node, _ := rhosusnode.NewNode(config)
104
		node.Start()
105
	},
106
}
107

108
func getId(rhosusPath string, persistent bool) string {
109
	var id string
110

111
	if !persistent {
112
		v4id, _ := uuid.NewV4()
113
		return v4id.String()
114
	}
115

116
	uuidFilePath := path.Join(rhosusPath, uuidFileName)
117

118
	// since we are just testing, we don't need that yet
119
	if util.FileExists(uuidFilePath) {
120
		file, err := os.OpenFile(uuidFilePath, os.O_RDONLY, 0666)
121
		defer file.Close()
122

123
		if err != nil {
124
			log.Fatal().Err(err).Msg("error opening node uuid file")
125
		}
126
		data, err := io.ReadAll(file)
127
		if err != nil {
128
			log.Fatal().Err(err).Msg("error reading uuid file")
129
		}
130

131
		id = string(data)
132
	} else {
133
		v4uid, _ := uuid.NewV4()
134
		id = v4uid.String()
135

136
		file, err := os.OpenFile(uuidFilePath, os.O_CREATE|os.O_RDWR, 0755)
137
		if err != nil {
138
			log.Fatal().Err(err).Msg("error reading uuid file")
139
		}
140
		defer file.Close()
141

142
		file.Write([]byte(id))
143
	}
144

145
	return id
146
}
147

148
func printWelcome() {
149
	welcome := "    ____  __  ______  _____ __  _______\n   / __ \\/ / / / __ \\/ ___// / / / ___/\n  / /_/ / /_/ / / / /\\__ \\/ / / /\\__ \\ \n / _, _/ __  / /_/ /___/ / /_/ /___/ / \n/_/ |_/_/ /_/\\____//____/\\____//____/  \n                                       "
150
	fmt.Println(welcome)
151

152
	fmt.Println("\n|------ Rhosus node")
153
	fmt.Println("|------ Version " + util.Version() + "\n")
154
}
155

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.