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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Git Issue 5009 Fix #5045

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions agent/check_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,9 +226,11 @@ func (a *Agent) executeCheck(ctx context.Context, request *corev2.CheckRequest,
if len(checkAssets) == 0 {
logger.WithFields(fields).Debug("no assets defined for this check")
} else {

logger.WithFields(fields).Debug("fetching assets for check")
var err error
assets, err = asset.GetAll(ctx, a.assetGetter, checkAssets)

if err != nil {
a.sendFailure(event, fmt.Errorf("error getting assets for check: %s", err))
return
Expand Down
2 changes: 1 addition & 1 deletion agent/cmd/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import (
"strings"
"time"

"github.com/sensu/sensu-go/agent"
corev2 "github.com/sensu/core/v2"
"github.com/sensu/sensu-go/agent"
"github.com/sensu/sensu-go/asset"
"github.com/sensu/sensu-go/util/path"
"github.com/sensu/sensu-go/util/url"
Expand Down
18 changes: 18 additions & 0 deletions asset/boltdb_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"context"
"encoding/json"
"fmt"
"github.com/spf13/viper"
"os"
"path/filepath"

Expand All @@ -23,6 +24,7 @@
// ExpandDuration is the name of the prometheus summary vec used to track
// average latencies of asset expansion.
ExpandDuration = "sensu_go_asset_expand_duration"
FlagCacheDir = "cache-dir"
)

var (
Expand Down Expand Up @@ -121,7 +123,9 @@
// has proceeded to Update below will block here.
if err := b.db.View(func(tx *bolt.Tx) error {
// If the key exists, the bucket should already exist.

bucket := tx.Bucket(assetBucketName)

if bucket == nil {
return nil
}
Expand All @@ -130,6 +134,7 @@
if value != nil {
// deserialize asset
if err := json.Unmarshal(value, &localAsset); err == nil {
logger.Println(err)
return nil
}
}
Expand All @@ -148,6 +153,7 @@

if err := b.db.Update(func(tx *bolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists(assetBucketName)

if err != nil {
return err
}
Expand All @@ -166,14 +172,17 @@

// install the asset
tmpFile, err := b.fetchWithDuration(ctx, asset)

if err != nil {

return err
}
defer tmpFile.Close()
defer os.Remove(tmpFile.Name())

// verify
if err := b.verifier.Verify(tmpFile, asset.Sha512); err != nil {

// Attempt to retrieve the size of the downloaded asset
var size uint64
if fileInfo, err := tmpFile.Stat(); err == nil {
Expand All @@ -188,6 +197,7 @@

// expand
assetPath, err := b.expandWithDuration(tmpFile, asset)

if err != nil {
return err
}
Expand Down Expand Up @@ -241,6 +251,14 @@
}))
defer timer.ObserveDuration()

assetSHA := asset.Sha512
CacheDir := viper.GetString(FlagCacheDir)
fullPath := filepath.Join(CacheDir, assetSHA)

if err := CleanUp(fullPath); err != nil { //fix for git issue 5009
fmt.Errorf("error cleaning up the SHA dir: %s", err)

Check failure on line 259 in asset/boltdb_manager.go

View workflow job for this annotation

GitHub Actions / staticcheck (project)

Errorf doesn't have side effects and its return value is ignored (SA4017)
}

assetPath = filepath.Join(b.localStorage, asset.Sha512)
return assetPath, b.expander.Expand(tmpFile, assetPath)
}
15 changes: 13 additions & 2 deletions asset/expander.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ package asset
import (
"errors"
"fmt"
"io"

archiver "github.com/mholt/archiver/v3"
"io"
"os"

filetype "gopkg.in/h2non/filetype.v1"
filetype_types "gopkg.in/h2non/filetype.v1/types"
Expand Down Expand Up @@ -37,6 +37,17 @@ type namer interface {
Name() string
}

// Sudhanshu - CleanUp the SHA for the git issue 5009 fix. Making sure that the asset.db after creation gets updated properly.

func CleanUp(fullPath string) error {
errorSHA := os.RemoveAll(fullPath)
if errorSHA != nil {
return errorSHA
}
return nil

}

// Expand an archive to a target directory.
func (a *archiveExpander) Expand(archive io.ReadSeeker, targetDirectory string) error {
// detect the type of archive the asset is
Expand Down
34 changes: 34 additions & 0 deletions asset/expander_test.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,47 @@
package asset

import (
v2 "github.com/sensu/core/v2"
"os"
"path/filepath"
"testing"

"github.com/sensu/sensu-go/testing/testutil"
)

var asset *v2.Asset

Check failure on line 12 in asset/expander_test.go

View workflow job for this annotation

GitHub Actions / staticcheck (project)

var asset is unused (U1000)

// sudhanshu- Git issue 5009

func TestCleanUp(t *testing.T) {
t.Parallel()

// Create a temporary directory for testing
tmpDir := t.TempDir()

// Define the SHA and file name
SHAName := "shaAsset.tar"
SHAFilePath := filepath.Join(tmpDir, SHAName)

// Create a dummy file inside the temporary directory
SHAFile, err := os.Create(SHAFilePath)
if err != nil {
t.Fatalf("Failed to create dummy file: %v", err)
}
SHAFile.Close()

// Call CleanUp with the SHA of the dummy file and the temporary directory
err = CleanUp(SHAFilePath)
if err != nil {
t.Errorf("CleanUp returned an error: %v", err)
}

_, err = os.Stat(SHAFilePath)
if !os.IsNotExist(err) {
t.Errorf("CleanUp did not remove the dummy file as expected")
}
}

func TestExpandValidTar(t *testing.T) {
t.Parallel()
assetPath := getFixturePath("rubby-on-rails.tar")
Expand Down
3 changes: 3 additions & 0 deletions asset/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,12 @@ func (r RuntimeAssetSet) Scripts() (map[string]io.ReadCloser, error) {
// GetAll gets a list of assets with the provided getter.
func GetAll(ctx context.Context, getter Getter, assets []types.Asset) (RuntimeAssetSet, error) {
runtimeAssets := make([]*RuntimeAsset, 0, len(assets))

for _, asset := range assets {
runtimeAsset, err := getter.Get(ctx, &asset)

if err != nil {

return nil, err
}
if runtimeAsset != nil {
Expand Down
3 changes: 3 additions & 0 deletions cli/commands/asset/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ func AddCommand(cli *cli.SensuCli) *cobra.Command {

func addCommandExecute(cli *cli.SensuCli) func(cmd *cobra.Command, args []string) error {
return func(cmd *cobra.Command, args []string) error {
//sudhanshu/5009
//check if asset.db exits if not then re-create it also delete the SHA associated with it and re-create it.
//
// If no name is present print out usage
if len(args) != 1 {
_ = cmd.Help()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Changelog
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic
Versioning](http://semver.org/spec/v2.0.0.html).

## Unreleased

## [0.2.2] - 2021-03-31

### Changed
- Updated README

## [0.2.1] - 2021-03-10

### Changed
- Change release github action to use macos-latest so that macos cgo build works

## [0.2.0] - 2021-03-10

### Changed
- Updated goreleaser to build macOS version with cgo enabled

## [0.1.0] - 2020-12-30

### Added
- Initial release
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright 2020 Todd Campbell

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
[![Sensu Bonsai Asset](https://img.shields.io/badge/Bonsai-Download%20Me-brightgreen.svg?colorB=89C967&logo=sensu)](https://bonsai.sensu.io/assets/sensu/check-cpu-usage)
![Go Test](https://github.com/sensu/check-cpu-usage/workflows/Go%20Test/badge.svg)
![goreleaser](https://github.com/sensu/check-cpu-usage/workflows/goreleaser/badge.svg)

# Sensu CPU usage check

## Table of Contents
- [Overview](#overview)
- [Usage examples](#usage-examples)
- [Configuration](#configuration)
- [Asset registration](#asset-registration)
- [Check definition](#check-definition)
- [Installation from source](#installation-from-source)
- [Contributing](#contributing)

## Overview

The Sensu CPU usage check is a [Sensu Check][1] that provides alerting and
metrics for CPU usage. Metrics are provided in [nagios_perfdata][5] format.

**Note:** The macOS binary is built using [cgo][6] and may not be portable
across all versions of macOS.

## Usage examples

```
Check CPU usage and provide metrics

Usage:
check-cpu-usage [flags]
check-cpu-usage [command]

Available Commands:
help Help about any command
version Print the version number of this plugin

Flags:
-c, --critical float Critical threshold for overall CPU usage (default 90)
-w, --warning float Warning threshold for overall CPU usage (default 75)
-s, --sample-interval int Length of sample interval in seconds (default 2)
-h, --help help for check-cpu-usage

Use "check-cpu-usage [command] --help" for more information about a command.
```

## Configuration

### Asset registration

[Sensu Assets][2] are the best way to make use of this plugin. If you're not
using an asset, please consider doing so! If you're using sensuctl 5.13 with
Sensu Backend 5.13 or later, you can use the following command to add the asset:

```
sensuctl asset add sensu/check-cpu-usage
```

If you're using an earlier version of sensuctl, you can find the asset on the
[Bonsai Asset Index][3].

### Check definition

```yml
---
type: CheckConfig
api_version: core/v2
metadata:
name: check-cpu-usage
namespace: default
spec:
command: >-
check-cpu-usage
--critical 95
--warning 85
--sample-interval 2
output_metric_format: nagios_perfdata
output_metric_handlers:
- influxdb
subscriptions:
- system
runtime_assets:
- sensu/check-cpu-usage
```

## Installation from source

The preferred way of installing and deploying this plugin is to use it as an
Asset. If you would like to compile and install the plugin from source or
contribute to it, download the latest version or create an executable from this
source.

From the local path of the check-cpu-usage repository:

```
go build
```

## Contributing

For more information about contributing to this plugin, see [Contributing][4].

[1]: https://docs.sensu.io/sensu-go/latest/reference/checks/
[2]: https://docs.sensu.io/sensu-go/latest/reference/assets/
[3]: https://bonsai.sensu.io/assets/sensu/check-cpu-usage
[4]: https://github.com/sensu/sensu-go/blob/master/CONTRIBUTING.md
[5]: https://docs.sensu.io/sensu-go/latest/observability-pipeline/observe-schedule/collect-metrics-with-checks/#supported-output-metric-formats
[6]: https://golang.org/cmd/cgo/
Binary file not shown.
Binary file added home/raiden/Desktop/sensu/agent/cache/queue.db
Binary file not shown.
Loading