Run golint on source code

This commit is contained in:
Prasad Ghangal 2018-12-31 11:11:48 +05:30
parent 3b3d768bdb
commit c3bfc46dde
13 changed files with 80 additions and 44 deletions

View File

@ -7,9 +7,13 @@ import (
"path/filepath"
)
// ConfigFileName is a name of kubeops configuration file
var ConfigFileName = "kubeopsconfig.yaml"
// Notify flag to toggle event notification
var Notify = true
// Config structure of configuration yaml file
type Config struct {
Resources []Resource
Recommendations bool
@ -17,24 +21,24 @@ type Config struct {
Events K8SEvents
}
// K8SEvents contains event types
type K8SEvents struct {
Types []string
}
// Resource contains resources to watch
type Resource struct {
Name string
Namespaces []string
Events []string
}
type Namespaces struct {
Namespaces []string `json:"namespaces"`
}
// Communications channels to send events to
type Communications struct {
Slack Slack
}
// Slack configuration to authentication and send notifications
type Slack struct {
Channel string
Token string

View File

@ -30,6 +30,7 @@ func findNamespace(ns string) string {
return ns
}
// RegisterInformers creates new informer controllers to watch k8s resources
func RegisterInformers(c *config.Config) {
// Register informers for resource lifecycle events
if len(c.Resources) > 0 {

View File

@ -11,16 +11,23 @@ import (
rbacV1 "k8s.io/api/rbac/v1"
)
// Level type to store event levels
type Level string
const (
Info Level = "info"
Warn Level = "warn"
Debug Level = "debug"
Error Level = "error"
// Info level
Info Level = "info"
// Warn level
Warn Level = "warn"
// Debug level
Debug Level = "debug"
// Error level
Error Level = "error"
// Critical level
Critical Level = "critical"
)
// Event to store required information from k8s objects
type Event struct {
Code string
Kind string
@ -40,6 +47,7 @@ type Event struct {
Action string
}
// LevelMap is a map of event type to Level
var LevelMap map[string]Level
func init() {
@ -52,6 +60,7 @@ func init() {
LevelMap["Normal"] = Info
}
// New extract required details from k8s object and returns new Event object
func New(object interface{}, eventType string, kind string) Event {
objectTypeMeta := utils.GetObjectTypeMetaData(object)
objectMeta := utils.GetObjectMetaData(object)

View File

@ -1,17 +1,16 @@
package filterengine
import (
//"fmt"
"github.com/infracloudio/kubeops/pkg/events"
"github.com/infracloudio/kubeops/pkg/filterengine/filters"
log "github.com/infracloudio/kubeops/pkg/logging"
)
var (
// DefaultFilterEngine contains default implementation for FilterEngine
DefaultFilterEngine FilterEngine
// Create filters list
// Filters contains the lists of available filters
// TODO: load this dynamically
Filters = []Filter{
filters.NewImageTagChecker(),
@ -19,15 +18,17 @@ var (
}
)
// FilterEngine has methods to register and run filters
type FilterEngine interface {
Run(interface{}, events.Event) events.Event
Register(Filter)
}
type DefaultFilters struct {
type defaultFilters struct {
FiltersList []Filter
}
// Filter has method to run filter
type Filter interface {
Run(interface{}, *events.Event)
}
@ -43,11 +44,11 @@ func init() {
// NewDefaultFilter creates new DefaultFilter object
func NewDefaultFilter() FilterEngine {
return &DefaultFilters{}
return &defaultFilters{}
}
// Run run the filters
func (f *DefaultFilters) Run(object interface{}, event events.Event) events.Event {
func (f *defaultFilters) Run(object interface{}, event events.Event) events.Event {
log.Logger.Debug("Filterengine running filters")
for _, f := range f.FiltersList {
f.Run(object, &event)
@ -56,7 +57,7 @@ func (f *DefaultFilters) Run(object interface{}, event events.Event) events.Even
}
// Register filter to engine
func (f *DefaultFilters) Register(filter Filter) {
func (f *defaultFilters) Register(filter Filter) {
log.Logger.Debug("Registering the filter", filter)
f.FiltersList = append(f.FiltersList, filter)
}

View File

@ -9,9 +9,11 @@ import (
apiV1 "k8s.io/api/core/v1"
)
// ImageTagChecker add recommendations to the event object if latest image tag is used in pod containers
type ImageTagChecker struct {
}
// NewImageTagChecker creates new ImageTagChecker object
func NewImageTagChecker() *ImageTagChecker {
return &ImageTagChecker{}
}

View File

@ -5,9 +5,12 @@ import (
extV1beta1 "k8s.io/api/extensions/v1beta1"
)
// IngressValidator checks if service and tls secret used in ingress specs is already present
// and adds recommendations to event struct accordingly
type IngressValidator struct {
}
// NewIngressValidator returns new IngressValidator object
func NewIngressValidator() *IngressValidator {
return &IngressValidator{}
}

View File

@ -9,11 +9,13 @@ import (
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// ValidService returns Service object is service given service exists in the given namespace
func ValidService(name, namespace string) (*apiV1.Service, error) {
serviceClient := utils.KubeClient.CoreV1().Services(namespace)
return serviceClient.Get(name, metaV1.GetOptions{})
}
// ValidServicePort returns valid Service object if given service with the port exists in the given namespace
func ValidServicePort(name, namespace string, port int32) (*apiV1.Service, error) {
serviceClient := utils.KubeClient.CoreV1().Services(namespace)
service, err := serviceClient.Get(name, metaV1.GetOptions{})
@ -28,11 +30,13 @@ func ValidServicePort(name, namespace string, port int32) (*apiV1.Service, error
return service, fmt.Errorf("Port %d is not exposed by the service %s", port, name)
}
// ValidSecret return Secret object if the secret is present in the specified object
func ValidSecret(name, namespace string) (*apiV1.Secret, error) {
secretClient := utils.KubeClient.CoreV1().Secrets(namespace)
return secretClient.Get(name, metaV1.GetOptions{})
}
// FindNamespaceFromService returns namespace from fully qualified domain name
func FindNamespaceFromService(service string) string {
ns := strings.Split(service, ".")
if len(ns) > 1 {

View File

@ -6,6 +6,7 @@ import (
"github.com/sirupsen/logrus"
)
// Logger global object for logging across the pkg/
var Logger = logrus.New()
func init() {

View File

@ -4,6 +4,7 @@ import (
"github.com/infracloudio/kubeops/pkg/events"
)
// Notifier to send event notification on the communication channels
type Notifier interface {
Send(events.Event) error
}

View File

@ -9,18 +9,17 @@ import (
"github.com/nlopes/slack"
)
var AttachmentColor map[events.Level]string
type SlackMessage struct {
}
var attachmentColor map[events.Level]string
// Slack contains Token for authentication with slack and Channel name to send notification to
type Slack struct {
Token string
Channel string
}
// NewSlack returns new Slack object
func NewSlack() Notifier {
AttachmentColor = map[events.Level]string{
attachmentColor = map[events.Level]string{
events.Info: "good",
events.Warn: "warning",
events.Debug: "good",
@ -39,6 +38,7 @@ func NewSlack() Notifier {
}
}
// Send event notification to slack
func (s *Slack) Send(event events.Event) error {
log.Logger.Info(fmt.Sprintf(">> Sending to slack: %+v", event))
@ -48,12 +48,13 @@ func (s *Slack) Send(event events.Event) error {
}
attachment := slack.Attachment{
Fields: []slack.AttachmentField{
slack.AttachmentField{
{
Title: "Kind",
Value: event.Kind,
Short: true,
},
slack.AttachmentField{
{
Title: "Name",
Value: event.Name,
Short: true,
@ -105,7 +106,7 @@ func (s *Slack) Send(event events.Event) error {
})
}
attachment.Color = AttachmentColor[event.Level]
attachment.Color = attachmentColor[event.Level]
params.Attachments = []slack.Attachment{attachment}
log.Logger.Infof("Sending message on %v with token %s", s.Channel, s.Token)

View File

@ -11,7 +11,7 @@ import (
log "github.com/infracloudio/kubeops/pkg/logging"
)
var AllowedKubectlCommands = map[string]bool{
var validKubectlCommands = map[string]bool{
"api-resources": true,
"api-versions": true,
"cluster-info": true,
@ -26,18 +26,18 @@ var AllowedKubectlCommands = map[string]bool{
"auth": true,
}
var AllowedNotifierCommands = map[string]bool{
var validNotifierCommands = map[string]bool{
"notifier": true,
"help": true,
"ping": true,
}
func ParseAndRunCommand(msg string) string {
func parseAndRunCommand(msg string) string {
args := strings.Split(msg, " ")
if AllowedKubectlCommands[args[0]] {
if validKubectlCommands[args[0]] {
return runKubectlCommand(args)
}
if AllowedNotifierCommands[args[0]] {
if validNotifierCommands[args[0]] {
return runNotifierCommand(args)
}
return "Command not supported. Please run '@kubeops help' to see supported commands"
@ -110,7 +110,7 @@ func runNotifierCommand(args []string) string {
func printHelp() string {
allowedKubectl := ""
for k, _ := range AllowedKubectlCommands {
for k := range validKubectlCommands {
allowedKubectl = allowedKubectl + k + ", "
}
helpMsg := "kubeops executes kubectl commands on k8s cluster and returns output.\n" +

View File

@ -9,11 +9,13 @@ import (
"github.com/nlopes/slack"
)
type SlackBot struct {
// Bot listens for user's message, execute commands and sends back the response
type Bot struct {
Token string
}
type SlackMessage struct {
// slackMessage contains message details to execute command and send back the result
type slackMessage struct {
ChannelID string
BotID string
InMessage string
@ -22,17 +24,19 @@ type SlackMessage struct {
RTM *slack.RTM
}
func NewSlackBot() *SlackBot {
// NewSlackBot returns new Bot object
func NewSlackBot() *Bot {
c, err := config.New()
if err != nil {
logging.Logger.Fatal(fmt.Sprintf("Error in loading configuration. Error:%s", err.Error()))
}
return &SlackBot{
return &Bot{
Token: c.Communications.Slack.Token,
}
}
func (s *SlackBot) Start() {
// Start starts the slacknot RTM connection and listens for messages
func (s *Bot) Start() {
api := slack.New(s.Token)
authResp, err := api.AuthTest()
if err != nil {
@ -55,7 +59,7 @@ func (s *SlackBot) Start() {
}
logging.Logger.Debugf("Slack incoming message: %+v", ev)
msg := strings.TrimPrefix(ev.Text, "<@"+botID+"> ")
sm := SlackMessage{
sm := slackMessage{
ChannelID: ev.Channel,
BotID: botID,
InMessage: msg,
@ -74,8 +78,8 @@ func (s *SlackBot) Start() {
}
}
func (sm *SlackMessage) HandleMessage() {
sm.OutMessage = ParseAndRunCommand(sm.InMessage)
func (sm *slackMessage) HandleMessage() {
sm.OutMessage = parseAndRunCommand(sm.InMessage)
sm.OutMsgLength = len(sm.OutMessage)
sm.Send()
}
@ -93,7 +97,7 @@ func formatAndSendLogs(rtm *slack.RTM, channelID, logs string, filename string)
}
}
func (sm SlackMessage) Send() {
func (sm slackMessage) Send() {
// Upload message as a file if too long
if sm.OutMsgLength >= 3990 {
params := slack.FileUploadParameters{

View File

@ -21,11 +21,15 @@ import (
)
var (
RtObjectMap map[string]runtime.Object
ResourceGetterMap map[string]cache.Getter
// RtObjectMap is a map of resource name to respective runtime object
RtObjectMap map[string]runtime.Object
// ResourceGetterMap is a map of resource name to resource Getter interface
ResourceGetterMap map[string]cache.Getter
// AllowedEventKindsMap is a map to filter valid event kinds
AllowedEventKindsMap map[EventKind]bool
// AllowedEventTypesMap is a map to filter valid event types
AllowedEventTypesMap map[string]bool
// KubeClient is a global kubernetes client to communicate to apiserver
KubeClient kubernetes.Interface
)
@ -50,15 +54,16 @@ func init() {
log.Logger.Fatal(err)
}
}
CreateMaps()
createMaps()
}
// EventKind used in AllowedEventKindsMap to filter event kinds
type EventKind struct {
Resource string
Namespace string
}
func CreateMaps() {
func createMaps() {
config, err := config.New()
if err != nil {
log.Logger.Fatal("Error in loading configuration. Error:%s", err.Error())
@ -176,7 +181,7 @@ func GetObjectMetaData(obj interface{}) metaV1.ObjectMeta {
return objectMeta
}
// GetObjectTypeMetadata returns typemetadata of the given object
// GetObjectTypeMetaData returns typemetadata of the given object
func GetObjectTypeMetaData(obj interface{}) metaV1.TypeMeta {
var typeMeta metaV1.TypeMeta