Skip to content

Commit

Permalink
- Fix lint issues (#405)
Browse files Browse the repository at this point in the history
- Minor code improvements
 - Unexported locally used variables
fixes #250

-- Rebased --
 21st March

Signed-off-by: Shailesh Pant <[email protected]>
  • Loading branch information
pshail authored Mar 22, 2022
1 parent 58e5a39 commit 6568fb5
Show file tree
Hide file tree
Showing 27 changed files with 138 additions and 38 deletions.
2 changes: 2 additions & 0 deletions agent/cloudinit/cloudinit.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"sigs.k8s.io/yaml"
)

// ScriptExecutor bootstrap script executor
type ScriptExecutor struct {
WriteFilesExecutor IFileWriter
RunCmdExecutor ICmdRunner
Expand All @@ -25,6 +26,7 @@ type bootstrapConfig struct {
CommandsToExecute []string `json:"runCmd"`
}

// Files details required for files written by bootstrap script
type Files struct {
Path string `json:"path,"`
Encoding string `json:"encoding,omitempty"`
Expand Down
2 changes: 2 additions & 0 deletions agent/cloudinit/cmd_runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ type ICmdRunner interface {
RunCmd(string) error
}

// CmdRunner default implementer of ICmdRunner
// TODO reevaluate empty interface/struct
type CmdRunner struct {
}

Expand Down
1 change: 1 addition & 0 deletions agent/cloudinit/file_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ type IFileWriter interface {
WriteToFile(*Files) error
}

// FileWriter default implementation of IFileWriter
type FileWriter struct {
}

Expand Down
2 changes: 2 additions & 0 deletions agent/cloudinit/template_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@ type ITemplateParser interface {
ParseTemplate(string) (string, error)
}

// TemplateParser cloudinit templates parsing using ITemplateParser
type TemplateParser struct {
Template interface{}
}

// ParseTemplate parses and returns the parsed template content
func (tp TemplateParser) ParseTemplate(templateContent string) (string, error) {
tmpl, err := template.New("byoh").Parse(templateContent)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion agent/help_flag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ var _ = Describe("Help flag for host agent", func() {
continue
}
words := strings.Split(line, " ")
line = (words[0] + " " + words[1]) // checking the first two words
line = words[0] + " " + words[1] // checking the first two words
// Any option not belongs to expectedOptions is not allowed.
Expect(strings.TrimSpace(line)).To(BeElementOf(expectedOptions))
}
Expand Down
9 changes: 8 additions & 1 deletion agent/installer/bundle_downloader.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
)

var (
// DownloadPathPermissions file mode permissions for download path
DownloadPathPermissions fs.FileMode = 0777
)

Expand Down Expand Up @@ -53,7 +54,13 @@ func (bd *bundleDownloader) DownloadFromRepo(
downloadPathWithRepo := bd.getBundlePathWithRepo()

err := ensureDirExist(downloadPathWithRepo)
defer os.Remove(downloadPathWithRepo)
defer func(name string) {
err = os.Remove(name)
if err != nil {
bd.logger.Error(err, "Failed to remove directory", "path", name)
}
}(downloadPathWithRepo)

if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion agent/installer/checks.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (

func checkPreRequsitePackages() error {
if runtime.GOOS == "linux" {
unavailablePackages := []string{}
unavailablePackages := make([]string, 0)
execr := utilsexec.New()
for _, pkgName := range preRequisitePackages {
_, err := execr.LookPath(pkgName)
Expand Down
1 change: 1 addition & 0 deletions agent/installer/cli-dev.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ var (
klogger logr.Logger
)

// Main entry point for the installer dev/test CLI
func Main() {
klogger = klogr.New()

Expand Down
54 changes: 40 additions & 14 deletions agent/installer/installer.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,24 @@ import (
"github.com/vmware-tanzu/cluster-api-provider-bringyourownhost/agent/installer/internal/algo"
)

// Error string wrapper for errors returned by the installer
type Error string

func (e Error) Error() string { return string(e) }

const (
ErrDetectOs = Error("Error detecting OS")
// ErrDetectOs error type when supported OS could not be detected
ErrDetectOs = Error("Error detecting OS")
// ErrOsK8sNotSupported error type when the OS is not supported by the k8s installer
ErrOsK8sNotSupported = Error("No k8s support for OS")
ErrBundleDownload = Error("Error downloading bundle")
ErrBundleExtract = Error("Error extracting bundle")
ErrBundleInstall = Error("Error installing bundle")
ErrBundleUninstall = Error("Error uninstalling bundle")
// ErrBundleDownload error type when the bundle download fails
ErrBundleDownload = Error("Error downloading bundle")
// ErrBundleExtract error type when the bundle extraction fails
ErrBundleExtract = Error("Error extracting bundle")
// ErrBundleInstall error type when the bundle installation fails
ErrBundleInstall = Error("Error installing bundle")
// ErrBundleUninstall error type when the bundle uninstallation fails
ErrBundleUninstall = Error("Error uninstalling bundle")
)

var preRequisitePackages = []string{"socat", "ebtables", "ethtool", "conntrack"}
Expand Down Expand Up @@ -84,6 +91,7 @@ func (bd *bundleDownloader) getBundlePathDirOrPreview(k8s, tag string) string {
return bd.GetBundleDirPath(k8s, tag)
}

// DownloadOrPreview downloads the bundle if bundleDownloader is configured with a download path else runs in preview mode without downloading
func (bd *bundleDownloader) DownloadOrPreview(os, k8s, tag string) error {
if bd == nil || bd.downloadPath == "" {
bd.logger.Info("Running in preview mode, skip bundle download")
Expand Down Expand Up @@ -154,7 +162,7 @@ func (i *installer) Install(bundleRepo, k8sVer, tag string) error {
return nil
}

// Uninstal uninstalls the specified k8s version on the current OS
// Uninstall uninstalls the specified k8s version on the current OS
func (i *installer) Uninstall(bundleRepo, k8sVer, tag string) error {
i.setBundleRepo(bundleRepo)
algoInst, err := i.getAlgoInstallerWithBundle(k8sVer, tag)
Expand Down Expand Up @@ -243,11 +251,20 @@ type logPrinter struct {
logger logr.Logger
}

// Desc logPrinter implementation of OutputBuilder Desc method
func (lp *logPrinter) Desc(s string) { lp.logger.Info(s) }
func (lp *logPrinter) Cmd(s string) { lp.logger.Info(s) }
func (lp *logPrinter) Out(s string) { lp.logger.Info(s) }
func (lp *logPrinter) Err(s string) { lp.logger.Info(s) }
func (lp *logPrinter) Msg(s string) { lp.logger.Info(s) }

// Cmd logPrinter implementation of OutputBuilder Cmd method
func (lp *logPrinter) Cmd(s string) { lp.logger.Info(s) }

// Out logPrinter implementation of OutputBuilder Out method
func (lp *logPrinter) Out(s string) { lp.logger.Info(s) }

// Err logPrinter implementation of OutputBuilder Err method
func (lp *logPrinter) Err(s string) { lp.logger.Info(s) }

// Msg logPrinter implementation of OutputBuilder Msg method
func (lp *logPrinter) Msg(s string) { lp.logger.Info(s) }

// stringPrinter is an adapter of OutputBuilder to string
type stringPrinter struct {
Expand All @@ -260,11 +277,20 @@ type stringPrinter struct {
strDivider string
}

// Desc stringPrinter implementation of description output
func (obp *stringPrinter) Desc(s string) { obp.steps = append(obp.steps, applyFmt(obp.descFmt, s)) }
func (obp *stringPrinter) Cmd(s string) { obp.steps = append(obp.steps, applyFmt(obp.cmdFmt, s)) }
func (obp *stringPrinter) Out(s string) { obp.steps = append(obp.steps, applyFmt(obp.outFmt, s)) }
func (obp *stringPrinter) Err(s string) { obp.steps = append(obp.steps, applyFmt(obp.errFmt, s)) }
func (obp *stringPrinter) Msg(s string) { obp.steps = append(obp.steps, applyFmt(obp.msgFmt, s)) }

// Cmd stringPrinter implementation of command output
func (obp *stringPrinter) Cmd(s string) { obp.steps = append(obp.steps, applyFmt(obp.cmdFmt, s)) }

// Out stringPrinter implementation of info/content output
func (obp *stringPrinter) Out(s string) { obp.steps = append(obp.steps, applyFmt(obp.outFmt, s)) }

// Err stringPrinter implementation of error output
func (obp *stringPrinter) Err(s string) { obp.steps = append(obp.steps, applyFmt(obp.errFmt, s)) }

// Msg stringPrinter implementation of message output
func (obp *stringPrinter) Msg(s string) { obp.steps = append(obp.steps, applyFmt(obp.msgFmt, s)) }

// String implements the Stringer interface
// It joins the string array by adding new lines between the strings and returns it as a single string
Expand Down
1 change: 1 addition & 0 deletions agent/installer/internal/algo/apt_step.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"strings"
)

// NewAptStep returns a new step to install apt package
func NewAptStep(k *BaseK8sInstaller, aptPkg string) Step {
return NewAptStepEx(k, aptPkg, false)
}
Expand Down
4 changes: 4 additions & 0 deletions agent/installer/internal/algo/installer.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,13 @@ are required in order to:
6) disable unattended OS updates
*/

// Step execute/rollback interface
type Step interface {
do() error
undo() error
}

// K8sStepProvider steps provider for k8s installer
type K8sStepProvider interface {
getSteps(*BaseK8sInstaller) []Step

Expand Down Expand Up @@ -68,6 +70,7 @@ type BaseK8sInstaller struct {
OutputBuilder
}

// Install installation of k8s cluster as per configured steps in the provider
func (b *BaseK8sInstaller) Install() error {
steps := b.getSteps(b)

Expand All @@ -83,6 +86,7 @@ func (b *BaseK8sInstaller) Install() error {
return nil
}

// Uninstall uninstallation of k8s cluster as per configured steps in the provider
func (b *BaseK8sInstaller) Uninstall() error {
lastStepIdx := len(b.getSteps(b)) - 1
b.rollback(lastStepIdx)
Expand Down
1 change: 1 addition & 0 deletions agent/installer/internal/algo/mock_ubuntu_with_error.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ func (s *mockStep) undo() error {
return s.Err
}

// MockUbuntuWithError is a mock implementation of BaseK8sInstaller that returns an error on the steps
type MockUbuntuWithError struct {
BaseK8sInstaller
errorOnStep int
Expand Down
1 change: 1 addition & 0 deletions agent/installer/internal/algo/output_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

package algo

// OutputBuilder is an interface for building output as the algorithm runs.
type OutputBuilder interface {
Out(string)
Err(string)
Expand Down
6 changes: 6 additions & 0 deletions agent/installer/internal/algo/output_builder_counter.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,32 @@

package algo

// OutputBuilderCounter used to count the logs called by the OutputBuilder under various heads/types of output
type OutputBuilderCounter struct {
LogCalledCnt int
}

// Out increments the log count for info/content output
func (c *OutputBuilderCounter) Out(str string) {
c.LogCalledCnt++
}

// Err increments the log count for error output
func (c *OutputBuilderCounter) Err(str string) {
c.LogCalledCnt++
}

// Cmd increments the log count for command output
func (c *OutputBuilderCounter) Cmd(str string) {
c.LogCalledCnt++
}

// Desc increments the log count for description output
func (c *OutputBuilderCounter) Desc(str string) {
c.LogCalledCnt++
}

// Msg increments the log count for message output
func (c *OutputBuilderCounter) Msg(str string) {
c.LogCalledCnt++
}
1 change: 1 addition & 0 deletions agent/installer/internal/algo/ubuntu20_4K8s1_22.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"path/filepath"
)

// Ubuntu20_4K8s1_22 is the configuration for Ubuntu 20.4.X, K8s 1.22.X extending BaseK8sInstaller
type Ubuntu20_4K8s1_22 struct {
BaseK8sInstaller
}
Expand Down
5 changes: 5 additions & 0 deletions agent/installer/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ func newRegistry() registry {
return registry{osk8sInstallerMap: make(osk8sInstallerMap)}
}

// AddBundleInstaller adds a bundle installer to the registry
func (r *registry) AddBundleInstaller(os, k8sVer string, installer osk8sInstaller) {
if _, ok := r.osk8sInstallerMap[os]; !ok {
r.osk8sInstallerMap[os] = make(k8sInstallerMap)
Expand All @@ -49,6 +50,7 @@ func (r *registry) AddBundleInstaller(os, k8sVer string, installer osk8sInstalle
r.osk8sInstallerMap[os][k8sVer] = installer
}

// AddOsFilter adds an OS filter to the filtered bundle list of registry
func (r *registry) AddOsFilter(osFilter, osBundle string) {
r.filterOSBundleList = append(r.filterOSBundleList, filterOsBundlePair{osFilter: osFilter, osBundle: osBundle})
}
Expand All @@ -57,6 +59,7 @@ func (r *registry) AddK8sFilter(k8sFilter string) {
r.filterK8sBundleList = append(r.filterK8sBundleList, filterK8sBundle{k8sFilter: k8sFilter})
}

// ListOS returns a list of OSes supported by the registry
func (r *registry) ListOS() (osFilter, osBundle []string) {
osFilter = make([]string, 0, len(r.filterOSBundleList))
osBundle = make([]string, 0, len(r.filterOSBundleList))
Expand All @@ -69,6 +72,7 @@ func (r *registry) ListOS() (osFilter, osBundle []string) {
return
}

// ListK8s returns a list of K8s versions supported by the registry
func (r *registry) ListK8s(osBundleHost string) []string {
var result []string

Expand All @@ -89,6 +93,7 @@ func (r *registry) ListK8s(osBundleHost string) []string {
return result
}

// GetInstaller returns the bundle installer for the given os and k8s version
func (r *registry) GetInstaller(osHost, k8sVer string) (osk8si osk8sInstaller, osBundle string) {
osBundle = r.resolveOsToOsBundle(osHost)
k8sBundle := r.resolveK8sToK8sBundle(k8sVer)
Expand Down
2 changes: 1 addition & 1 deletion agent/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"os"
"strings"

pflag "github.com/spf13/pflag"
"github.com/spf13/pflag"
"github.com/vmware-tanzu/cluster-api-provider-bringyourownhost/agent/cloudinit"
"github.com/vmware-tanzu/cluster-api-provider-bringyourownhost/agent/installer"
"github.com/vmware-tanzu/cluster-api-provider-bringyourownhost/agent/reconciler"
Expand Down
5 changes: 4 additions & 1 deletion agent/reconciler/host_reconciler.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ type IK8sInstaller interface {
Uninstall(string, string, string) error
}

// HostReconciler encapsulates the data/logic needed to reconcile a ByoHost
type HostReconciler struct {
Client client.Client
CmdRunner cloudinit.ICmdRunner
Expand All @@ -46,7 +47,8 @@ type HostReconciler struct {

const (
bootstrapSentinelFile = "/run/cluster-api/bootstrap-success.complete"
KubeadmResetCommand = "kubeadm reset --force"
// KubeadmResetCommand is the command to run to force reset/remove nodes' local file system of the files created by kubeadm
KubeadmResetCommand = "kubeadm reset --force"
)

// Reconcile handles events for the ByoHost that is registered by this agent process
Expand Down Expand Up @@ -161,6 +163,7 @@ func (r *HostReconciler) getBootstrapScript(ctx context.Context, dataSecretName,
return bootstrapSecret, nil
}

// SetupWithManager sets up the controller with the manager
func (r *HostReconciler) SetupWithManager(ctx context.Context, mgr manager.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&infrastructurev1beta1.ByoHost{}).
Expand Down
5 changes: 5 additions & 0 deletions agent/registration/host_registrar.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,16 @@ import (
)

var (
// LocalHostRegistrar is a HostRegistrar that registers the local host.
LocalHostRegistrar *HostRegistrar
)

// HostInfo contains information about the host network interface.
type HostInfo struct {
DefaultNetworkInterfaceName string
}

// HostRegistrar used to register a host.
type HostRegistrar struct {
K8sClient client.Client
ByoHostInfo HostInfo
Expand Down Expand Up @@ -67,6 +70,7 @@ func (hr *HostRegistrar) Register(hostName, namespace string, hostLabels map[str
return hr.UpdateNetwork(ctx, byoHost)
}

// UpdateNetwork updates the network interface status for the host
func (hr *HostRegistrar) UpdateNetwork(ctx context.Context, byoHost *infrastructurev1beta1.ByoHost) error {
klog.Info("Add Network Info")
helper, err := patch.NewHelper(byoHost, hr.K8sClient)
Expand All @@ -79,6 +83,7 @@ func (hr *HostRegistrar) UpdateNetwork(ctx context.Context, byoHost *infrastruct
return helper.Patch(ctx, byoHost)
}

// GetNetworkStatus returns the network interface(s) status for the host
func (hr *HostRegistrar) GetNetworkStatus() []infrastructurev1beta1.NetworkStatus {
Network := make([]infrastructurev1beta1.NetworkStatus, 0)

Expand Down
Loading

0 comments on commit 6568fb5

Please sign in to comment.