Skip to content

Commit

Permalink
feature(main): add initsystem cmd and so on (#3841) (#3861)
Browse files Browse the repository at this point in the history
Signed-off-by: cuisongliu <cuisongliu@qq.com>

# Conflicts:
#	pkg/runtime/k3s/bootstrap.go
#	pkg/runtime/k3s/config.go

# Conflicts:
#	pkg/runtime/k3s/bootstrap.go
#	pkg/runtime/k3s/config.go

Co-authored-by: cuisongliu <cuisongliu@qq.com>
  • Loading branch information
sealos-ci-robot and cuisongliu committed Sep 7, 2023
1 parent 50acaec commit d29b03e
Show file tree
Hide file tree
Showing 18 changed files with 352 additions and 689 deletions.
161 changes: 161 additions & 0 deletions cmd/sealctl/cmd/initsystem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
/*
Copyright 2022 cuisongliu@qq.com.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.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.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cmd

import (
"fmt"

"github.com/spf13/cobra"

"github.com/labring/sealos/pkg/utils/initsystem"
)

var (
initsystemInterface initsystem.InitSystem
)

func newInitSystemCmd() *cobra.Command {
var initsystemCmd = &cobra.Command{
Use: "initsystem",
Short: "init system",
}
initsystemCmd.AddCommand(newInitSystemEnableCmd())
initsystemCmd.AddCommand(newInitSystemStartCmd())
initsystemCmd.AddCommand(newInitSystemStopCmd())
initsystemCmd.AddCommand(newInitSystemRestartCmd())
initsystemCmd.AddCommand(newInitSystemIsExistsCmd())
initsystemCmd.AddCommand(newInitSystemIsEnabledCmd())
initsystemCmd.AddCommand(newInitSystemIsActiveCmd())
return initsystemCmd
}

func newInitSystemStartCmd() *cobra.Command {
var initsystemCmd = &cobra.Command{
Use: "start",
Short: "start initsystem service",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return initsystemInterface.ServiceStart(args[0])
},
PreRunE: func(cmd *cobra.Command, args []string) error {
return initsystemInit()
},
}
return initsystemCmd
}

func newInitSystemEnableCmd() *cobra.Command {
var initsystemCmd = &cobra.Command{
Use: "enable",
Short: "enable initsystem service",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return initsystemInterface.ServiceEnable(args[0])
},
PreRunE: func(cmd *cobra.Command, args []string) error {
return initsystemInit()
},
}
return initsystemCmd
}

func newInitSystemStopCmd() *cobra.Command {
var initsystemCmd = &cobra.Command{
Use: "stop",
Short: "stop initsystem service",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return initsystemInterface.ServiceStop(args[0])
},
PreRunE: func(cmd *cobra.Command, args []string) error {
return initsystemInit()
},
}
return initsystemCmd
}

func newInitSystemRestartCmd() *cobra.Command {
var initsystemCmd = &cobra.Command{
Use: "restart",
Short: "restart initsystem service",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return initsystemInterface.ServiceRestart(args[0])
},
PreRunE: func(cmd *cobra.Command, args []string) error {
return initsystemInit()
},
}
return initsystemCmd
}

func newInitSystemIsExistsCmd() *cobra.Command {
var initsystemCmd = &cobra.Command{
Use: "is-exists",
Short: "is exists initsystem service",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
out := initsystemInterface.ServiceExists(args[0])
fmt.Println(out)
},
PreRunE: func(cmd *cobra.Command, args []string) error {
return initsystemInit()
},
}
return initsystemCmd
}

func newInitSystemIsEnabledCmd() *cobra.Command {
var initsystemCmd = &cobra.Command{
Use: "is-enabled",
Short: "is enabled initsystem service",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
out := initsystemInterface.ServiceIsEnabled(args[0])
fmt.Println(out)
},
PreRunE: func(cmd *cobra.Command, args []string) error {
return initsystemInit()
},
}
return initsystemCmd
}

func newInitSystemIsActiveCmd() *cobra.Command {
var initsystemCmd = &cobra.Command{
Use: "is-active",
Short: "is active initsystem service",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
out := initsystemInterface.ServiceIsActive(args[0])
fmt.Println(out)
},
PreRunE: func(cmd *cobra.Command, args []string) error {
return initsystemInit()
},
}
return initsystemCmd
}

func initsystemInit() error {
inte, err := initsystem.GetInitSystem()
if err != nil {
return err
}
initsystemInterface = inte
return nil
}
8 changes: 7 additions & 1 deletion cmd/sealctl/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,17 @@ func init() {
{
Message: "Network Management Commands:",
Commands: []*cobra.Command{
newHostsNameCmd(),
newHostsCmd(),
newIPVSCmd(),
},
},
{
Message: "Machine Management Commands:",
Commands: []*cobra.Command{
newHostsNameCmd(),
newInitSystemCmd(),
},
},
{
Message: "Cluster Management Commands:",
Commands: []*cobra.Command{
Expand Down
111 changes: 78 additions & 33 deletions cmd/sealctl/cmd/static_pod.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ import (
"os"
"path"

"github.com/labring/sealos/pkg/types/v1beta1"

v1 "k8s.io/api/core/v1"

"github.com/labring/sealos/pkg/utils/yaml"

"github.com/spf13/cobra"

"github.com/labring/sealos/pkg/constants"
Expand All @@ -40,48 +46,87 @@ func newStaticPodCmd() *cobra.Command {
return staticPodCmd
}

type lvscarePod struct {
vip string
master []string
image string
name string
print bool
}

func newLvscareCmd() *cobra.Command {
var vip, image, name string
var masters []string
var printBool bool
var obj lvscarePod
var setImage bool
var lvscareCmd = &cobra.Command{
Use: "lvscare",
Short: "generator lvscare static pod file",
PreRun: func(cmd *cobra.Command, args []string) {
if len(masters) == 0 {
logger.Error("master not allow empty")
os.Exit(1)
PreRunE: func(cmd *cobra.Command, args []string) error {
if len(obj.master) == 0 && !setImage {
return fmt.Errorf("master not allow empty")
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
fileName := fmt.Sprintf("%s.%s", name, constants.YamlFileSuffix)
yaml, err := ipvs.LvsStaticPodYaml(vip, masters, image, name)
if err != nil {
logger.Error(err)
os.Exit(1)
RunE: func(cmd *cobra.Command, args []string) error {
if !setImage {
return genNewPod(obj)
}
if printBool {
fmt.Println(yaml)
return
}
logger.Debug("lvscare static pod yaml is %s", yaml)
if err = file.MkDirs(staticPodPath); err != nil {
logger.Error("init dir is error: %v", err)
os.Exit(1)
}
err = os.WriteFile(path.Join(staticPodPath, fileName), []byte(yaml), 0755)
if err != nil {
logger.Error(err)
os.Exit(1)
}
logger.Info("generator lvscare static pod is success")
return setNewPodImage(obj)
},
}
// manually to set host via gateway
lvscareCmd.Flags().StringVar(&vip, "vip", "10.103.97.2:6443", "default vip IP")
lvscareCmd.Flags().StringVar(&name, "name", constants.LvsCareStaticPodName, "generator lvscare static pod name")
lvscareCmd.Flags().StringVar(&image, "image", constants.DefaultLvsCareImage, "generator lvscare static pod image")
lvscareCmd.Flags().StringSliceVar(&masters, "masters", []string{}, "generator masters addrs")
lvscareCmd.Flags().BoolVar(&printBool, "print", false, "is print yaml")
lvscareCmd.Flags().StringVar(&obj.vip, "vip", "10.103.97.2:6443", "default vip IP")
lvscareCmd.Flags().StringVar(&obj.name, "name", constants.LvsCareStaticPodName, "generator lvscare static pod name")
lvscareCmd.Flags().StringVar(&obj.image, "image", v1beta1.DefaultLvsCareImage, "generator lvscare static pod image")
lvscareCmd.Flags().BoolVar(&setImage, "set-img", false, "update lvscare image to static pod")
lvscareCmd.Flags().StringSliceVar(&obj.master, "masters", []string{}, "generator masters addrs")
lvscareCmd.Flags().BoolVar(&obj.print, "print", false, "is print yaml")
return lvscareCmd
}

func genNewPod(obj lvscarePod) error {
fileName := fmt.Sprintf("%s.%s", obj.name, constants.YamlFileSuffix)
yaml, err := ipvs.LvsStaticPodYaml(obj.vip, obj.master, obj.image, obj.name)
if err != nil {
return err
}
if obj.print {
fmt.Println(yaml)
return nil
}
logger.Debug("lvscare static pod yaml is %s", yaml)
if err = file.MkDirs(staticPodPath); err != nil {
return fmt.Errorf("init dir is error: %v", err)
}
err = os.WriteFile(path.Join(staticPodPath, fileName), []byte(yaml), 0755)
if err != nil {
return err
}
logger.Info("generator lvscare static pod is success")
return nil
}

func setNewPodImage(obj lvscarePod) error {
fileName := fmt.Sprintf("%s.%s", obj.name, constants.YamlFileSuffix)
podPath := path.Join(staticPodPath, fileName)
if file.IsExist(podPath) {
pod := &v1.Pod{}
if err := yaml.UnmarshalFile(podPath, pod); err != nil {
return err
}
pod.Spec.Containers[0].Image = obj.image
data, err := ipvs.PodToYaml(*pod)
if err != nil {
return err
}
if obj.print {
fmt.Println(string(data))
return nil
}
err = os.WriteFile(path.Join(staticPodPath, fileName), data, 0755)
if err != nil {
return err
}
logger.Info("update lvscare static pod image is success")
}
return nil
}
2 changes: 1 addition & 1 deletion cmd/sealos/cmd/cert.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func newCertCmd() *cobra.Command {
for _, f := range []string{
path.Join(pathResolver.ConfigsPath(), "kubeadm-init.yaml"),
path.Join(pathResolver.EtcPath(), "kubeadm-init.yaml"),
path.Join(pathResolver.TmpPath(), "k3s-init.yaml"),
path.Join(pathResolver.ConfigsPath(), "k3s-init.yaml"),
} {
if fileutils.IsExist(f) {
runtimeConfigPath = f
Expand Down
3 changes: 1 addition & 2 deletions pkg/checker/cri_shim_checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,7 @@ func (n *CRIShimChecker) Check(_ *v2.Cluster, phase string) error {
}
}()

criShimConfig := "/etc/image-cri-shim.yaml"
if shimCfg, err := types.Unmarshal(criShimConfig); err != nil {
if shimCfg, err := types.Unmarshal(types.DefaultImageCRIShimConfig); err != nil {
status.Error = fmt.Errorf("read image-cri-shim config error: %w", err).Error()
} else {
status.Config = map[string]string{}
Expand Down
1 change: 0 additions & 1 deletion pkg/constants/consts.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ const (
DefaultRegistryPassword = "passw0rd"
DefaultRegistryData = "/var/lib/registry"
DefaultLvscareDomain = "lvscare.node.ip"
DefaultLvsCareImage = "sealos.hub:5000/sealos/lvscare:latest"
DefaultHostsPath = "/etc/hosts"
)

Expand Down
8 changes: 5 additions & 3 deletions pkg/ipvs/lvscare.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ package ipvs
import (
"fmt"

"github.com/labring/sealos/pkg/types/v1beta1"

v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
Expand All @@ -35,7 +37,7 @@ func LvsStaticPodYaml(vip string, masters []string, image, name string) (string,
return "", fmt.Errorf("vip and mster not allow empty")
}
if image == "" {
image = constants.DefaultLvsCareImage
image = v1beta1.DefaultLvsCareImage
}
args := []string{"care", "--vs", vip, "--health-path", "/healthz", "--health-schem", "https"}
for _, m := range masters {
Expand All @@ -51,14 +53,14 @@ func LvsStaticPodYaml(vip string, masters []string, image, name string) (string,
ImagePullPolicy: v1.PullIfNotPresent,
SecurityContext: &v1.SecurityContext{Privileged: &flag},
})
yaml, err := podToYaml(pod)
yaml, err := PodToYaml(pod)
if err != nil {
return "", err
}
return string(yaml), nil
}

func podToYaml(pod v1.Pod) ([]byte, error) {
func PodToYaml(pod v1.Pod) ([]byte, error) {
codecs := scheme.Codecs
gv := v1.SchemeGroupVersion
const mediaType = runtime.ContentTypeYAML
Expand Down

0 comments on commit d29b03e

Please sign in to comment.