Go linter upgrade to 1.44.2 (#908)

* Go linter upgrade to 1.44

Signed-off-by: tanvigour <tanvi.gour@gmail.com>

* remove old excludes and address new ones

Signed-off-by: tanvigour <tanvi.gour@gmail.com>
This commit is contained in:
tanvigour 2022-03-07 02:48:48 -05:00 committed by GitHub
parent a3e87dc69d
commit 050eb553f2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
34 changed files with 165 additions and 148 deletions

View File

@ -30,7 +30,7 @@ jobs:
runs-on: ${{ matrix.os }}
env:
GOVER: 1.17
GOLANG_CI_LINT_VER: v1.31
GOLANG_CI_LINT_VER: v1.44.2
GOOS: ${{ matrix.target_os }}
GOARCH: ${{ matrix.target_arch }}
GOPROXY: https://proxy.golang.org

View File

@ -246,3 +246,16 @@ linters:
- exhaustive
- gci
- noctx
- exhaustivestruct
- gomoddirectives
- paralleltest
- tparallel
- wastedassign
- cyclop
- forbidigo
- tagliatelle
- thelper
- wrapcheck
- varnamelen
- forcetypeassert
- ireturn

View File

@ -97,7 +97,7 @@ dapr dashboard -k -p 9999
}
// search for dashboard service namespace in order:
// user-supplied namespace, dapr-system, default
// user-supplied namespace, dapr-system, default.
namespaces := []string{dashboardNamespace}
if dashboardNamespace != daprSystemNamespace {
namespaces = append(namespaces, daprSystemNamespace)
@ -115,12 +115,12 @@ dapr dashboard -k -p 9999
}
}
// if the service is not found, try to search all pods
// if the service is not found, try to search all pods.
if foundNamespace == "" {
ok, nspace := kubernetes.CheckPodExists(client, "", nil, dashboardSvc)
// if the service is found, tell the user to try with the found namespace
// if the service is still not found, throw an error
// if the service is found, tell the user to try with the found namespace.
// if the service is still not found, throw an error.
if ok {
print.InfoStatusEvent(os.Stdout, "Dapr dashboard found in namespace: %s. Run dapr dashboard -k -n %s to use this namespace.", nspace, nspace)
} else {
@ -129,7 +129,7 @@ dapr dashboard -k -p 9999
os.Exit(1)
}
// manage termination of port forwarding connection on interrupt
// manage termination of port forwarding connection on interrupt.
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt)
defer signal.Stop(signals)
@ -148,19 +148,19 @@ dapr dashboard -k -p 9999
os.Exit(1)
}
// initialize port forwarding
// initialize port forwarding.
if err = portForward.Init(); err != nil {
print.FailureStatusEvent(os.Stderr, "Error in port forwarding: %s\nCheck for `dapr dashboard` running in other terminal sessions, or use the `--port` flag to use a different port.\n", err)
os.Exit(1)
}
// block until interrupt signal is received
// block until interrupt signal is received.
go func() {
<-signals
portForward.Stop()
}()
// url for dashboard after port forwarding
// url for dashboard after port forwarding.
var webURL string = fmt.Sprintf("http://%s:%d", dashboardHost, dashboardLocalPort)
print.InfoStatusEvent(os.Stdout, fmt.Sprintf("Dapr dashboard found in namespace:\t%s", foundNamespace))
@ -174,7 +174,7 @@ dapr dashboard -k -p 9999
<-portForward.GetStop()
} else {
// Standalone mode
// Standalone mode.
err := standalone.NewDashboardCmd(dashboardLocalPort).Run()
if err != nil {
print.FailureStatusEvent(os.Stderr, "Dapr dashboard not found. Is Dapr installed?")

View File

@ -69,7 +69,7 @@ dapr invoke --unix-domain-socket --app-id target --method sample --verb GET
}
client := standalone.NewClient()
// TODO(@daixiang0): add Windows support
// TODO(@daixiang0): add Windows support.
if invokeSocket != "" {
if runtime.GOOS == "windows" {
print.FailureStatusEvent(os.Stderr, "The unix-domain-socket option is not supported on Windows")
@ -81,7 +81,7 @@ dapr invoke --unix-domain-socket --app-id target --method sample --verb GET
response, err := client.Invoke(invokeAppID, invokeAppMethod, bytePayload, invokeVerb, invokeSocket)
if err != nil {
err = fmt.Errorf("error invoking app %s: %s", invokeAppID, err)
err = fmt.Errorf("error invoking app %s: %w", invokeAppID, err)
print.FailureStatusEvent(os.Stderr, err.Error())
return
}

View File

@ -63,7 +63,7 @@ dapr publish --enable-domain-socket --publish-app-id myapp --pubsub target --top
}
client := standalone.NewClient()
// TODO(@daixiang0): add Windows support
// TODO(@daixiang0): add Windows support.
if publishSocket != "" {
if runtime.GOOS == "windows" {
print.FailureStatusEvent(os.Stderr, "The unix-domain-socket option is not supported on Windows")

View File

@ -85,12 +85,12 @@ dapr run --app-id myapp --app-port 3000 --app-protocol grpc -- go run main.go
}
if unixDomainSocket != "" {
// TODO(@daixiang0): add Windows support
// TODO(@daixiang0): add Windows support.
if runtime.GOOS == "windows" {
print.FailureStatusEvent(os.Stderr, "The unix-domain-socket option is not supported on Windows")
os.Exit(1)
} else {
// use unix domain socket means no port any more
// use unix domain socket means no port any more.
print.WarningStatusEvent(os.Stdout, "Unix domain sockets are currently a preview feature")
port = 0
grpcPort = 0

View File

@ -1,3 +1,4 @@
//go:build !windows
// +build !windows
/*

View File

@ -23,8 +23,8 @@ import (
"golang.org/x/sys/windows"
)
func setupShutdownNotify(sigCh chan os.Signal){
//This will catch Ctrl-C
func setupShutdownNotify(sigCh chan os.Signal) {
// This will catch Ctrl-C
signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT)
// Unlike Linux/Mac, you can't just send a SIGTERM from another process

View File

@ -115,5 +115,5 @@ func homeDir() string {
if h := os.Getenv("HOME"); h != "" {
return h
}
return os.Getenv("USERPROFILE") // windows
return os.Getenv("USERPROFILE") // windows.
}

View File

@ -57,7 +57,7 @@ func Init(config InitConfiguration) error {
stopSpinning := print.Spinner(os.Stdout, msg)
defer stopSpinning(print.Failure)
//nolint
err := install(config)
if err != nil {
return err
@ -71,7 +71,7 @@ func Init(config InitConfiguration) error {
func createNamespace(namespace string) error {
_, client, err := GetKubeConfigClient()
if err != nil {
return fmt.Errorf("can't connect to a Kubernetes cluster: %v", err)
return fmt.Errorf("can't connect to a Kubernetes cluster: %w", err)
}
ns := &v1.Namespace{
@ -98,7 +98,7 @@ func getVersion(version string) (string, error) {
var err error
version, err = cli_ver.GetDaprVersion()
if err != nil {
return "", fmt.Errorf("cannot get the latest release version: %s", err)
return "", fmt.Errorf("cannot get the latest release version: %w", err)
}
version = strings.TrimPrefix(version, "v")
}
@ -108,7 +108,7 @@ func getVersion(version string) (string, error) {
func createTempDir() (string, error) {
dir, err := ioutil.TempDir("", "dapr")
if err != nil {
return "", fmt.Errorf("error creating temp dir: %s", err)
return "", fmt.Errorf("error creating temp dir: %w", err)
}
return dir, nil
}

View File

@ -40,11 +40,11 @@ func Logs(appID, podName, namespace string) error {
pods, err := ListPods(client, namespace, nil)
if err != nil {
return fmt.Errorf("could not get logs %v", err)
return fmt.Errorf("could not get logs %w", err)
}
if podName == "" {
// no pod name specified. in case of multiple pods, the first one will be selected
// no pod name specified. in case of multiple pods, the first one will be selected.
var foundDaprPod bool
for _, pod := range pods.Items {
if foundDaprPod {
@ -52,7 +52,7 @@ func Logs(appID, podName, namespace string) error {
}
for _, container := range pod.Spec.Containers {
if container.Name == daprdContainerName {
// find app ID
// find app ID.
for i, arg := range container.Args {
if arg == appIDContainerArgName {
id := container.Args[i+1]
@ -74,12 +74,12 @@ func Logs(appID, podName, namespace string) error {
getLogsRequest := client.CoreV1().Pods(namespace).GetLogs(podName, &corev1.PodLogOptions{Container: daprdContainerName, Follow: false})
logStream, err := getLogsRequest.Stream(context.TODO())
if err != nil {
return fmt.Errorf("could not get logs. Please check pod-name (%s). Error - %v", podName, err)
return fmt.Errorf("could not get logs. Please check pod-name (%s). Error - %w", podName, err)
}
defer logStream.Close()
_, err = io.Copy(os.Stdout, logStream)
if err != nil {
return fmt.Errorf("could not get logs %v", err)
return fmt.Errorf("could not get logs %w", err)
}
return nil

View File

@ -35,7 +35,7 @@ import (
const (
systemConfigName = "daprsystem"
trustBundleSecretName = "dapr-trust-bundle" // nolint:gosec
warningDaysForCertExpiry = 30 // in days
warningDaysForCertExpiry = 30 // in days.
)
func IsMTLSEnabled() (bool, error) {
@ -77,7 +77,7 @@ func ExportTrustChain(outputDir string) error {
_, err := os.Stat(outputDir)
if os.IsNotExist(err) {
errDir := os.MkdirAll(outputDir, 0755)
errDir := os.MkdirAll(outputDir, 0o755)
if errDir != nil {
return err
}
@ -92,17 +92,17 @@ func ExportTrustChain(outputDir string) error {
issuerCert := secret.Data["issuer.crt"]
issuerKey := secret.Data["issuer.key"]
err = ioutil.WriteFile(filepath.Join(outputDir, "ca.crt"), ca, 0600)
err = ioutil.WriteFile(filepath.Join(outputDir, "ca.crt"), ca, 0o600)
if err != nil {
return err
}
err = ioutil.WriteFile(filepath.Join(outputDir, "issuer.crt"), issuerCert, 0600)
err = ioutil.WriteFile(filepath.Join(outputDir, "issuer.crt"), issuerCert, 0o600)
if err != nil {
return err
}
err = ioutil.WriteFile(filepath.Join(outputDir, "issuer.key"), issuerKey, 0600)
err = ioutil.WriteFile(filepath.Join(outputDir, "issuer.key"), issuerKey, 0o600)
if err != nil {
return err
}

View File

@ -133,10 +133,10 @@ func (pf *PortForward) Init() error {
}()
select {
// if `pf.run()` succeeds, block until terminated
// if `pf.run()` succeeds, block until terminated.
case <-pf.ReadyCh:
// if failure, causing a receive `<-failure` and returns the error
// if failure, causing a receive `<-failure` and returns the error.
case err := <-failure:
return err
}

View File

@ -31,5 +31,6 @@ type RunOutput struct {
// Run executes the application based on the run configuration.
func Run(config *RunConfig) (*RunOutput, error) {
//nolint
return nil, nil
}

View File

@ -64,6 +64,7 @@ func NewStatusClient() (*StatusClient, error) {
// List status for Dapr resources.
func (s *StatusClient) Status() ([]StatusOutput, error) {
//nolint
client := s.client
if client == nil {
return nil, errors.New("kubernetes client not initialized")
@ -98,7 +99,7 @@ func (s *StatusClient) Status() ([]StatusOutput, error) {
version := image[strings.IndexAny(image, ":")+1:]
status := ""
// loop through all replicas and update to Running/Healthy status only if all instances are Running and Healthy
// loop through all replicas and update to Running/Healthy status only if all instances are Running and Healthy.
healthy := "False"
running := true

View File

@ -155,7 +155,7 @@ func TestStatus(t *testing.T) {
ExitCode: 1,
},
}, false)
// delete pod's podstatus
// delete pod's podstatus.
pod.Status.ContainerStatuses = nil
pod.Status.Phase = v1.PodPending

View File

@ -10,7 +10,7 @@ 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.
*/
//nolint
package print
import (

View File

@ -30,8 +30,8 @@ import (
)
var (
runDataFile string = "dapr-run-data.ldj"
runDataLockFile string = "dapr-run-data.lock"
runDataFile = "dapr-run-data.ldj"
runDataLockFile = "dapr-run-data.lock"
)
type RunData struct {
@ -65,7 +65,7 @@ func DeleteRunDataFile() error {
func tryGetRunDataLock() (*lockfile.Lockfile, error) {
lockFile, err := lockfile.New(filepath.Join(os.TempDir(), runDataLockFile))
if err != nil {
// TODO: Log once we implement logging
// TODO: Log once we implement logging.
return nil, err
}

View File

@ -17,12 +17,11 @@ type DaprProcess interface {
List() ([]ListOutput, error)
}
type daprProcess struct {
}
type daprProcess struct{}
// Client is the interface the wraps all the methods exposed by the Dapr CLI.
type Client interface {
// Invoke is a command to invoke a remote or local dapr instance
// Invoke is a command to invoke a remote or local dapr instance.
Invoke(appID, method string, data []byte, verb string, socket string) (string, error)
// Publish is used to publish event to a topic in a pubsub for an app ID.
Publish(publishAppID, pubsubName, topic string, payload []byte, socket string) error

View File

@ -23,14 +23,14 @@ import (
// NewDashboardCmd creates the command to run dashboard.
func NewDashboardCmd(port int) *exec.Cmd {
// Use the default binary install location
// Use the default binary install location.
dashboardPath := defaultDaprBinPath()
binaryName := "dashboard"
if runtime.GOOS == daprWindowsOS {
binaryName = "dashboard.exe"
}
// Construct command to run dashboard
// Construct command to run dashboard.
return &exec.Cmd{
Path: filepath.Join(dashboardPath, binaryName),
Args: []string{binaryName, "--port", strconv.Itoa(port)},

View File

@ -74,7 +74,7 @@ func TestInvoke(t *testing.T) {
}
for _, socket := range []string{"", "/tmp"} {
// TODO(@daixiang0): add Windows support
// TODO(@daixiang0): add Windows support.
if runtime.GOOS == "windows" && socket != "" {
continue
}

View File

@ -190,7 +190,7 @@ func List() ([]ListOutput, error) {
listRow.Command = utils.TruncateString(run.appCmd, 20)
}
// filter only dashboard instance
// filter only dashboard instance.
if listRow.AppID != "" {
list = append(list, listRow)
}

View File

@ -84,7 +84,7 @@ func TestPublish(t *testing.T) {
topic: "test",
pubsubName: "test",
lo: ListOutput{
// empty appID
// empty appID.
Command: "test",
},
errString: "couldn't find a running Dapr instance",
@ -143,7 +143,7 @@ func TestPublish(t *testing.T) {
},
}
for _, socket := range []string{"", "/tmp"} {
// TODO(@daixiang0): add Windows support
// TODO(@daixiang0): add Windows support.
if runtime.GOOS == "windows" && socket != "" {
continue
}

View File

@ -177,12 +177,13 @@ func (meta *DaprMeta) portExists(port int) bool {
if port <= 0 {
return false
}
//nolint
_, ok := meta.ExistingPorts[port]
if ok {
return true
}
// try to listen on the port
// try to listen on the port.
listener, err := net.Listen("tcp", fmt.Sprintf(":%v", port))
if err != nil {
return true
@ -237,7 +238,7 @@ func (config *RunConfig) getArgs() []string {
if config.ConfigFile != "" {
sentryAddress := mtlsEndpoint(config.ConfigFile)
if sentryAddress != "" {
// mTLS is enabled locally, set it up
// mTLS is enabled locally, set it up.
args = append(args, "--enable-mtls", "--sentry-address", sentryAddress)
}
}
@ -256,7 +257,7 @@ func (config *RunConfig) getEnv() []string {
continue
}
if value, ok := valueField.(int); ok && value <= 0 {
// ignore unset numeric variables
// ignore unset numeric variables.
continue
}
@ -325,6 +326,7 @@ func getAppCommand(config *RunConfig) *exec.Cmd {
}
func Run(config *RunConfig) (*RunOutput, error) {
//nolint
err := config.validate()
if err != nil {
return nil, err
@ -335,6 +337,7 @@ func Run(config *RunConfig) (*RunOutput, error) {
return nil, err
}
//nolint
var appCMD *exec.Cmd = getAppCommand(config)
return &RunOutput{
DaprCMD: daprCMD,

View File

@ -128,10 +128,10 @@ func getEnv(key string, value interface{}) string {
}
func TestRun(t *testing.T) {
// Setup the components directory which is done at init time
// Setup the components directory which is done at init time.
setupRun(t)
// Setup the tearDown routine to run in the end
// Setup the tearDown routine to run in the end.
defer tearDownRun(t)
basicConfig := &RunConfig{

View File

@ -120,7 +120,7 @@ func Init(runtimeVersion, dashboardVersion string, dockerNetwork string, slimMod
var err error
runtimeVersion, err = cli_ver.GetDaprVersion()
if err != nil {
return fmt.Errorf("cannot get the latest release version: '%s'. Try specifying --runtime-version=<desired_version>", err)
return fmt.Errorf("cannot get the latest release version: '%w'. Try specifying --runtime-version=<desired_version>", err)
}
}
@ -150,47 +150,47 @@ func Init(runtimeVersion, dashboardVersion string, dockerNetwork string, slimMod
errorChan := make(chan error)
initSteps := []func(*sync.WaitGroup, chan<- error, string, string, string, string){}
if slimMode {
// Install 3 binaries in slim mode: daprd, dashboard, placement
// Install 3 binaries in slim mode: daprd, dashboard, placement.
wg.Add(3)
initSteps = append(initSteps, createSlimConfiguration)
} else if dashboardVersion != "" {
// Install 2 binaries: daprd, dashboard
// Install 2 binaries: daprd, dashboard.
wg.Add(2)
initSteps = append(initSteps, createComponentsAndConfiguration, runPlacementService, runRedis, runZipkin)
} else {
// Install 1 binaries: daprd
// Install 1 binaries: daprd.
wg.Add(1)
initSteps = append(initSteps, createComponentsAndConfiguration, runPlacementService, runRedis, runZipkin)
}
// Init other configurations, containers
// Init other configurations, containers.
wg.Add(len(initSteps))
msg := "Downloading binaries and setting up components..."
stopSpinning := print.Spinner(os.Stdout, msg)
defer stopSpinning(print.Failure)
// Make default components directory
// Make default components directory.
err = makeDefaultComponentsDir()
if err != nil {
return err
}
// Initialize daprd binary
// Initialize daprd binary.
go installBinary(&wg, errorChan, daprBinDir, runtimeVersion, daprRuntimeFilePrefix, dockerNetwork, cli_ver.DaprGitHubRepo)
// Initialize dashboard binary
// Initialize dashboard binary.
if dashboardVersion != "" {
go installBinary(&wg, errorChan, daprBinDir, dashboardVersion, dashboardFilePrefix, dockerNetwork, cli_ver.DashboardGitHubRepo)
}
if slimMode {
// Initialize placement binary only on slim install
// Initialize placement binary only on slim install.
go installBinary(&wg, errorChan, daprBinDir, runtimeVersion, placementServiceFilePrefix, dockerNetwork, cli_ver.DaprGitHubRepo)
}
for _, step := range initSteps {
// Run init on the configurations and containers
// Run init on the configurations and containers.
go step(&wg, errorChan, daprBinDir, runtimeVersion, dockerNetwork, imageRepositoryURL)
}
@ -211,7 +211,7 @@ func Init(runtimeVersion, dashboardVersion string, dockerNetwork string, slimMod
print.SuccessStatusEvent(os.Stdout, msg)
print.InfoStatusEvent(os.Stdout, "%s binary has been installed to %s.", daprRuntimeFilePrefix, daprBinDir)
if slimMode {
// Print info on placement binary only on slim install
// Print info on placement binary only on slim install.
print.InfoStatusEvent(os.Stdout, "%s binary has been installed to %s.", placementServiceFilePrefix, daprBinDir)
} else {
dockerContainerNames := []string{DaprPlacementContainerName, DaprRedisContainerName, DaprZipkinContainerName}
@ -231,12 +231,12 @@ func Init(runtimeVersion, dashboardVersion string, dockerNetwork string, slimMod
}
func prepareDaprInstallDir(daprBinDir string) error {
err := os.MkdirAll(daprBinDir, 0777)
err := os.MkdirAll(daprBinDir, 0o777)
if err != nil {
return err
}
err = os.Chmod(daprBinDir, 0777)
err = os.Chmod(daprBinDir, 0o777)
if err != nil {
return err
}
@ -257,7 +257,7 @@ func runZipkin(wg *sync.WaitGroup, errorChan chan<- error, dir, version string,
args := []string{}
if exists {
// do not create container again if it exists
// do not create container again if it exists.
args = append(args, "start", zipkinContainerName)
} else {
imageName := zipkinDockerImageName
@ -291,7 +291,7 @@ func runZipkin(wg *sync.WaitGroup, errorChan chan<- error, dir, version string,
if !runError {
errorChan <- parseDockerError("Zipkin tracing", err)
} else {
errorChan <- fmt.Errorf("docker %s failed with: %v", args, err)
errorChan <- fmt.Errorf("docker %s failed with: %w", args, err)
}
return
}
@ -310,7 +310,7 @@ func runRedis(wg *sync.WaitGroup, errorChan chan<- error, dir, version string, d
args := []string{}
if exists {
// do not create container again if it exists
// do not create container again if it exists.
args = append(args, "start", redisContainerName)
} else {
imageName := redisDockerImageName
@ -343,7 +343,7 @@ func runRedis(wg *sync.WaitGroup, errorChan chan<- error, dir, version string, d
if !runError {
errorChan <- parseDockerError("Redis state store", err)
} else {
errorChan <- fmt.Errorf("docker %s failed with: %v", args, err)
errorChan <- fmt.Errorf("docker %s failed with: %w", args, err)
}
return
}
@ -352,7 +352,7 @@ func runRedis(wg *sync.WaitGroup, errorChan chan<- error, dir, version string, d
// check if the container either exists and stopped or is running.
func confirmContainerIsRunningOrExists(containerName string, isRunning bool) (bool, error) {
// e.g. docker ps --filter name=dapr_redis --filter status=running --format {{.Names}}
// e.g. docker ps --filter name=dapr_redis --filter status=running --format {{.Names}}.
args := []string{"ps", "--all", "--filter", "name=" + containerName}
@ -364,11 +364,12 @@ func confirmContainerIsRunningOrExists(containerName string, isRunning bool) (bo
response, err := utils.RunCmdAndWait("docker", args...)
response = strings.TrimSuffix(response, "\n")
// If 'docker ps' failed due to some reason
// If 'docker ps' failed due to some reason.
if err != nil {
//nolint
return false, fmt.Errorf("unable to confirm whether %s is running or exists. error\n%v", containerName, err.Error())
}
// 'docker ps' worked fine, but the response did not have the container name
// 'docker ps' worked fine, but the response did not have the container name.
if response == "" || response != containerName {
if isRunning {
return false, fmt.Errorf("container %s is not running", containerName)
@ -380,9 +381,10 @@ func confirmContainerIsRunningOrExists(containerName string, isRunning bool) (bo
}
func parseDockerError(component string, err error) error {
//nolint
if exitError, ok := err.(*exec.ExitError); ok {
exitCode := exitError.ExitCode()
if exitCode == 125 { // see https://github.com/moby/moby/pull/14012
if exitCode == 125 { // see https://github.com/moby/moby/pull/14012.
return fmt.Errorf("failed to launch %s. Is it already running?", component)
}
if exitCode == 127 {
@ -393,6 +395,7 @@ func parseDockerError(component string, err error) error {
}
func isContainerRunError(err error) bool {
//nolint
if exitError, ok := err.(*exec.ExitError); ok {
exitCode := exitError.ExitCode()
return exitCode == 125
@ -409,7 +412,7 @@ func runPlacementService(wg *sync.WaitGroup, errorChan chan<- error, dir, versio
image = fmt.Sprintf("%s/%s", imageRepositoryURL, image)
}
// Use only image for latest version
// Use only image for latest version.
if version == latestVersion {
image = daprDockerImageName
}
@ -455,7 +458,7 @@ func runPlacementService(wg *sync.WaitGroup, errorChan chan<- error, dir, versio
if !runError {
errorChan <- parseDockerError("placement service", err)
} else {
errorChan <- fmt.Errorf("docker %s failed with: %v", args, err)
errorChan <- fmt.Errorf("docker %s failed with: %w", args, err)
}
return
}
@ -463,29 +466,29 @@ func runPlacementService(wg *sync.WaitGroup, errorChan chan<- error, dir, versio
}
func moveDashboardFiles(extractedFilePath string, dir string) (string, error) {
// Move /release/os/web directory to /web
// Move /release/os/web directory to /web.
oldPath := path_filepath.Join(path_filepath.Dir(extractedFilePath), "web")
newPath := path_filepath.Join(dir, "web")
err := os.Rename(oldPath, newPath)
if err != nil {
err = fmt.Errorf("failed to move dashboard files: %s", err)
err = fmt.Errorf("failed to move dashboard files: %w", err)
return "", err
}
// Move binary from /release/<os>/web/dashboard(.exe) to /dashboard(.exe)
// Move binary from /release/<os>/web/dashboard(.exe) to /dashboard(.exe).
err = os.Rename(extractedFilePath, path_filepath.Join(dir, path_filepath.Base(extractedFilePath)))
if err != nil {
err = fmt.Errorf("error moving %s binary to path: %s", path_filepath.Base(extractedFilePath), err)
err = fmt.Errorf("error moving %s binary to path: %w", path_filepath.Base(extractedFilePath), err)
return "", err
}
// Change the extracted binary file path to reflect the move above
// Change the extracted binary file path to reflect the move above.
extractedFilePath = path_filepath.Join(dir, path_filepath.Base(extractedFilePath))
// Remove the now-empty 'release' directory
// Remove the now-empty 'release' directory.
err = os.RemoveAll(path_filepath.Join(dir, "release"))
if err != nil {
err = fmt.Errorf("error moving dashboard files: %s", err)
err = fmt.Errorf("error moving dashboard files: %w", err)
return "", err
}
@ -513,7 +516,7 @@ func installBinary(wg *sync.WaitGroup, errorChan chan<- error, dir, version, bin
filepath, err := downloadFile(dir, fileURL)
if err != nil {
errorChan <- fmt.Errorf("error downloading %s binary: %s", binaryFilePrefix, err)
errorChan <- fmt.Errorf("error downloading %s binary: %w", binaryFilePrefix, err)
return
}
extractedFilePath := ""
@ -524,13 +527,13 @@ func installBinary(wg *sync.WaitGroup, errorChan chan<- error, dir, version, bin
extractedFilePath, err = untar(filepath, dir, binaryFilePrefix)
}
if err != nil {
errorChan <- fmt.Errorf("error extracting %s binary: %s", binaryFilePrefix, err)
errorChan <- fmt.Errorf("error extracting %s binary: %w", binaryFilePrefix, err)
return
}
err = os.Remove(filepath)
if err != nil {
errorChan <- fmt.Errorf("failed to remove archive: %s", err)
errorChan <- fmt.Errorf("failed to remove archive: %w", err)
return
}
@ -544,13 +547,13 @@ func installBinary(wg *sync.WaitGroup, errorChan chan<- error, dir, version, bin
binaryPath, err := moveFileToPath(extractedFilePath, dir)
if err != nil {
errorChan <- fmt.Errorf("error moving %s binary to path: %s", binaryFilePrefix, err)
errorChan <- fmt.Errorf("error moving %s binary to path: %w", binaryFilePrefix, err)
return
}
err = makeExecutable(binaryPath)
if err != nil {
errorChan <- fmt.Errorf("error making %s binary executable: %s", binaryFilePrefix, err)
errorChan <- fmt.Errorf("error making %s binary executable: %w", binaryFilePrefix, err)
return
}
@ -569,22 +572,22 @@ func createComponentsAndConfiguration(wg *sync.WaitGroup, errorChan chan<- error
}
var err error
// Make default components directory
// Make default components directory.
componentsDir := DefaultComponentsDirPath()
err = createRedisPubSub(redisHost, componentsDir)
if err != nil {
errorChan <- fmt.Errorf("error creating redis pubsub component file: %s", err)
errorChan <- fmt.Errorf("error creating redis pubsub component file: %w", err)
return
}
err = createRedisStateStore(redisHost, componentsDir)
if err != nil {
errorChan <- fmt.Errorf("error creating redis statestore component file: %s", err)
errorChan <- fmt.Errorf("error creating redis statestore component file: %w", err)
return
}
err = createDefaultConfiguration(zipkinHost, DefaultConfigFilePath())
if err != nil {
errorChan <- fmt.Errorf("error creating default configuration file: %s", err)
errorChan <- fmt.Errorf("error creating default configuration file: %w", err)
return
}
}
@ -595,29 +598,30 @@ func createSlimConfiguration(wg *sync.WaitGroup, errorChan chan<- error, _, _ st
// For --slim we pass empty string so that we do not configure zipkin.
err := createDefaultConfiguration("", DefaultConfigFilePath())
if err != nil {
errorChan <- fmt.Errorf("error creating default configuration file: %s", err)
errorChan <- fmt.Errorf("error creating default configuration file: %w", err)
return
}
}
func makeDefaultComponentsDir() error {
// Make default components directory
// Make default components directory.
componentsDir := DefaultComponentsDirPath()
//nolint
_, err := os.Stat(componentsDir)
if os.IsNotExist(err) {
errDir := os.MkdirAll(componentsDir, 0755)
errDir := os.MkdirAll(componentsDir, 0o755)
if errDir != nil {
return fmt.Errorf("error creating default components folder: %s", errDir)
return fmt.Errorf("error creating default components folder: %w", errDir)
}
}
os.Chmod(componentsDir, 0777)
os.Chmod(componentsDir, 0o777)
return nil
}
func makeExecutable(filepath string) error {
if runtime.GOOS != daprWindowsOS {
err := os.Chmod(filepath, 0777)
err := os.Chmod(filepath, 0o777)
if err != nil {
return err
}
@ -703,7 +707,7 @@ func untar(filepath, targetDir, binaryFilePrefix string) (string, error) {
foundBinary := ""
for {
header, err := tr.Next()
//nolint
if err == io.EOF {
break
} else if err != nil {
@ -712,7 +716,7 @@ func untar(filepath, targetDir, binaryFilePrefix string) (string, error) {
continue
}
// untar all files in archive
// untar all files in archive.
path, err := sanitizeExtractPath(targetDir, header.Name)
if err != nil {
return "", err
@ -737,7 +741,7 @@ func untar(filepath, targetDir, binaryFilePrefix string) (string, error) {
return "", err
}
// If the found file is the binary that we want to find, save it and return later
// If the found file is the binary that we want to find, save it and return later.
if strings.HasSuffix(header.Name, binaryFilePrefix) {
foundBinary = path
}
@ -763,7 +767,7 @@ func moveFileToPath(filepath string, installLocation string) (string, error) {
}
// #nosec G306
if err = ioutil.WriteFile(destFilePath, input, 0644); err != nil {
if err = ioutil.WriteFile(destFilePath, input, 0o644); err != nil {
if runtime.GOOS != daprWindowsOS && strings.Contains(err.Error(), "permission denied") {
err = errors.New(err.Error() + " - please run with sudo")
}
@ -921,7 +925,7 @@ func checkAndOverWriteFile(filePath string, b []byte) error {
_, err := os.Stat(filePath)
if os.IsNotExist(err) {
// #nosec G306
if err = ioutil.WriteFile(filePath, b, 0644); err != nil {
if err = ioutil.WriteFile(filePath, b, 0o644); err != nil {
return err
}
}

View File

@ -1,3 +1,4 @@
//go:build !windows
// +build !windows
/*

View File

@ -42,5 +42,3 @@ func Stop(appID string) error {
return fmt.Errorf("couldn't find app id %s", appID)
}

View File

@ -37,7 +37,7 @@ func removeContainers(uninstallPlacementContainer, uninstallAll bool, dockerNetw
if err != nil {
containerErrs = append(
containerErrs,
fmt.Errorf("could not remove %s image: %s", daprDockerImageName, err))
fmt.Errorf("could not remove %s image: %w", daprDockerImageName, err))
}
}
@ -64,7 +64,7 @@ func removeDockerContainer(containerErrs []error, containerName, network string)
if err != nil {
containerErrs = append(
containerErrs,
fmt.Errorf("could not remove %s container: %s", container, err))
fmt.Errorf("could not remove %s container: %w", container, err))
}
return containerErrs
}
@ -88,10 +88,10 @@ func Uninstall(uninstallAll bool, dockerNetwork string) error {
daprBinDir := defaultDaprBinPath()
placementFilePath := binaryFilePath(daprBinDir, placementServiceFilePrefix)
_, placementErr := os.Stat(placementFilePath) // check if the placement binary exists
_, placementErr := os.Stat(placementFilePath) // check if the placement binary exists.
uninstallPlacementContainer := os.IsNotExist(placementErr)
// Remove .dapr/bin
// Remove .dapr/bin.
err := removeDir(daprBinDir)
if err != nil {
print.WarningStatusEvent(os.Stdout, "WARNING: could not delete dapr bin dir: %s", daprBinDir)

View File

@ -63,7 +63,7 @@ func GetBuildInfo(version string) string {
out, err := exec.Command(daprCMD, "--build-info").Output()
if err != nil {
// try '--version' for older runtime version
// try '--version' for older runtime version.
out, err = exec.Command(daprCMD, "--version").Output()
}
if err != nil {

View File

@ -23,7 +23,7 @@ import (
)
func TestGetVersionsGithub(t *testing.T) {
// Ensure a clean environment
// Ensure a clean environment.
tests := []struct {
Name string
@ -134,7 +134,7 @@ func TestGetVersionsGithub(t *testing.T) {
}
func TestGetVersionsHelm(t *testing.T) {
// Ensure a clean environment
// Ensure a clean environment.
tests := []struct {
Name string

View File

@ -119,7 +119,7 @@ func DeleteCRD(crds []string) func(*testing.T) {
for _, crd := range crds {
output, err := spawn.Command("kubectl", "delete", "crd", crd)
if err != nil {
// CRD already deleted and not found
// CRD already deleted and not found.
require.Contains(t, output, "Error from server (NotFound)")
continue
} else {
@ -130,7 +130,7 @@ func DeleteCRD(crds []string) func(*testing.T) {
}
}
// Get Test Cases
// Get Test Cases.
func GetTestsOnInstall(details VersionDetails, opts TestOptions) []TestCase {
return []TestCase{
@ -146,7 +146,7 @@ func GetTestsOnInstall(details VersionDetails, opts TestOptions) []TestCase {
func GetTestsOnUninstall(details VersionDetails, opts TestOptions) []TestCase {
return []TestCase{
{"uninstall " + details.RuntimeVersion, uninstallTest(opts.UninstallAll)}, // waits for pod deletion
{"uninstall " + details.RuntimeVersion, uninstallTest(opts.UninstallAll)}, // waits for pod deletion.
{"crds exist on uninstall " + details.RuntimeVersion, CRDTest(details, opts)},
{"clusterroles not exist " + details.RuntimeVersion, ClusterRolesTest(details, opts)},
{"clusterrolebindings not exist " + details.RuntimeVersion, ClusterRoleBindingsTest(details, opts)},
@ -169,14 +169,14 @@ func MTLSTestOnInstallUpgrade(opts TestOptions) func(t *testing.T) {
require.Contains(t, output, "Mutual TLS is enabled in your Kubernetes cluster", "expected output to match")
}
// expiry
// expiry.
output, err = spawn.Command(daprPath, "mtls", "expiry")
require.NoError(t, err, "expected no error on querying for mtls expiry")
assert.Contains(t, output, "Root certificate expires in", "expected output to contain string")
assert.Contains(t, output, "Expiry date:", "expected output to contain string")
// export
// check that the dir does not exist now
// check that the dir does not exist now.
_, err = os.Stat("./certs")
if assert.Error(t, err) {
assert.True(t, os.IsNotExist(err), err.Error())
@ -186,7 +186,7 @@ func MTLSTestOnInstallUpgrade(opts TestOptions) func(t *testing.T) {
require.NoError(t, err, "expected no error on mtls export")
require.Contains(t, output, "Trust certs successfully exported to", "expected output to contain string")
// check export success
// check export success.
_, err = os.Stat("./certs")
require.NoError(t, err, "expected directory to exist")
_, err = os.Stat("./certs/ca.crt")
@ -205,9 +205,9 @@ func MTLSTestOnInstallUpgrade(opts TestOptions) func(t *testing.T) {
func ComponentsTestOnInstallUpgrade(opts TestOptions) func(t *testing.T) {
return func(t *testing.T) {
daprPath := getDaprPath()
// if dapr is installed
// if dapr is installed.
if opts.ApplyComponentChanges {
// apply any changes to the component
// apply any changes to the component.
t.Log("apply component changes")
output, err := spawn.Command("kubectl", "apply", "-f", "../testdata/statestore.yaml")
require.NoError(t, err, "expected no error on kubectl apply")
@ -245,12 +245,12 @@ func StatusTestOnInstallUpgrade(details VersionDetails, opts TestOptions) func(t
}
}
lines := strings.Split(output, "\n")[1:] // remove header of status
lines := strings.Split(output, "\n")[1:] // remove header of status.
t.Logf("dapr status -k infos: \n%s\n", lines)
for _, line := range lines {
cols := strings.Fields(strings.TrimSpace(line))
if len(cols) > 6 { // atleast 6 fields are verified from status (Age and created time are not)
if toVerify, ok := notFound[cols[0]]; ok { // get by name
if len(cols) > 6 { // atleast 6 fields are verified from status (Age and created time are not).
if toVerify, ok := notFound[cols[0]]; ok { // get by name.
require.Equal(t, DaprTestNamespace, cols[1], "namespace must match")
require.Equal(t, "True", cols[2], "healthly field must be true")
require.Equal(t, "Running", cols[3], "pods must be Running")
@ -385,7 +385,7 @@ func CRDTest(details VersionDetails, opts TestOptions) func(t *testing.T) {
}
}
// Unexported functions
// Unexported functions.
func (v VersionDetails) constructFoundMap(res Resource) map[string]bool {
foundMap := map[string]bool{}
@ -415,7 +415,7 @@ func homeDir() string {
if h := os.Getenv("HOME"); h != "" {
return h
}
return os.Getenv("USERPROFILE") // windows
return os.Getenv("USERPROFILE") // windows.
}
func getConfig() (*rest.Config, error) {
@ -482,8 +482,8 @@ func uninstallTest(all bool) func(t *testing.T) {
output, err := EnsureUninstall(all)
t.Log(output)
require.NoError(t, err, "uninstall failed")
// wait for pods to be deleted completely
// needed to verify status checks fails correctly
// wait for pods to be deleted completely.
// needed to verify status checks fails correctly.
podsDeleted := make(chan struct{})
done := make(chan struct{})
t.Log("waiting for pods to be deleted completely")
@ -511,9 +511,9 @@ func uninstallMTLSTest() func(t *testing.T) {
func componentsTestOnUninstall(all bool) func(t *testing.T) {
return func(t *testing.T) {
daprPath := getDaprPath()
// On Dapr uninstall CRDs are not removed, consequently the components will not be removed
// TODO Related to https://github.com/dapr/cli/issues/656
// For now the components remain
// On Dapr uninstall CRDs are not removed, consequently the components will not be removed.
// TODO Related to https://github.com/dapr/cli/issues/656.
// For now the components remain.
output, err := spawn.Command(daprPath, "components", "-k")
require.NoError(t, err, "expected no error on calling dapr components")
componentOutputCheck(t, output, all)
@ -523,7 +523,7 @@ func componentsTestOnUninstall(all bool) func(t *testing.T) {
return
}
// Manually remove components and verify output
// Manually remove components and verify output.
output, err = spawn.Command("kubectl", "delete", "-f", "../testdata/statestore.yaml")
require.NoError(t, err, "expected no error on kubectl apply")
require.Equal(t, "component.dapr.io \"statestore\" deleted\n", output, "expected output to match")
@ -531,7 +531,7 @@ func componentsTestOnUninstall(all bool) func(t *testing.T) {
require.NoError(t, err, "expected no error on calling dapr components")
lines := strings.Split(output, "\n")
// An extra empty line is there in output
// An extra empty line is there in output.
require.Equal(t, 2, len(lines), "expected only header of the output to remain")
}
}
@ -547,8 +547,8 @@ func statusTestOnUninstall() func(t *testing.T) {
}
func componentOutputCheck(t *testing.T, output string, all bool) {
lines := strings.Split(output, "\n")[1:] // remove header
// for fresh cluster only one component yaml has been applied
lines := strings.Split(output, "\n")[1:] // remove header.
// for fresh cluster only one component yaml has been applied.
fields := strings.Fields(lines[0])
if all {
@ -557,7 +557,7 @@ func componentOutputCheck(t *testing.T, output string, all bool) {
return
}
// Fields splits on space, so Created time field might be split again
// Fields splits on space, so Created time field might be split again.
assert.GreaterOrEqual(t, len(fields), 6, "expected at least 6 fields in components output")
assert.Equal(t, "statestore", fields[0], "expected name to match")
assert.Equal(t, "state.redis", fields[1], "expected type to match")
@ -627,7 +627,7 @@ func validatePodsOnInstallUpgrade(t *testing.T, details VersionDetails) {
func waitPodDeletion(t *testing.T, done, podsDeleted chan struct{}) {
for {
select {
case <-done: // if timeout was reached
case <-done: // if timeout was reached.
return
default:
break
@ -651,7 +651,7 @@ func waitPodDeletion(t *testing.T, done, podsDeleted chan struct{}) {
func waitAllPodsRunning(t *testing.T, namespace string, done, podsRunning chan struct{}) {
for {
select {
case <-done: // if timeout was reached
case <-done: // if timeout was reached.
return
default:
break
@ -667,7 +667,7 @@ func waitAllPodsRunning(t *testing.T, namespace string, done, podsRunning chan s
require.NoError(t, err, "error getting pods list from k8s")
count := 0
for _, item := range list.Items {
// Check pods running, and containers ready
// Check pods running, and containers ready.
if item.Status.Phase == core_v1.PodRunning && len(item.Status.ContainerStatuses) != 0 && item.Status.ContainerStatuses[0].Ready {
count++
}

View File

@ -210,7 +210,6 @@ func testInstallWithCustomImageRegsitry(t *testing.T) {
}
func verifyArtifactsAfterInstall(t *testing.T) {
// Verify Containers
cli, err := client.NewClientWithOpts(client.FromEnv)
require.NoError(t, err)
@ -483,12 +482,11 @@ func testStop(t *testing.T) {
t.Log(output)
require.NoError(t, err, "dapr stop failed")
assert.Contains(t, output, "app stopped successfully: dapr_e2e_stop")
}, "run", "--app-id", "dapr_e2e_stop", "--", "bash", "-c", "sleep 60 ; exit 1")
}
func testPublish(t *testing.T) {
var sub = &common.Subscription{
sub := &common.Subscription{
PubsubName: "pubsub",
Topic: "sample",
Route: "/orders",
@ -636,9 +634,7 @@ func testInvoke(t *testing.T) {
require.NoError(t, err, "dapr stop failed")
assert.Contains(t, output, "app stopped successfully: invoke_e2e")
}, "run", "--app-id", "invoke_e2e", "--app-port", "9987", "--unix-domain-socket", path)
}
}
func listOutputCheck(t *testing.T, output string) {

View File

@ -72,8 +72,7 @@ func WriteTable(writer io.Writer, csvContent string) {
}
func TruncateString(str string, maxLength int) string {
strLength := len(str)
if strLength <= maxLength {
if len(str) <= maxLength {
return str
}
@ -103,12 +102,13 @@ func RunCmdAndWait(name string, args ...string) (string, error) {
}
errB, err := ioutil.ReadAll(stderr)
if err != nil {
//nolint
return "", nil
}
err = cmd.Wait()
if err != nil {
// in case of error, capture the exact message
// in case of error, capture the exact message.
if len(errB) > 0 {
return "", errors.New(string(errB))
}
@ -130,7 +130,7 @@ func CreateDirectory(dir string) error {
if _, err := os.Stat(dir); !os.IsNotExist(err) {
return nil
}
return os.Mkdir(dir, 0777)
return os.Mkdir(dir, 0o777)
}
// IsDockerInstalled checks whether docker is installed/running.