validation

main
alex 2023-10-17 17:16:36 +02:00
parent 75d7f44a55
commit 2a637f3426
10 changed files with 62 additions and 71 deletions

View File

@ -47,7 +47,7 @@ MARIADB_PASSWORD=db_password
MARIADB_DATABASE_NAME=db_database_name`) MARIADB_DATABASE_NAME=db_database_name`)
config.LoadConfig() config.LoadConfig()
rslogger.InitLogger(false, config.Cfg.ColorizedOutput, config.Cfg.LogManagerServerUrl) rslogger.InitLogger(true, config.Cfg.ColorizedOutput, config.Cfg.LogManagerServerUrl)
if os.Getenv("DOCKER") != "" { if os.Getenv("DOCKER") != "" {
fmt.Println("Waiting for mariadb docker") fmt.Println("Waiting for mariadb docker")

View File

@ -123,3 +123,7 @@ func IsRobotNameInList(robotName string) bool {
return false return false
} }
func IsRobotIdInList(robotId string) bool {
return GetRobotById(robotId) != nil
}

View File

@ -2,6 +2,8 @@ package cache
import ( import (
"jannex/robot-control-manager/modules/structs" "jannex/robot-control-manager/modules/structs"
"jannex/robot-control-manager/modules/utils"
"sort"
"sync" "sync"
"git.ex.umbach.dev/Alex/roese-utils/rspagination" "git.ex.umbach.dev/Alex/roese-utils/rspagination"
@ -36,11 +38,16 @@ func GetAllUnauthorizedRobots(query rspagination.PageQuery) structs.Unauthorized
r = append(r, *v) r = append(r, *v)
} }
start, end := rspagination.GetPage(len(r), query.Page, 10) // sort after connected at
sort.SliceStable(r, func(i, j int) bool {
return r[i].ConnectedAt.After(r[j].ConnectedAt)
})
start, end := rspagination.GetPage(len(r), query.Page, utils.UnauthorizedRobotsPageLimit)
return structs.UnauthorizedRobotsResponse{ return structs.UnauthorizedRobotsResponse{
UnauthorizedRobots: r[start:end], UnauthorizedRobots: r[start:end],
TotalPages: rspagination.CalculateTotalPages(len(r), 10), TotalPages: rspagination.CalculateTotalPages(len(r), utils.UnauthorizedRobotsPageLimit),
} }
} }

View File

@ -42,54 +42,6 @@ type APIRobot struct {
CreatedAt time.Time CreatedAt time.Time
} }
/*
func (r *Robot) CountUpJobsWaiting() {
r.JobMutex.Lock()
defer r.JobMutex.Unlock()
r.JobsWaitingCount++
} */
/*
func (r *Robot) CountDownJobsWaiting() {
r.JobMutex.Lock()
defer r.JobMutex.Unlock()
if r.JobsWaitingCount > 0 {
r.JobsWaitingCount--
}
}
*/
/*
func (r *Robot) ProcessJobTask(jobId string) {
fmt.Println("wait for job", jobId)
if r.CurrentJobId == "" {
robot.UpdateRobotCurrentJobId(r, jobId)
}
if r.CurrentJobId != "" && r.CurrentJobId != jobId {
r.CountUpJobsWaiting()
}
for r.CurrentJobId != "" && r.CurrentJobId != jobId {
// wait for current job to finish
fmt.Println("job is processing", r.CurrentJobId, jobId, r.JobsWaitingCount)
time.Sleep(2 * time.Second)
}
robot.UpdateRobotCurrentJobId(r, jobId)
fmt.Println("processing job", jobId)
} */
/*
func (r *Robot) SetCurrentJobId(jobId string) {
r.JobMutex.Lock()
defer r.JobMutex.Unlock()
r.CurrentJobId = jobId
} */
type UnauthorizedRobot struct { type UnauthorizedRobot struct {
Id string Id string
Type uint8 Type uint8
@ -113,7 +65,7 @@ type FirstRequestBody struct {
// swagger:model StatusResponse // swagger:model StatusResponse
type StatusResponse struct { type StatusResponse struct {
Status string Status int
} }
// swagger:model RobotsResponse // swagger:model RobotsResponse
@ -142,6 +94,6 @@ type RobotFinishBody struct {
} }
type UpdateRobotBody struct { type UpdateRobotBody struct {
RobotId string RobotId string
Name string RobotName string
} }

View File

@ -3,12 +3,13 @@ package utils
const ( const (
RobotPingRetries = 3 RobotPingRetries = 3
RobotPingHandlerInterval = 5 // seconds RobotPingHandlerInterval = 5 // seconds
RobotsPageLimit = 10 RobotsPageLimit = 5
RobotsPermitJoinAutoDisable = 120 // seconds RobotsPermitJoinAutoDisable = 120 // seconds
UnauthorizedRobotsPageLimit = 10 UnauthorizedRobotsPageLimit = 5
minRobotNameLength = "2" minRobotNameLength = "2"
maxRobotNameLength = "30" maxRobotNameLength = "30"
maxJobNameLength = "30"
) )
const ( const (
@ -24,6 +25,12 @@ const (
RobotTypeYeet = 2 RobotTypeYeet = 2
) )
const (
ResponseStatusOk = 0
ResponseStatusError = 1
ResponseStatusOffline = 2
)
const ( const (
SSESentCmdUpdateRobotStatus = 1 SSESentCmdUpdateRobotStatus = 1
SSESentCmdAddUnauthorizedRobot = 2 SSESentCmdAddUnauthorizedRobot = 2
@ -38,7 +45,8 @@ const (
var ( var (
generalRules = map[string]string{ generalRules = map[string]string{
"Name": "required,min=" + minRobotNameLength + ",max=" + maxRobotNameLength, "RobotName": "required,min=" + minRobotNameLength + ",max=" + maxRobotNameLength,
"Type": "required,numeric", "Type": "required,numeric",
"JobName": "required,max=" + maxJobNameLength,
} }
) )

View File

@ -8,5 +8,6 @@ import (
func ValidatorInit() { func ValidatorInit() {
rsvalidator.Validate.RegisterStructValidationMapRules(generalRules, rsvalidator.Validate.RegisterStructValidationMapRules(generalRules,
structs.UpdateRobotBody{}) structs.UpdateRobotBody{},
structs.ControlBody{})
} }

View File

@ -55,16 +55,24 @@ func ControlRex(c *fiber.Ctx) error {
return c.SendStatus(fiber.StatusUnprocessableEntity) return c.SendStatus(fiber.StatusUnprocessableEntity)
} }
if r.Status == utils.RobotStatusOffline {
return c.JSON(structs.StatusResponse{Status: utils.ResponseStatusOffline})
}
if r.Status != utils.RobotStatusIdle && r.Status != utils.RobotStatusRunning {
}
robot.ProcessJobTask(r, body.JobId, body.JobName) robot.ProcessJobTask(r, body.JobId, body.JobName)
robot.UpdateRobotStatus(r, utils.RobotStatusRunning) robot.UpdateRobotStatus(r, utils.RobotStatusRunning)
if err := request.Request(fiber.MethodPost, r.Address+":5000/api/v1/control", body.Task); err != nil { if err := request.Request(fiber.MethodPost, r.Address+":5000/api/v1/control", body.Task); err != nil {
return c.JSON(structs.StatusResponse{Status: "err"}) return c.JSON(structs.StatusResponse{Status: utils.ResponseStatusError})
} }
robot.UpdateRobotStatus(r, utils.RobotStatusIdle) robot.UpdateRobotStatus(r, utils.RobotStatusIdle)
return c.JSON(structs.StatusResponse{Status: "ok"}) return c.JSON(structs.StatusResponse{Status: utils.ResponseStatusOk})
} }
func FinishControlRex(c *fiber.Ctx) error { func FinishControlRex(c *fiber.Ctx) error {

View File

@ -41,7 +41,9 @@ func SetPermitJoin(c *fiber.Ctx) error {
cache.SetPermitJoin(false) cache.SetPermitJoin(false)
logger.AddSystemLog("Permit join disabled") logger.AddSystemLog("Permit join disabled")
robot.PermitJoinTimer.Stop() if robot.PermitJoinTimer != nil {
robot.PermitJoinTimer.Stop()
}
} else { } else {
cache.SetPermitJoin(true) cache.SetPermitJoin(true)
logger.AddSystemLog("Permit join enabled") logger.AddSystemLog("Permit join enabled")

View File

@ -54,7 +54,6 @@ func FirstRequest(c *fiber.Ctx) error {
if !cache.IsPermitJoinEnabled() && foundRobot.Id == "" { if !cache.IsPermitJoinEnabled() && foundRobot.Id == "" {
logger.AddSystemLog("Unauthorized robot tried to connect with id %v and type %v", body.Id, utils.GetRobotTypeString(body.Type)) logger.AddSystemLog("Unauthorized robot tried to connect with id %v and type %v", body.Id, utils.GetRobotTypeString(body.Type))
return c.SendStatus(fiber.StatusForbidden) return c.SendStatus(fiber.StatusForbidden)
} }
@ -115,7 +114,7 @@ func FirstRequest(c *fiber.Ctx) error {
logger.AddSystemLog("Robot connected with id %v and type %v", body.Id, utils.GetRobotTypeString(body.Type)) logger.AddSystemLog("Robot connected with id %v and type %v", body.Id, utils.GetRobotTypeString(body.Type))
} }
return c.JSON(structs.StatusResponse{Status: "ok"}) return c.JSON(structs.StatusResponse{Status: utils.ResponseStatusOk})
} }
func addRobotSSEMessage(newRobot *structs.Robot) { func addRobotSSEMessage(newRobot *structs.Robot) {
@ -327,11 +326,11 @@ func UpdateRobot(c *fiber.Ctx) error {
foundRobot := cache.GetRobotById(body.RobotId) foundRobot := cache.GetRobotById(body.RobotId)
if foundRobot == nil || cache.IsRobotNameInList(body.Name) { if foundRobot == nil || cache.IsRobotNameInList(body.RobotName) {
return c.SendStatus(fiber.StatusUnprocessableEntity) return c.SendStatus(fiber.StatusUnprocessableEntity)
} }
foundRobot.Name = body.Name foundRobot.Name = body.RobotName
database.DB.Model(&structs.Robot{}). database.DB.Model(&structs.Robot{}).
Where("id = ?", foundRobot.Id). Where("id = ?", foundRobot.Id).
@ -342,7 +341,7 @@ func UpdateRobot(c *fiber.Ctx) error {
Body: body, Body: body,
}) })
logger.AddSystemLog("Robot with id %v name changed to %v", body.RobotId, body.Name) logger.AddSystemLog("Robot with id %v name changed to %v", body.RobotId, body.RobotName)
return c.SendStatus(fiber.StatusOK) return c.SendStatus(fiber.StatusOK)
} }

View File

@ -28,15 +28,25 @@ class RexRobot:
# generate random id # generate random id
def randomId(): def randomId():
return random.randint(0, 100000) return random.randint(0, 100)
# 10 random rexrobot # 10 random rexrobot
for i in range(10): RexRobot("test")
RexRobot(str(randomId()))
for i in range(1):
#RexRobot(str(randomId()))
RexRobot("759")
RexRobot("760")
RexRobot("761")
RexRobot("762")
RexRobot("763")
RexRobot("764")
RexRobot("765")
rex = RexRobot("test")
#rex = RexRobot("k5")
app = Flask(__name__) app = Flask(__name__)