Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support rendering template files on target host with sealctl #3872

Merged
merged 5 commits into from Sep 8, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
141 changes: 36 additions & 105 deletions cmd/sealctl/cmd/initsystem.go
Expand Up @@ -18,6 +18,7 @@ package cmd

import (
"fmt"
"strings"

"github.com/spf13/cobra"

Expand All @@ -31,124 +32,54 @@ var (
func newInitSystemCmd() *cobra.Command {
var initsystemCmd = &cobra.Command{
Use: "initsystem",
Short: "init system",
Short: "init system management",
}
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
}
initsystemCmd.AddCommand(createInitSystemSubCommand("enable", func(s string) error {
return initsystemInterface.ServiceEnable(s)
}))
initsystemCmd.AddCommand(createInitSystemSubCommand("start", func(s string) error {
return initsystemInterface.ServiceStart(s)
}))
initsystemCmd.AddCommand(createInitSystemSubCommand("stop", func(s string) error {
return initsystemInterface.ServiceStop(s)
}))
initsystemCmd.AddCommand(createInitSystemSubCommand("restart", func(s string) error {
return initsystemInterface.ServiceRestart(s)
}))
initsystemCmd.AddCommand(createInitSystemSubCommand("is-exists", func(s string) error {
fmt.Println(initsystemInterface.ServiceExists(s))
return nil
}))
initsystemCmd.AddCommand(createInitSystemSubCommand("is-enabled", func(s string) error {
fmt.Println(initsystemInterface.ServiceIsEnabled(s))
return nil
}))
initsystemCmd.AddCommand(createInitSystemSubCommand("is-active", func(s string) error {
fmt.Println(initsystemInterface.ServiceIsActive(s))
return nil
}))

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()
},
func createInitSystemSubCommand(verb string, runE func(string) error) *cobra.Command {
var short string
if strings.HasPrefix(verb, "is-") {
short = fmt.Sprintf("check if the initsystem service is %s", strings.TrimPrefix(verb, "is-"))
} else {
short = fmt.Sprintf("%s the initsystem service", verb)
}
return initsystemCmd
}

func newInitSystemRestartCmd() *cobra.Command {
var initsystemCmd = &cobra.Command{
Use: "restart",
Short: "restart initsystem service",
return &cobra.Command{
Use: verb,
Short: short,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return initsystemInterface.ServiceRestart(args[0])
return runE(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 {
Expand Down
125 changes: 125 additions & 0 deletions cmd/sealctl/cmd/render.go
@@ -0,0 +1,125 @@
// Copyright 漏 2023 sealos.
//
// 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 (
"os"
"path/filepath"
"strings"

"github.com/spf13/cobra"
"helm.sh/helm/v3/pkg/cli/values"
"helm.sh/helm/v3/pkg/getter"

"github.com/labring/sealos/pkg/template"
fileutils "github.com/labring/sealos/pkg/utils/file"
"github.com/labring/sealos/pkg/utils/logger"
"github.com/labring/sealos/pkg/utils/maps"
)

func newRenderCommand() *cobra.Command {
var (
valueFiles []string
sets []string
)
cmd := &cobra.Command{
Use: "render",
Short: "render template files with values and envs",
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return runRender(valueFiles, sets, args)
},
}
cmd.Flags().StringSliceVarP(&valueFiles, "values", "f", []string{}, "values files for context")
cmd.Flags().StringSliceVar(&sets, "set", []string{}, "k/v sets for context")
return cmd
}

func loadValues(valueFiles, sets []string) (map[string]interface{}, error) {
valueOpt := &values.Options{
ValueFiles: valueFiles,
Values: sets,
}
return valueOpt.MergeValues([]getter.Provider{{
Schemes: []string{"http", "https"},
New: getter.NewHTTPGetter,
}})
}

func findTemplateFiles(paths ...string) ([]string, error) {
var ret []string
for i := range paths {
files, err := fileutils.FindFilesMatchExtension(paths[i], ".tpl", ".tmpl")
if err != nil {
return nil, err
}
ret = append(ret, files...)
}
return ret, nil
}

func runRender(valueFiles, sets []string, args []string) error {
mergedValues, err := loadValues(valueFiles, sets)
if err != nil {
return err
}
envs := maps.FromSlice(os.Environ())
data := make(map[string]interface{})
// For compatibility with older templates
for k, v := range envs {
data[k] = v
}

data["Values"] = mergedValues
data["Env"] = envs

filepaths, err := findTemplateFiles(args...)
if err != nil {
return err
}
for i := range filepaths {
if err := func(fp string) error {
logger.Debug("found template file %s, trying to rendering", fp)
trimed := strings.TrimSuffix(fp, filepath.Ext(fp))
if fileutils.IsExist(trimed) {
logger.Debug("found existing file %s, override it", trimed)
}
file, err := os.OpenFile(trimed, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
return err
}
defer file.Close()
b, err := fileutils.ReadAll(fp)
if err != nil {
return err
}
t, err := template.Parse(string(b))
if err != nil {
return err
}
if err = t.Execute(file, data); err != nil {
return err
}
logger.Info("render %s from %s completed", trimed, fp)
return nil
}(filepaths[i]); err != nil {
return err
}
}
return nil
}

func init() {
rootCmd.AddCommand(newRenderCommand())
}