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

minor improvements #6

Merged
merged 1 commit into from
Aug 7, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions cli/commands/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ type CommandProps struct {

// Root builds and returns our root command
func Root(props *CommandProps) *cobra.Command {
var debug bool
var verbose bool
var silent bool

Expand All @@ -26,7 +27,7 @@ func Root(props *CommandProps) *cobra.Command {
// set logging verbosity for all loggers
level := zerolog.InfoLevel

if verbose {
if verbose || debug {
level = zerolog.DebugLevel
}

Expand All @@ -39,11 +40,12 @@ func Root(props *CommandProps) *cobra.Command {
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
return props.UI.Launch()
return props.UI.Launch(debug)
},
}

// Persistent flags available to all commands
cmd.PersistentFlags().BoolVar(&debug, "debug", false, "run in terminal log mode - no ui")
cmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "Show debug logs")
cmd.PersistentFlags().BoolVar(&silent, "silent", false, "disables all logging")

Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ require (
github.com/gdamore/tcell/v2 v2.6.0
github.com/golang/mock v1.6.0
github.com/imdario/mergo v0.3.16
github.com/jackpal/gateway v1.0.10
github.com/projectdiscovery/mapcidr v1.1.2
github.com/rivo/tview v0.0.0-20230621164836-6cc0565babaf
github.com/rs/zerolog v1.29.1
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,8 @@ github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLf
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
github.com/jackc/pgx/v5 v5.3.0 h1:/NQi8KHMpKWHInxXesC8yD4DhkXPrVhmnwYkjp9AmBA=
github.com/jackpal/gateway v1.0.10 h1:7g3fDo4Cd3RnTu6PzAfw6poO4Y81uNxrxFQFsBFSzJM=
github.com/jackpal/gateway v1.0.10/go.mod h1:+uPBgIllrbkwYCAoDkGSZbjvpre/bGYAFCYIcrH+LHs=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
Expand Down
8 changes: 8 additions & 0 deletions internal/core/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/robgonnella/ops/internal/event"
"github.com/robgonnella/ops/internal/logger"
"github.com/robgonnella/ops/internal/server"
"github.com/robgonnella/ops/internal/util"
)

// EventListener represents a registered listener for database events
Expand All @@ -30,6 +31,7 @@ type Core struct {
ctx context.Context
cancel context.CancelFunc
conf *config.Config
networkInfo *util.NetworkInfo
configService config.Service
discovery discovery.Service
serverService server.Service
Expand All @@ -43,6 +45,7 @@ type Core struct {

// New returns new core module for given configuration
func New(
networkInfo *util.NetworkInfo,
conf *config.Config,
configService config.Service,
serverService server.Service,
Expand All @@ -55,6 +58,7 @@ func New(
return &Core{
ctx: ctx,
cancel: cancel,
networkInfo: networkInfo,
conf: conf,
configService: configService,
discovery: discovery,
Expand Down Expand Up @@ -84,6 +88,10 @@ func (c *Core) Conf() config.Config {
return *c.conf
}

func (c *Core) NetworkInfo() util.NetworkInfo {
return *c.networkInfo
}

// CreateConfig creates a new config in the database
func (c *Core) CreateConfig(conf config.Config) error {
_, err := c.configService.Create(&conf)
Expand Down
20 changes: 18 additions & 2 deletions internal/core/core_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package core_test

import (
"context"
"net"
"sync"
"testing"

Expand All @@ -14,6 +15,7 @@ import (
mock_discovery "github.com/robgonnella/ops/internal/mock/discovery"
mock_server "github.com/robgonnella/ops/internal/mock/server"
"github.com/robgonnella/ops/internal/server"
"github.com/robgonnella/ops/internal/util"
"github.com/stretchr/testify/assert"
)

Expand All @@ -27,6 +29,14 @@ func TestCore(t *testing.T) {
mockConfig := mock_config.NewMockService(ctrl)
mockServerService := mock_server.NewMockService(ctrl)

networkInfo := &util.NetworkInfo{
Hostname: "hostname",
Interface: &net.Interface{},
Gateway: net.ParseIP("0.0.0.0"),
UserIP: net.ParseIP("0.0.0.0"),
Cidr: "0.0.0.0/0",
}

discoveryService := discovery.NewScannerService(
mockScanner,
mockDetailsScanner,
Expand All @@ -44,6 +54,7 @@ func TestCore(t *testing.T) {
}

coreService := core.New(
networkInfo,
&conf,
mockConfig,
mockServerService,
Expand Down Expand Up @@ -218,9 +229,14 @@ func TestCore(t *testing.T) {
Do(func([]string) {
wg.Done()
})
mockScanner.EXPECT().Scan().DoAndReturn(func() ([]*discovery.DiscoveryResult, error) {
mockScanner.EXPECT().Scan(gomock.Any()).DoAndReturn(func(rchan chan *discovery.DiscoveryResult) error {
defer wg.Done()
return discoveryResults, nil
go func() {
for _, r := range discoveryResults {
rchan <- r
}
}()
return nil
})
mockDetailsScanner.EXPECT().
GetServerDetails(gomock.Any(), "ip").
Expand Down
20 changes: 13 additions & 7 deletions internal/util/core.go → internal/core/create.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package util
package core

import (
"errors"

"github.com/robgonnella/ops/internal/config"
"github.com/robgonnella/ops/internal/core"
"github.com/robgonnella/ops/internal/discovery"
"github.com/robgonnella/ops/internal/exception"
"github.com/robgonnella/ops/internal/server"
"github.com/robgonnella/ops/internal/util"
"github.com/spf13/viper"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
Expand Down Expand Up @@ -37,7 +37,7 @@ func getSqliteDbConnection(dbFile string) (*gorm.DB, error) {
}

// getDefaultConfig creates and returns a default configuration
func getDefaultConfig(defaultCIDR string) *config.Config {
func getDefaultConfig(networkInfo *util.NetworkInfo) *config.Config {
user := viper.Get("user").(string)
identity := viper.Get("default-ssh-identity").(string)

Expand All @@ -48,12 +48,12 @@ func getDefaultConfig(defaultCIDR string) *config.Config {
Identity: identity,
Overrides: []config.SSHOverride{},
},
Targets: []string{defaultCIDR},
Targets: []string{networkInfo.Cidr},
}
}

// CreateNewAppCore creates and returns a new instance of *core.Core
func CreateNewAppCore(defaultCIDR string) (*core.Core, error) {
func CreateNewAppCore(networkInfo *util.NetworkInfo) (*Core, error) {
dbFile := viper.Get("database-file").(string)

db, err := getSqliteDbConnection(dbFile)
Expand All @@ -69,7 +69,7 @@ func CreateNewAppCore(defaultCIDR string) (*core.Core, error) {

if err != nil {
if errors.Is(err, exception.ErrRecordNotFound) {
conf = getDefaultConfig(defaultCIDR)
conf = getDefaultConfig(networkInfo)
conf, err = configService.Create(conf)

if err != nil {
Expand Down Expand Up @@ -97,5 +97,11 @@ func CreateNewAppCore(defaultCIDR string) (*core.Core, error) {
serverService,
)

return core.New(conf, configService, serverService, scannerService), nil
return New(
networkInfo,
conf,
configService,
serverService,
scannerService,
), nil
}
2 changes: 1 addition & 1 deletion internal/discovery/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ type DetailScanner interface {

// Scanner interface for scanning a network for devices
type Scanner interface {
Scan() ([]*DiscoveryResult, error)
Scan(resultChan chan *DiscoveryResult) error
Stop()
}

Expand Down
18 changes: 7 additions & 11 deletions internal/discovery/net.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,31 +49,29 @@ func NewNetScanner(targets []string) (*NetScanner, error) {
}, nil
}

func (s *NetScanner) Scan() ([]*DiscoveryResult, error) {
func (s *NetScanner) Scan(resultChan chan *DiscoveryResult) error {
if s.canceled {
return nil, errors.New("network scanner is in a canceled state")
return errors.New("network scanner is in a canceled state")
}

s.log.Info().Msg("Scanning network...")

results := []*DiscoveryResult{}

wg := &sync.WaitGroup{}

for _, ip := range s.targets {
s.semaphore <- struct{}{} // acquire
wg.Add(1)
go func(i string, w *sync.WaitGroup, res []*DiscoveryResult) {
go func(i string, w *sync.WaitGroup, res chan *DiscoveryResult) {
r := s.scanIP(i)
results = append(results, r)
res <- r
<-s.semaphore // release
w.Done()
}(ip, wg, results)
}(ip, wg, resultChan)
}

wg.Wait()

return results, nil
return nil
}

func (s *NetScanner) Stop() {
Expand All @@ -92,16 +90,14 @@ func (s *NetScanner) scanIP(ip string) *DiscoveryResult {
Status: server.StatusOffline,
}

s.log.Info().Str("ip", ip).Msg("Scanning target")
s.log.Debug().Str("ip", ip).Msg("Scanning target")

timeOut := time.Millisecond * 200
conn, err := net.DialTimeout("tcp", ip+":22", timeOut)

if err != nil {
r.Ports = []Port{{ID: 22, Status: PortClosed}}

s.log.Error().Err(err).Msg("network scanning error")

if _, ok := err.(*net.OpError); ok {
if strings.HasSuffix(err.Error(), "connect: connection refused") {
r.Status = server.StatusOnline
Expand Down
10 changes: 4 additions & 6 deletions internal/discovery/nmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func (s *NmapScanner) Stop() {
}

// scan targets and ports and return network results
func (s *NmapScanner) Scan() ([]*DiscoveryResult, error) {
func (s *NmapScanner) Scan(resultChan chan *DiscoveryResult) error {
s.log.Info().Msg("Scanning network...")

result, warnings, err := s.scanner.Run()
Expand All @@ -74,11 +74,9 @@ func (s *NmapScanner) Scan() ([]*DiscoveryResult, error) {

if err != nil {
s.log.Error().Err(err).Msg("encountered network scan error")
return nil, err
return err
}

discoverResults := []*DiscoveryResult{}

for _, host := range result.Hosts {
ports := []Port{}

Expand Down Expand Up @@ -122,8 +120,8 @@ func (s *NmapScanner) Scan() ([]*DiscoveryResult, error) {
Ports: ports,
}

discoverResults = append(discoverResults, res)
resultChan <- res
}

return discoverResults, nil
return nil
}
Loading