Skip to content

Commit

Permalink
Version 2
Browse files Browse the repository at this point in the history
  • Loading branch information
rickmills committed Oct 13, 2020
1 parent 4a66dbe commit 6a70c6f
Show file tree
Hide file tree
Showing 13 changed files with 661 additions and 22 deletions.
11 changes: 11 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,14 @@ src/*
!src/.cobra.yml
!src/serverauth.go
serverauth
dist/*
*.exe
*.exe~
*.dll
*.so
*.dylib
*.test
*.out
vendor/
*.tar.gz
build.sh
45 changes: 45 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
[submodule "github.com/fsnotify/fsnotify"]
path = github.com/fsnotify/fsnotify
url = https://github.com/fsnotify/fsnotify
[submodule "github.com/hashicorp/hcl"]
path = github.com/hashicorp/hcl
url = https://github.com/hashicorp/hcl
[submodule "github.com/magiconair/properties"]
path = github.com/magiconair/properties
url = https://github.com/magiconair/properties
[submodule "github.com/mitchellh/mapstructure"]
path = github.com/mitchellh/mapstructure
url = https://github.com/mitchellh/mapstructure
[submodule "github.com/pelletier/go-toml"]
path = github.com/pelletier/go-toml
url = https://github.com/pelletier/go-toml
[submodule "github.com/spf13/afero"]
path = github.com/spf13/afero
url = https://github.com/spf13/afero
[submodule "github.com/spf13/cast"]
path = github.com/spf13/cast
url = https://github.com/spf13/cast
[submodule "github.com/spf13/cobra"]
path = github.com/spf13/cobra
url = https://github.com/spf13/cobra
[submodule "github.com/spf13/jwalterweatherman"]
path = github.com/spf13/jwalterweatherman
url = https://github.com/spf13/jwalterweatherman
[submodule "github.com/spf13/viper"]
path = github.com/spf13/viper
url = https://github.com/spf13/viper
[submodule "github.com/subosito/gotenv"]
path = github.com/subosito/gotenv
url = https://github.com/subosito/gotenv
[submodule "golang.org/x/sys"]
path = golang.org/x/sys
url = https://golang.org/x/sys
[submodule "golang.org/x/text"]
path = golang.org/x/text
url = https://golang.org/x/text
[submodule "gopkg.in/yaml.v2"]
path = gopkg.in/yaml.v2
url = https://gopkg.in/yaml.v2
[submodule "github.com/spf13/pflag"]
path = github.com/spf13/pflag
url = https://github.com/spf13/pflag
65 changes: 65 additions & 0 deletions .goreleaser.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
builds:
# List of builds
- # First Build
env:
- CGO_ENABLED=0
main: main.go
# Set the binary output location to bin/ so archive will comply with Sensu Go Asset structure
binary: bin/{{ .ProjectName }}
goos:
- freebsd
- linux
- darwin
goarch:
- amd64
- 386
- arm
goarm:
- 5
- 6
- 7
ignore:
# TODO: add freebsd/arm support to gopsutil
- goos: freebsd
goarch: arm
targets:
- linux_386
- linux_amd64
- linux_arm_5
- linux_arm_6
- linux_arm_7
- linux_arm64
# - freebsd_amd64
# - freebsd_386
- darwin_amd64
checksum:
name_template: "{{ .ProjectName }}_{{ .Version }}_sha512-checksums.txt"
algorithm: sha512

archives:
- id: tar
format: tar.gz
files:
- LICENSE
- README.md
- CHANGELOG.md
nfpms:
-
id: serverauth
package_name: serverauth
file_name_template: "{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}"
builds:
- serverauth-agent-dev
vendor: ServerAuth.com
homepage: https://serverauth.com
maintainer: ServerAuth <info@serverauth.com>
description: ServerAuth management agent.
formats:
- deb
- rpm
dependencies:
- git
epoch: 1
release: 2
empty_folders:
- /etc/serverauth
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Changelog

## [2.0.0] - 2020-07-20
### Added
- New release system using Go Releaser
- Support for Server Monitoring Added
- Reworked the codebase to move to using Go Modules

7 changes: 7 additions & 0 deletions src/cmd/add.go → cmd/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,13 @@ var addCmd = &cobra.Command{
panic("There was a problem setting up the user account. Please try again or contact ServerAuth for assistance")
}

for _, data := range accounts {
if data.Username == username {
color.Green("The user %s is already configured - no changes needed.", data.Username)
os.Exit(1)
}
}

// Append the new account and update the config
accounts = append(accounts, Account{username, apikey})
viper.Set("accounts", accounts)
Expand Down
177 changes: 177 additions & 0 deletions cmd/monitor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
/*
Copyright © 2019 ServerAuth.com <info@serverauth.com>
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.
*/
package cmd

import (
"fmt"
"log"
"net/http"
"net/url"
"os"
"runtime"
"strconv"
"strings"
"time"

"github.com/fatih/color"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/disk"
"github.com/shirou/gopsutil/host"
"github.com/shirou/gopsutil/load"

"github.com/shirou/gopsutil/mem"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var actionCmd = &cobra.Command{
Use: "monitor",
Short: "Collect server metrics",
Long: `Collects the latest server monitoring metrics and sends them to your ServerAuth account.`,
Run: func(cmd *cobra.Command, args []string) {
// Read in the existing accounts and get ready for adding another user
viper.ReadInConfig()

var accounts []Account
configErr := viper.UnmarshalKey("accounts", &accounts)

if configErr != nil {
color.Red("There was a problem setting up the user account.\nPlease try again or contact ServerAuth for assistance.")
os.Exit(1)
}

// Get the organisation id
var orgId string
viper.UnmarshalKey("orgid", &orgId)

if len(orgId) <= 0 {
color.Red("The organisation id is missing from your ServerAuth configuration.\nPlease check you've correctly configured ServerAuth on this server and try again.")
os.Exit(1)
}

// Get the server api key
var serverAPIKey string
viper.UnmarshalKey("apikey", &serverAPIKey)

if len(serverAPIKey) <= 0 {
color.Red("The server API key is missing.\nPlease check you've correctly configured ServerAuth on this server and try again.")
os.Exit(1)
}

// Get the team api key
var teamAPIKey string
viper.UnmarshalKey("teamkey", &teamAPIKey)

if len(teamAPIKey) <= 0 {
color.Red("The team API key is missing.\nPlease check you've correctly configured ServerAuth on this server and try again.")
os.Exit(1)
}

// Get the base domain, which can optionally be overridden
var baseDomain string
viper.UnmarshalKey("basedomain", &baseDomain)

if len(baseDomain) <= 0 {
// No overridden base domain, fall back to the default
baseDomain = "https://api.serverauth.com/"
}

// Build the base url
baseURL := baseDomain + "monitoring"

// Get current system stats
memory, _ := mem.VirtualMemory()
loadAvg, _ := load.Avg()
cpuHw, _ := cpu.Info()
//percent, _ := cpu.Percent(time.Second, true)
uptime, _ := host.Uptime()
misc, _ := load.Misc()
platform, family, version, _ := host.PlatformInformation()
diskStat, err := disk.Usage("/")
currentTime := time.Now()
timeZone, timeOffset := currentTime.Zone()

// Create http client
httpClient := http.Client{
Timeout: time.Second * 10, // Maximum of 10 secs
}

form := url.Values{}

// Mem
form.Add("mem[total]", fmt.Sprint(memory.Total))
form.Add("mem[free]", fmt.Sprint(memory.Free))
form.Add("mem[used]", fmt.Sprint(memory.Used))
form.Add("mem[used_percent]", fmt.Sprint(memory.UsedPercent))

// Loadavg
form.Add("load[1]", fmt.Sprint(loadAvg.Load1))
form.Add("load[5]", fmt.Sprint(loadAvg.Load5))
form.Add("load[15]", fmt.Sprint(loadAvg.Load15))

// Processes
form.Add("procs[running]", fmt.Sprint(misc.ProcsRunning))
form.Add("procs[blocked]", fmt.Sprint(misc.ProcsBlocked))
form.Add("procs[total]", fmt.Sprint(misc.ProcsTotal))

// Generic CPU HW
form.Add("cpu", fmt.Sprint(cpuHw))

// Uptime
form.Add("uptime_seconds", fmt.Sprint(uptime))

// Platform info
form.Add("platform[name]", fmt.Sprint(platform))
form.Add("platform[family]", fmt.Sprint(family))
form.Add("platform[version]", fmt.Sprint(version))

// Disk info
form.Add("disk[total]", strconv.FormatUint(diskStat.Total, 10))
form.Add("disk[used]", strconv.FormatUint(diskStat.Used, 10))
form.Add("disk[free]", strconv.FormatUint(diskStat.Free, 10))
form.Add("disk[percent_free]", strconv.FormatFloat(diskStat.UsedPercent, 'f', 2, 64))
form.Add("disk[inodes_total]", strconv.FormatUint(diskStat.InodesTotal, 10))
form.Add("disk[inodes_used]", strconv.FormatUint(diskStat.InodesUsed, 10))
form.Add("disk[inodes_free]", strconv.FormatUint(diskStat.InodesFree, 10))

// Time info
form.Add("time[zone]", fmt.Sprint(timeZone))
form.Add("time[offset]", fmt.Sprint(timeOffset))
form.Add("time[now]", fmt.Sprint(currentTime.Unix()))

// Create a request
req, err := http.NewRequest(http.MethodPost, baseURL, strings.NewReader(form.Encode()))
if err != nil {
log.Fatal(err)
}

req.Header.Set("User-Agent", "ServerAuthAgent-v2.0.0;"+runtime.GOOS)
req.Header.Set("TeamApiKey", teamAPIKey)
req.Header.Set("ServerApiKey", serverAPIKey)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
httpClient.Do(req)
},
}

func init() {
rootCmd.AddCommand(actionCmd)
}
File renamed without changes.
18 changes: 4 additions & 14 deletions src/cmd/root.go → cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import (
"fmt"
"os"

"github.com/fatih/color"
"github.com/spf13/cobra"

"github.com/spf13/viper"
Expand All @@ -47,9 +46,6 @@ var rootCmd = &cobra.Command{
Use: "serverauth",
Short: "ServerAuth Server Agent",
Long: `The ServerAuth Server Agent is an easy to use command line application, allowing your server to automatically sync your teams SSH keys.`,
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
}

// Execute adds all child commands to the root command and sets flags appropriately.
Expand All @@ -63,12 +59,6 @@ func Execute() {

func init() {
cobra.OnInitialize(initConfig)

// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.

//rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.serverauth.yaml)")
}

// initConfig reads in config file and ENV variables if set.
Expand All @@ -80,8 +70,8 @@ func initConfig() {
viper.AutomaticEnv() // read in environment variables that match

// If a config file is found, read it in.
if err := viper.ReadInConfig(); err != nil {
color.Red("Your server is not configured to use ServerAuth!")
fmt.Println("Please follow the instructions on your server details page inside your ServerAuth account, or contact us for assistance.", viper.ConfigFileUsed())
}
// if err := viper.ReadInConfig(); err != nil {
// color.Red("Your server is not configured to use ServerAuth!")
// fmt.Println("Please follow the instructions on your server details page inside your ServerAuth account, or contact us for assistance.", viper.ConfigFileUsed())
// }
}
4 changes: 2 additions & 2 deletions src/cmd/sync.go → cmd/sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ var syncCmd = &cobra.Command{

if len(baseDomain) <= 0 {
// No overridden base domain, fall back to the default
baseDomain = "https://api.serverauth.com/v1/"
baseDomain = "https://api.serverauth.com/"
}

// Build the base url
Expand Down Expand Up @@ -109,7 +109,7 @@ var syncCmd = &cobra.Command{
}

// Set our custom useragent
req.Header.Set("User-Agent", "ServerAuthAgent-v1.0.0;"+runtime.GOOS)
req.Header.Set("User-Agent", "ServerAuthAgent-v2.0.0;"+runtime.GOOS)

// Run the request
res, getErr := httpClient.Do(req)
Expand Down
Loading

0 comments on commit 6a70c6f

Please sign in to comment.