Commit 18776250 authored by brent's avatar brent

add task type manager

parent 5efb81a1
[dev]
kongadminurl = "http://192.168.1.10:8001"
[test]
kongadminurl = "http://43.198.252.255:8001"
[prod]
kongadminurl = "http://172.31.12.187:8001"
\ No newline at end of file
......@@ -5,11 +5,12 @@ mysqlhost = "192.168.1.211"
mysqlport = 3306
mysqldb = "liuxuzhong"
; mysqluser = "ai"
; mysqlpass = "RFnnKHRar5xk7TEF"
; mysqlhost = "43.198.252.255"
; mysqlport = 3306
; mysqldb = "ai"
[test]
mysqluser = "ai"
mysqlpass = "RFnnKHRar5xk7TEF"
mysqlhost = "43.198.252.255"
mysqlport = 3306
mysqldb = "ai"
[prod]
mysqluser = "ai"
......
......@@ -5,6 +5,13 @@ postgreshost = "192.168.1.10"
postgresport = 8812
postgresdb = "qdb"
[test]
postgresuser = "admin"
postgrespass = "quest"
postgreshost = "43.198.252.255"
postgresport = 8812
postgresdb = "qdb"
[prod]
postgresuser = "admin"
postgrespass = "quest"
......
......@@ -7,6 +7,15 @@ balancehost = "192.168.1.10:6379"
balancedb = 0
balancepass = ""
[test]
tokenhost = "43.198.252.255:6379"
tokendb = 0
tokenpass = "iH0g2CqzjI6SfercGwsT"
balancehost = "43.198.252.255:6379"
balancedb = 0
balancepass = "iH0g2CqzjI6SfercGwsT"
[prod]
tokenhost = "172.31.12.187:6379"
......
package controllers
import (
"ai_developer_admin/libs/cronjob"
"ai_developer_admin/libs/mysql"
"ai_developer_admin/libs/odysseus"
"ai_developer_admin/libs/postgres"
"ai_developer_admin/libs/redis"
"ai_developer_admin/libs/utils"
"ai_developer_admin/models"
"encoding/json"
"fmt"
......@@ -15,6 +17,7 @@ import (
)
var format = "2006-01-02T15:04:05.000000Z"
var layout = "2006-01-02T15:04:05"
type TaskController struct {
MainController
......@@ -45,17 +48,20 @@ func (server *TaskController) Bills() {
return
}
currentTime := time.Now()
if appRequest.EndTime == nil {
if appRequest.EndTime == "" {
endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, currentTime.Location())
appRequest.EndTime = &endTime
appRequest.EndTime = fmt.Sprintf(endTime.Format(format))
}
if appRequest.StartTime == nil {
if appRequest.StartTime == "" {
temp := fmt.Sprintf("-%dh", 24*7)
m, _ := time.ParseDuration(temp)
tempTime := currentTime.Add(m)
tempTime = time.Date(tempTime.Year(), tempTime.Month(), tempTime.Day(), 0, 0, 0, 0, tempTime.Location())
appRequest.StartTime = &tempTime
appRequest.StartTime = fmt.Sprintf(tempTime.Format(format))
}
startTimeIn, _ := time.Parse(layout, appRequest.StartTime)
endTimeIn, _ := time.Parse(layout, appRequest.EndTime)
if appRequest.Page == 0 {
appRequest.Page = 1
}
......@@ -66,12 +72,12 @@ func (server *TaskController) Bills() {
offset := (appRequest.Page - 1) * appRequest.Size
if appRequest.EndTime.Before(*appRequest.StartTime) {
if endTimeIn.Before(startTimeIn) {
server.respond(models.BusinessFailed, "起始时间不能大于结束时间")
return
}
startTime := fmt.Sprintf(appRequest.StartTime.Format(format))
endTime := fmt.Sprintf(appRequest.EndTime.Format(format))
startTime := fmt.Sprintf(startTimeIn.Format(format))
endTime := fmt.Sprintf(endTimeIn.Format(format))
sql := fmt.Sprintf("SELECT time,sum(fee) AS fee FROM bills WHERE uid='%d' and time >= '%s' and time <= '%s' SAMPLE BY 1M ALIGN TO CALENDAR ORDER BY time DESC LIMIT %d,%d;", info.UserID, startTime, endTime, offset, appRequest.Size)
counts, err := postgres.CountTasks(sql)
if err != nil {
......@@ -110,9 +116,11 @@ func (server *TaskController) BillDetails() {
timeCondition := ""
startTime := ""
endTime := ""
if appRequest.StartTime != nil && appRequest.EndTime != nil {
startTime = fmt.Sprintf(appRequest.StartTime.Format(format))
endTime = fmt.Sprintf(appRequest.EndTime.Format(format))
if appRequest.StartTime != "" && appRequest.EndTime != "" {
temp, _ := time.Parse(layout, appRequest.StartTime)
startTime = fmt.Sprintf(temp.Format(format))
temp, _ = time.Parse(layout, appRequest.EndTime)
endTime = fmt.Sprintf(temp.Format(format))
timeCondition = fmt.Sprintf(" and time >= '%s' and time <= '%s'", startTime, endTime)
}
sql := fmt.Sprintf("SELECT id,type,time,fee,result FROM bills WHERE uid='%d'%s ORDER BY time DESC LIMIT %d,%d;", info.UserID, timeCondition, offset, appRequest.Size)
......@@ -161,7 +169,7 @@ func (server *TaskController) Tasks() {
body := server.Ctx.Input.RequestBody
appRequest := models.AppRequest{}
err := json.Unmarshal(body, &appRequest) //解析body中数据
logs.Debug("appRequest", appRequest)
logs.Debug("appRequest", appRequest, string(body))
if err != nil {
server.respond(models.NoRequestBody, err.Error())
return
......@@ -180,26 +188,58 @@ func (server *TaskController) Tasks() {
timeCondition := ""
startTime := ""
endTime := ""
if appRequest.StartTime == nil && appRequest.EndTime != nil {
if appRequest.StartTime == "" && appRequest.EndTime != "" {
server.respond(models.MissingParameter, "缺少开始时间")
return
}
if appRequest.StartTime != nil && appRequest.EndTime == nil {
if appRequest.StartTime != "" && appRequest.EndTime == "" {
server.respond(models.MissingParameter, "缺少结束时间")
return
}
if appRequest.StartTime != nil && appRequest.EndTime != nil {
startTime = fmt.Sprintf(appRequest.StartTime.Format(format))
endTime = fmt.Sprintf(appRequest.EndTime.Format(format))
timeCondition = fmt.Sprintf(" and time >= '%s' and time <= '%s'", startTime, endTime)
if appRequest.StartTime != "" && appRequest.EndTime != "" {
if timeCondition == "" {
timeCondition = "WHERE"
}
temp, _ := time.Parse(layout, appRequest.StartTime)
startTime = fmt.Sprintf(temp.Format(format))
temp, _ = time.Parse(layout, appRequest.EndTime)
endTime = fmt.Sprintf(temp.Format(format))
timeCondition = fmt.Sprintf("%s time >= '%s' and time <= '%s'", timeCondition, startTime, endTime)
if appRequest.ProfitAcc != "" || appRequest.WorkerAcc != "" {
timeCondition = fmt.Sprintf("%s and", timeCondition)
}
}
if appRequest.ProfitAcc != "" {
timeCondition = fmt.Sprintf(" and profit_acc = '%s'", appRequest.ProfitAcc)
if timeCondition == "" {
timeCondition = "WHERE"
}
timeCondition = fmt.Sprintf("%s profit_acc = '%s'", timeCondition, appRequest.ProfitAcc)
if appRequest.WorkerAcc != "" {
timeCondition = fmt.Sprintf("%s and", timeCondition)
}
}
if appRequest.WorkerAcc != "" {
timeCondition = fmt.Sprintf(" and worker_acc = '%s'", appRequest.WorkerAcc)
}
sql := fmt.Sprintf("SELECT id,type,time,workload,profit_acc,worker_acc,result FROM bills WHERE %s ORDER BY time DESC LIMIT %d,%d;", timeCondition, offset, appRequest.Size)
if timeCondition == "" {
timeCondition = "WHERE"
}
timeCondition = fmt.Sprintf("%s worker_acc = '%s'", timeCondition, appRequest.WorkerAcc)
}
//qb, _ := orm.NewQueryBuilder("mysql")
//
//qb.Select("id", "type", "time", "workload", "profit_acc", "worker_acc", "result").
// From("bills").
// Where("profit_acc = ?").
// And("worker_acc = ?").
// And("time >= ?").
// And("time <= ?").
// OrderBy("time").Desc()
//testSql := qb.String()
//testSql = fmt.Sprintf("%s LIMIT %d,%d;", testSql, offset, appRequest.Size)
//
//temp, err1 := postgres.QueryTset(testSql, appRequest.WorkerAcc, appRequest.ProfitAcc, startTime, endTime)
//logs.Debug("QueryTset = %s", temp, err1.Error())
sql := fmt.Sprintf("SELECT id,type,time,workload,profit_acc,worker_acc,result FROM bills %s ORDER BY time DESC LIMIT %d,%d;", timeCondition, offset, appRequest.Size)
data, err := postgres.QueryBills(sql)
if err != nil {
server.respond(models.BusinessFailed, err.Error())
......@@ -234,6 +274,79 @@ func (server *TaskController) Tasks() {
server.respond(http.StatusOK, "", responseTasks)
}
func (server *TaskController) TasksPerDay() {
body := server.Ctx.Input.RequestBody
appRequest := models.AppRequest{}
err := json.Unmarshal(body, &appRequest) //解析body中数据
logs.Debug("appRequest", appRequest)
if err != nil {
server.respond(models.NoRequestBody, err.Error())
return
}
if appRequest.StartTime == "" && appRequest.EndTime != "" {
server.respond(models.MissingParameter, "缺少开始时间")
return
}
if appRequest.StartTime != "" && appRequest.EndTime == "" {
server.respond(models.MissingParameter, "缺少结束时间")
return
}
tempLayout := layout
if appRequest.EndTime == "" && appRequest.StartTime == "" {
tempLayout = format
}
currentTime := time.Now()
if appRequest.EndTime == "" {
endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, currentTime.Location())
appRequest.EndTime = fmt.Sprintf(endTime.Format(format))
}
if appRequest.StartTime == "" {
temp := fmt.Sprintf("-%dh", 24*7)
m, _ := time.ParseDuration(temp)
tempTime := currentTime.Add(m)
tempTime = time.Date(tempTime.Year(), tempTime.Month(), tempTime.Day(), 0, 0, 0, 0, tempTime.Location())
appRequest.StartTime = fmt.Sprintf(tempTime.Format(format))
}
startTimeIn, _ := time.Parse(tempLayout, appRequest.StartTime)
endTimeIn, _ := time.Parse(tempLayout, appRequest.EndTime)
if endTimeIn.Before(startTimeIn) {
server.respond(models.BusinessFailed, "起始时间不能大于结束时间")
return
}
timeCondition := ""
if appRequest.ProfitAcc != "" {
timeCondition = fmt.Sprintf("%s and profit_acc = '%s'", timeCondition, appRequest.ProfitAcc)
}
if appRequest.WorkerAcc != "" {
timeCondition = fmt.Sprintf("%s and worker_acc = '%s'", timeCondition, appRequest.WorkerAcc)
}
startTime := fmt.Sprintf(startTimeIn.Format(format))
endTime := fmt.Sprintf(endTimeIn.Format(format))
dates := utils.SplitDate(startTime, endTime, format)
sql := fmt.Sprintf("SELECT time,count(*) FROM bills WHERE time >= '%s' and time <= '%s' %s SAMPLE BY 1d ALIGN TO CALENDAR;", startTime, endTime, timeCondition)
counts, err := postgres.CountTasks(sql)
if err != nil {
server.respond(models.BusinessFailed, err.Error())
return
}
for _, value := range dates {
tempDate := findTime(counts, value)
if tempDate != nil {
reTask := models.TaskCount{
Type: "0",
Time: *tempDate,
Count: "0",
ApiPath: "",
}
counts = append(counts, reTask)
}
}
server.respond(http.StatusOK, "", counts)
}
func (server *TaskController) UserTasks() {
info, err := server.Check()
if err != nil {
......@@ -262,9 +375,11 @@ func (server *TaskController) UserTasks() {
timeCondition := ""
startTime := ""
endTime := ""
if appRequest.StartTime != nil && appRequest.EndTime != nil {
startTime = fmt.Sprintf(appRequest.StartTime.Format(format))
endTime = fmt.Sprintf(appRequest.EndTime.Format(format))
if appRequest.StartTime != "" && appRequest.EndTime != "" {
temp, _ := time.Parse(layout, appRequest.StartTime)
startTime = fmt.Sprintf(temp.Format(format))
temp, _ = time.Parse(layout, appRequest.EndTime)
endTime = fmt.Sprintf(temp.Format(format))
timeCondition = fmt.Sprintf(" and time >= '%s' and time <= '%s'", startTime, endTime)
}
//qb.Select("id", "type", "time", "fee", "in_len").From("tasks").Where("uid=?").And("time>='?'").And("time<='?").OrderBy("time").Desc().Offset(int(offset)).Limit(int(appRequest.Size))
......@@ -341,32 +456,59 @@ func (server *TaskController) UserTasksPerDay() {
server.respond(models.NoRequestBody, err.Error())
return
}
if appRequest.StartTime == "" && appRequest.EndTime != "" {
server.respond(models.MissingParameter, "缺少开始时间")
return
}
if appRequest.StartTime != "" && appRequest.EndTime == "" {
server.respond(models.MissingParameter, "缺少结束时间")
return
}
tempLayout := layout
if appRequest.EndTime == "" && appRequest.StartTime == "" {
tempLayout = format
}
currentTime := time.Now()
if appRequest.EndTime == nil {
if appRequest.EndTime == "" {
endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, currentTime.Location())
appRequest.EndTime = &endTime
appRequest.EndTime = fmt.Sprintf(endTime.Format(format))
}
if appRequest.StartTime == nil {
if appRequest.StartTime == "" {
temp := fmt.Sprintf("-%dh", 24*7)
m, _ := time.ParseDuration(temp)
tempTime := currentTime.Add(m)
tempTime = time.Date(tempTime.Year(), tempTime.Month(), tempTime.Day(), 0, 0, 0, 0, tempTime.Location())
appRequest.StartTime = &tempTime
appRequest.StartTime = fmt.Sprintf(tempTime.Format(format))
}
startTimeIn, _ := time.Parse(tempLayout, appRequest.StartTime)
endTimeIn, _ := time.Parse(tempLayout, appRequest.EndTime)
if appRequest.EndTime.Before(*appRequest.StartTime) {
if endTimeIn.Before(startTimeIn) {
server.respond(models.BusinessFailed, "起始时间不能大于结束时间")
return
}
startTime := fmt.Sprintf(appRequest.StartTime.Format(format))
endTime := fmt.Sprintf(appRequest.EndTime.Format(format))
startTime := fmt.Sprintf(startTimeIn.Format(format))
endTime := fmt.Sprintf(endTimeIn.Format(format))
dates := utils.SplitDate(startTime, endTime, format)
sql := fmt.Sprintf("SELECT time,count(*) FROM tasks WHERE uid='%d' and time >= '%s' and time <= '%s' SAMPLE BY 1d ALIGN TO CALENDAR;", info.UserID, startTime, endTime)
counts, err := postgres.CountTasks(sql)
if err != nil {
server.respond(models.BusinessFailed, err.Error())
return
}
for _, value := range dates {
tempDate := findTime(counts, value)
if tempDate != nil {
reTask := models.TaskCount{
Type: "0",
Time: *tempDate,
Count: "0",
ApiPath: "",
}
counts = append(counts, reTask)
}
}
server.respond(http.StatusOK, "", counts)
}
......@@ -384,26 +526,41 @@ func (server *TaskController) UserTaskTypePerDay() {
server.respond(models.NoRequestBody, err.Error())
return
}
if appRequest.StartTime == "" && appRequest.EndTime != "" {
server.respond(models.MissingParameter, "缺少开始时间")
return
}
if appRequest.StartTime != "" && appRequest.EndTime == "" {
server.respond(models.MissingParameter, "缺少结束时间")
return
}
tempLayout := layout
if appRequest.EndTime == "" && appRequest.StartTime == "" {
tempLayout = format
}
currentTime := time.Now()
if appRequest.EndTime == nil {
if appRequest.EndTime == "" {
endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, currentTime.Location())
appRequest.EndTime = &endTime
appRequest.EndTime = fmt.Sprintf(endTime.Format(format))
}
if appRequest.StartTime == nil {
if appRequest.StartTime == "" {
temp := fmt.Sprintf("-%dh", 24*7)
m, _ := time.ParseDuration(temp)
tempTime := currentTime.Add(m)
tempTime = time.Date(tempTime.Year(), tempTime.Month(), tempTime.Day(), 0, 0, 0, 0, tempTime.Location())
appRequest.StartTime = &tempTime
appRequest.StartTime = fmt.Sprintf(tempTime.Format(format))
}
if appRequest.EndTime.Before(*appRequest.StartTime) {
startTimeIn, _ := time.Parse(tempLayout, appRequest.StartTime)
endTimeIn, _ := time.Parse(tempLayout, appRequest.EndTime)
if endTimeIn.Before(startTimeIn) {
server.respond(models.BusinessFailed, "起始时间不能大于结束时间")
return
}
startTime := fmt.Sprintf(appRequest.StartTime.Format(format))
endTime := fmt.Sprintf(appRequest.EndTime.Format(format))
startTime := fmt.Sprintf(startTimeIn.Format(format))
endTime := fmt.Sprintf(endTimeIn.Format(format))
dates := utils.SplitDate(startTime, endTime, format)
sql := fmt.Sprintf("SELECT type, time,count(*) FROM tasks WHERE uid='%d' and time >= '%s' and time <= '%s' SAMPLE BY 1d ALIGN TO CALENDAR;", info.UserID, startTime, endTime)
counts, err := postgres.CountTasks(sql)
if err != nil {
......@@ -429,9 +586,32 @@ func (server *TaskController) UserTaskTypePerDay() {
}
responseTasks = append(responseTasks, reTask)
}
for _, value := range dates {
tempDate := findTime(responseTasks, value)
if tempDate != nil {
reTask := models.TaskCount{
Type: "0",
Time: *tempDate,
Count: "0",
ApiPath: "",
}
responseTasks = append(responseTasks, reTask)
}
}
server.respond(http.StatusOK, "", responseTasks)
}
func findTime(tasks []models.TaskCount, date string) *time.Time {
t, _ := time.Parse(format, date)
for _, value := range tasks {
if utils.InSameDay(t, value.Time) {
return nil
}
}
return &t
}
func (server *TaskController) UserTaskTypePercentage() {
info, err := server.Check()
if err != nil {
......@@ -446,26 +626,40 @@ func (server *TaskController) UserTaskTypePercentage() {
server.respond(models.NoRequestBody, err.Error())
return
}
if appRequest.StartTime == "" && appRequest.EndTime != "" {
server.respond(models.MissingParameter, "缺少开始时间")
return
}
if appRequest.StartTime != "" && appRequest.EndTime == "" {
server.respond(models.MissingParameter, "缺少结束时间")
return
}
tempLayout := layout
if appRequest.EndTime == "" && appRequest.StartTime == "" {
tempLayout = format
}
currentTime := time.Now()
if appRequest.EndTime == nil {
if appRequest.EndTime == "" {
endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, currentTime.Location())
appRequest.EndTime = &endTime
appRequest.EndTime = fmt.Sprintf(endTime.Format(format))
}
if appRequest.StartTime == nil {
if appRequest.StartTime == "" {
temp := fmt.Sprintf("-%dh", 24*7)
m, _ := time.ParseDuration(temp)
tempTime := currentTime.Add(m)
tempTime = time.Date(tempTime.Year(), tempTime.Month(), tempTime.Day(), 0, 0, 0, 0, tempTime.Location())
appRequest.StartTime = &tempTime
appRequest.StartTime = fmt.Sprintf(tempTime.Format(format))
}
startTimeIn, _ := time.Parse(tempLayout, appRequest.StartTime)
endTimeIn, _ := time.Parse(tempLayout, appRequest.EndTime)
if appRequest.EndTime.Before(*appRequest.StartTime) {
if endTimeIn.Before(startTimeIn) {
server.respond(models.BusinessFailed, "起始时间不能大于结束时间")
return
}
startTime := fmt.Sprintf(appRequest.StartTime.Format(format))
endTime := fmt.Sprintf(appRequest.EndTime.Format(format))
startTime := fmt.Sprintf(startTimeIn.Format(format))
endTime := fmt.Sprintf(endTimeIn.Format(format))
sql := fmt.Sprintf("SELECT type, count(type) FROM tasks WHERE uid='%d' and time >= '%s' and time <= '%s' GROUP BY type;", info.UserID, startTime, endTime)
counts, err := postgres.CountTasks(sql)
if err != nil {
......@@ -508,32 +702,60 @@ func (server *TaskController) UserFeePerDay() {
server.respond(models.NoRequestBody, err.Error())
return
}
if appRequest.StartTime == "" && appRequest.EndTime != "" {
server.respond(models.MissingParameter, "缺少开始时间")
return
}
if appRequest.StartTime != "" && appRequest.EndTime == "" {
server.respond(models.MissingParameter, "缺少结束时间")
return
}
tempLayout := layout
if appRequest.EndTime == "" && appRequest.StartTime == "" {
tempLayout = format
}
currentTime := time.Now()
if appRequest.EndTime == nil {
if appRequest.EndTime == "" {
endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, currentTime.Location())
appRequest.EndTime = &endTime
appRequest.EndTime = fmt.Sprintf(endTime.Format(format))
}
if appRequest.StartTime == nil {
if appRequest.StartTime == "" {
temp := fmt.Sprintf("-%dh", 24*7)
m, _ := time.ParseDuration(temp)
tempTime := currentTime.Add(m)
tempTime = time.Date(tempTime.Year(), tempTime.Month(), tempTime.Day(), 0, 0, 0, 0, tempTime.Location())
appRequest.StartTime = &tempTime
appRequest.StartTime = fmt.Sprintf(tempTime.Format(format))
}
startTimeIn, _ := time.Parse(tempLayout, appRequest.StartTime)
endTimeIn, _ := time.Parse(tempLayout, appRequest.EndTime)
if appRequest.EndTime.Before(*appRequest.StartTime) {
if endTimeIn.Before(startTimeIn) {
server.respond(models.BusinessFailed, "起始时间不能大于结束时间")
return
}
startTime := fmt.Sprintf(appRequest.StartTime.Format(format))
endTime := fmt.Sprintf(appRequest.EndTime.Format(format))
sql := fmt.Sprintf("SELECT time,sum(fee) FROM bills WHERE uid='%d' and time >= '%s' and time <= '%s' SAMPLE BY 1d ALIGN TO CALENDAR;", info.UserID, startTime, endTime)
startTime := fmt.Sprintf(startTimeIn.Format(format))
endTime := fmt.Sprintf(endTimeIn.Format(format))
dates := utils.SplitDate(startTime, endTime, format)
sql := fmt.Sprintf("SELECT time,sum(fee) AS fee FROM bills WHERE uid='%d' and time >= '%s' and time <= '%s' SAMPLE BY 1d ALIGN TO CALENDAR;", info.UserID, startTime, endTime)
counts, err := postgres.CountTasks(sql)
if err != nil {
server.respond(models.BusinessFailed, err.Error())
return
}
for _, value := range dates {
tempDate := findTime(counts, value)
if tempDate != nil {
reTask := models.TaskCount{
Type: "0",
Time: *tempDate,
Count: "0",
ApiPath: "",
}
counts = append(counts, reTask)
}
}
server.respond(http.StatusOK, "", counts)
}
......@@ -551,27 +773,43 @@ func (server *TaskController) UserTaskTypeFeePerDay() {
server.respond(models.NoRequestBody, err.Error())
return
}
if appRequest.StartTime == "" && appRequest.EndTime != "" {
server.respond(models.MissingParameter, "缺少开始时间")
return
}
if appRequest.StartTime != "" && appRequest.EndTime == "" {
server.respond(models.MissingParameter, "缺少结束时间")
return
}
tempLayout := layout
if appRequest.EndTime == "" && appRequest.StartTime == "" {
tempLayout = format
}
currentTime := time.Now()
if appRequest.EndTime == nil {
if appRequest.EndTime == "" {
endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, currentTime.Location())
appRequest.EndTime = &endTime
appRequest.EndTime = fmt.Sprintf(endTime.Format(format))
}
if appRequest.StartTime == nil {
if appRequest.StartTime == "" {
temp := fmt.Sprintf("-%dh", 24*7)
m, _ := time.ParseDuration(temp)
tempTime := currentTime.Add(m)
tempTime = time.Date(tempTime.Year(), tempTime.Month(), tempTime.Day(), 0, 0, 0, 0, tempTime.Location())
appRequest.StartTime = &tempTime
appRequest.StartTime = fmt.Sprintf(tempTime.Format(format))
}
startTimeIn, _ := time.Parse(tempLayout, appRequest.StartTime)
endTimeIn, _ := time.Parse(tempLayout, appRequest.EndTime)
if appRequest.EndTime.Before(*appRequest.StartTime) {
if endTimeIn.Before(startTimeIn) {
server.respond(models.BusinessFailed, "起始时间不能大于结束时间")
return
}
startTime := fmt.Sprintf(appRequest.StartTime.Format(format))
endTime := fmt.Sprintf(appRequest.EndTime.Format(format))
sql := fmt.Sprintf("SELECT type, time,sum(fee) FROM bills WHERE uid='%d' and time >= '%s' and time <= '%s' SAMPLE BY 1d ALIGN TO CALENDAR;", info.UserID, startTime, endTime)
startTime := fmt.Sprintf(startTimeIn.Format(format))
endTime := fmt.Sprintf(endTimeIn.Format(format))
dates := utils.SplitDate(startTime, endTime, format)
sql := fmt.Sprintf("SELECT type, time,sum(fee) AS fee FROM bills WHERE uid='%d' and time >= '%s' and time <= '%s' SAMPLE BY 1d ALIGN TO CALENDAR;", info.UserID, startTime, endTime)
counts, err := postgres.CountTasks(sql)
if err != nil {
server.respond(models.BusinessFailed, err.Error())
......@@ -591,11 +829,23 @@ func (server *TaskController) UserTaskTypeFeePerDay() {
reTask := models.TaskCount{
Type: task.Type,
Time: task.Time,
Count: task.Count,
Fee: task.Fee,
ApiPath: apiPath,
}
responseTasks = append(responseTasks, reTask)
}
for _, value := range dates {
tempDate := findTime(responseTasks, value)
if tempDate != nil {
reTask := models.TaskCount{
Type: "0",
Time: *tempDate,
Fee: "0",
ApiPath: "",
}
responseTasks = append(responseTasks, reTask)
}
}
server.respond(http.StatusOK, "", responseTasks)
}
......@@ -613,27 +863,41 @@ func (server *TaskController) UserTaskTypeFeePercentage() {
server.respond(models.NoRequestBody, err.Error())
return
}
if appRequest.StartTime == "" && appRequest.EndTime != "" {
server.respond(models.MissingParameter, "缺少开始时间")
return
}
if appRequest.StartTime != "" && appRequest.EndTime == "" {
server.respond(models.MissingParameter, "缺少结束时间")
return
}
tempLayout := layout
if appRequest.EndTime == "" && appRequest.StartTime == "" {
tempLayout = format
}
currentTime := time.Now()
if appRequest.EndTime == nil {
if appRequest.EndTime == "" {
endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, currentTime.Location())
appRequest.EndTime = &endTime
appRequest.EndTime = fmt.Sprintf(endTime.Format(format))
}
if appRequest.StartTime == nil {
if appRequest.StartTime == "" {
temp := fmt.Sprintf("-%dh", 24*7)
m, _ := time.ParseDuration(temp)
tempTime := currentTime.Add(m)
tempTime = time.Date(tempTime.Year(), tempTime.Month(), tempTime.Day(), 0, 0, 0, 0, tempTime.Location())
appRequest.StartTime = &tempTime
appRequest.StartTime = fmt.Sprintf(tempTime.Format(format))
}
startTimeIn, _ := time.Parse(tempLayout, appRequest.StartTime)
endTimeIn, _ := time.Parse(tempLayout, appRequest.EndTime)
if appRequest.EndTime.Before(*appRequest.StartTime) {
if endTimeIn.Before(startTimeIn) {
server.respond(models.BusinessFailed, "起始时间不能大于结束时间")
return
}
startTime := fmt.Sprintf(appRequest.StartTime.Format(format))
endTime := fmt.Sprintf(appRequest.EndTime.Format(format))
sql := fmt.Sprintf("SELECT type, sum(fee) FROM bills WHERE uid='%d' and time >= '%s' and time <= '%s' GROUP BY type;", info.UserID, startTime, endTime)
startTime := fmt.Sprintf(startTimeIn.Format(format))
endTime := fmt.Sprintf(endTimeIn.Format(format))
sql := fmt.Sprintf("SELECT type, sum(fee) AS fee FROM bills WHERE uid='%d' and time >= '%s' and time <= '%s' GROUP BY type;", info.UserID, startTime, endTime)
counts, err := postgres.CountTasks(sql)
if err != nil {
server.respond(models.BusinessFailed, err.Error())
......@@ -662,24 +926,44 @@ func (server *TaskController) UserTaskTypeFeePercentage() {
}
func (server *TaskController) AddTasktype() {
//_, err := server.Check()
//if err != nil {
// server.respond(http.StatusUnauthorized, err.Error())
// return
//}
_, err := server.Check()
if err != nil {
server.respond(http.StatusUnauthorized, err.Error())
return
}
body := server.Ctx.Input.RequestBody
appRequest := models.AddTaskType{}
err := json.Unmarshal(body, &appRequest) //解析body中数据
logs.Debug("appRequest", appRequest)
err = json.Unmarshal(body, &appRequest) //解析body中数据
logs.Debug("appRequest", appRequest, string(body))
if err != nil {
server.respond(models.NoRequestBody, err.Error())
return
}
if &appRequest.Type == nil {
if &appRequest.TaskTypeIn == nil {
server.respond(models.MissingParameter, "type 不能为空")
return
}
if &appRequest.TaskTypeIn.Name == nil {
server.respond(models.MissingParameter, "模型名称 不能为空")
return
}
if &appRequest.TaskTypeIn.Type == nil {
server.respond(models.MissingParameter, "模型类型 不能为空")
return
}
//if &appRequest.Type.Version == nil {
// server.respond(models.MissingParameter, "版本 不能为空")
// return
//}
if &appRequest.TaskTypeIn.BaseModel == nil {
server.respond(models.MissingParameter, "基础模型 不能为空")
return
}
//if &appRequest.Type.Version == nil {
// server.respond(models.MissingParameter, "基础模型 不能为空")
// return
//}
if &appRequest.Levels == nil {
server.respond(models.MissingParameter, "levels 不能为空")
......@@ -701,23 +985,37 @@ func (server *TaskController) AddTasktype() {
timestamp := time.Now()
hardwareRequire, err := json.Marshal(appRequest.Type.HardwareRequire)
cmd, err := json.Marshal(appRequest.Type.Cmd)
hardwareRequire, err := json.Marshal(appRequest.TaskTypeIn.HardwareRequire)
cmd, err := json.Marshal(appRequest.TaskTypeIn.Cmd)
//examples, err := json.Marshal(appRequest.Type.Examples)
apiPath := fmt.Sprintf("/%s/%s/%s", appRequest.TaskTypeIn.Type.String(), appRequest.TaskTypeIn.Name, appRequest.TaskTypeIn.BaseModel)
//if appRequest.Type.BaseModel != "" {
// apiPath = fmt.Sprintf("/%s/%s", apiPath, appRequest.Type.BaseModel)
//}
//if appRequest.Type.Version != "" {
// apiPath = fmt.Sprintf("/%s/%s", apiPath, appRequest.Type.Version)
//}
price := int64(appRequest.TaskTypeIn.Price * 1000000)
dbType := models.TaskType{
Desc: appRequest.Type.Desc,
Price: appRequest.Type.Price,
PublicKey: appRequest.Type.PublicKey,
Complexity: appRequest.Type.Complexity,
Name: appRequest.TaskTypeIn.Name,
BaseModel: appRequest.TaskTypeIn.BaseModel,
Version: appRequest.TaskTypeIn.Version,
Desc: appRequest.TaskTypeIn.Desc,
Price: price,
PublicKey: appRequest.TaskTypeIn.PublicKey,
Complexity: appRequest.TaskTypeIn.Complexity,
Type: int(appRequest.TaskTypeIn.Type),
Kind: appRequest.TaskTypeIn.Kind,
HardwareRequire: string(hardwareRequire),
ImageId: appRequest.Type.ImageId,
ImageUrl: appRequest.Type.ImageUrl,
ImageId: appRequest.TaskTypeIn.ImageId,
ImageUrl: appRequest.TaskTypeIn.ImageUrl,
Cmd: string(cmd),
Workload: appRequest.Type.Workload,
ApiPath: appRequest.Type.ApiPath,
ImageName: appRequest.Type.ImageName,
SignUrl: appRequest.Type.SignUrl,
Username: appRequest.Type.Username,
Password: appRequest.Type.Password,
Workload: appRequest.TaskTypeIn.Workload,
ApiPath: apiPath,
ImageName: appRequest.TaskTypeIn.ImageName,
SignUrl: appRequest.TaskTypeIn.SignUrl,
Username: appRequest.TaskTypeIn.Username,
Password: appRequest.TaskTypeIn.Password,
CreatedTime: timestamp,
UpdatedTime: timestamp,
}
......@@ -728,6 +1026,34 @@ func (server *TaskController) AddTasktype() {
server.respond(models.BusinessFailed, "填加 task type 失败")
return
}
dataString, err := redis.GetDataToString(cronjob.HeatKey)
var response []models.TaskHeat
if err != nil {
logs.Debug("GetDataToString err")
}
err = json.Unmarshal([]byte(dataString), &response)
if err != nil {
logs.Debug("GetDataToString Unmarshal err")
}
retask := models.TaskHeat{
TaskId: int(id),
User: dbType.Username,
Pwd: dbType.Password,
Repository: dbType.ImageUrl,
SignUrl: dbType.SignUrl,
ImageName: dbType.ImageName,
ImageId: dbType.ImageId,
HardwareRequire: appRequest.TaskTypeIn.HardwareRequire,
Count: int64(0),
Kind: dbType.Kind,
}
response = append(response, retask)
data, err := json.Marshal(response)
if err == nil {
redis.SetKeyAndData(cronjob.HeatKey, string(data), 0)
}
//todo:插入model表,并且关联task_type_id
var levels []models.UserLevelTaskType
for _, value := range appRequest.Levels {
......@@ -753,6 +1079,153 @@ func (server *TaskController) AddTasktype() {
func (server *TaskController) UpdateTaskType() {
//todo:需要调用学前的setTaskType,然后再调用PublichTaskUpdate
_, err := server.Check()
if err != nil {
server.respond(http.StatusUnauthorized, err.Error())
return
}
body := server.Ctx.Input.RequestBody
appRequest := models.AddTaskType{}
err = json.Unmarshal(body, &appRequest) //解析body中数据
logs.Debug("appRequest", appRequest)
if err != nil {
server.respond(models.NoRequestBody, err.Error())
return
}
if &appRequest.TaskTypeIn == nil {
server.respond(models.MissingParameter, "缺少 type 字段")
return
}
if &appRequest.TaskTypeIn.Id == nil {
server.respond(models.MissingParameter, "type id 不能为空")
return
}
if &appRequest.TaskTypeIn.Name == nil {
server.respond(models.MissingParameter, "模型名称 不能为空")
return
}
if &appRequest.TaskTypeIn.Type == nil {
server.respond(models.MissingParameter, "模型类型 不能为空")
return
}
if &appRequest.TaskTypeIn.BaseModel == nil {
server.respond(models.MissingParameter, "模型名称 不能为空")
return
}
if len(appRequest.Levels) > 0 {
flag := false
for _, value := range appRequest.Levels {
if value.Id == 0 {
flag = true
break
}
}
if flag {
server.respond(models.MissingParameter, "levels 中 有 id为空项")
return
}
}
//ormer := orm.NewOrm()
ormer := mysql.GetMysqlInstace().Ormer
//err = ormer.Begin()
//if err != nil {
// server.respond(models.BusinessFailed, "填加 task type 失败")
// return
//}
timestamp := time.Now()
hardwareRequire, err := json.Marshal(appRequest.TaskTypeIn.HardwareRequire)
cmd, err := json.Marshal(appRequest.TaskTypeIn.Cmd)
apiPath := fmt.Sprintf("/%s/%s/%s", appRequest.TaskTypeIn.Type.String(), appRequest.TaskTypeIn.Name, appRequest.TaskTypeIn.BaseModel)
//apiPath := fmt.Sprintf("/%s/%s", appRequest.Type.Type.String(), appRequest.Type.Name)
//if appRequest.Type.BaseModel != "" {
// apiPath = fmt.Sprintf("/%s/%s", apiPath, appRequest.Type.BaseModel)
//}
//if appRequest.Type.Version != "" {
// apiPath = fmt.Sprintf("/%s/%s", apiPath, appRequest.Type.Version)
//}
price := int64(appRequest.TaskTypeIn.Price * 1000000)
dbType := models.TaskType{
Id: appRequest.TaskTypeIn.Id,
Name: appRequest.TaskTypeIn.Name,
BaseModel: appRequest.TaskTypeIn.BaseModel,
Version: appRequest.TaskTypeIn.Version,
Desc: appRequest.TaskTypeIn.Desc,
Price: price,
PublicKey: appRequest.TaskTypeIn.PublicKey,
Complexity: appRequest.TaskTypeIn.Complexity,
HardwareRequire: string(hardwareRequire),
ImageId: appRequest.TaskTypeIn.ImageId,
ImageUrl: appRequest.TaskTypeIn.ImageUrl,
Type: int(appRequest.TaskTypeIn.Type),
Kind: appRequest.TaskTypeIn.Kind,
Cmd: string(cmd),
Workload: appRequest.TaskTypeIn.Workload,
ApiPath: apiPath,
ImageName: appRequest.TaskTypeIn.ImageName,
SignUrl: appRequest.TaskTypeIn.SignUrl,
Username: appRequest.TaskTypeIn.Username,
Password: appRequest.TaskTypeIn.Password,
CreatedTime: timestamp,
UpdatedTime: timestamp,
}
_, err = ormer.Update(&dbType)
if err != nil {
//ormer.Rollback()
server.respond(models.BusinessFailed, "填加 task type 失败")
return
}
dataString, err := redis.GetDataToString(cronjob.HeatKey)
var response []models.TaskHeat
if err != nil {
logs.Debug("GetDataToString err")
}
err = json.Unmarshal([]byte(dataString), &response)
if err != nil {
logs.Debug("GetDataToString Unmarshal err")
}
for _, task := range response {
if task.TaskId == dbType.Id {
task.User = dbType.Username
task.Pwd = dbType.Password
task.Repository = dbType.ImageUrl
task.SignUrl = dbType.SignUrl
task.ImageName = dbType.ImageName
task.ImageId = dbType.ImageId
task.HardwareRequire = appRequest.TaskTypeIn.HardwareRequire
task.Kind = dbType.Kind
}
}
data, err := json.Marshal(response)
if err == nil {
redis.SetKeyAndData(cronjob.HeatKey, string(data), 0)
}
//todo:插入model表,并且关联task_type_id
//var levels []models.UserLevelTaskType
for _, value := range appRequest.Levels {
value.UpdatedTime = timestamp
_, err = ormer.Update(&value)
//if err != nil {
// //ormer.Rollback()
// //server.respond(models.BusinessFailed, "填加 task type 失败")
// return
//}
}
//err = ormer.Commit()
//if err != nil {
// server.respond(models.BusinessFailed, "填加 task type 失败")
// return
//}
odysseus.PublichTaskUpdate(dbType.ApiPath)
server.respond(http.StatusOK, "修改 task type 成功")
}
func (server *TaskController) GetTaskTypes() {
......@@ -761,18 +1234,303 @@ func (server *TaskController) GetTaskTypes() {
server.respond(http.StatusUnauthorized, err.Error())
return
}
qs := mysql.GetMysqlInstace().Ormer.QueryTable("task_type")
count, err := qs.Count()
logs.Debug("Levels = ", count)
body := server.Ctx.Input.RequestBody
appRequest := models.AppRequest{}
err = json.Unmarshal(body, &appRequest) //解析body中数据
logs.Debug("appRequest", appRequest, string(body))
if err != nil {
server.respond(models.NoRequestBody, err.Error())
return
}
if appRequest.Page == 0 {
appRequest.Page = 1
}
if appRequest.Size == 0 {
appRequest.Size = 10
}
offset := (appRequest.Page - 1) * appRequest.Size
var types []*models.TaskType
sql := fmt.Sprintf("SELECT * FROM task_type WHERE deleted = 0 LIMIT %d,%d;", offset, appRequest.Size)
mysql.GetMysqlInstace().Ormer.Raw(sql).QueryRows(&types)
var remodels []*models.NewTaskType
for _, data := range types {
var hardwareRequire interface{}
eer := json.Unmarshal([]byte(data.HardwareRequire), &hardwareRequire)
if eer != nil {
}
var cmd interface{}
eer = json.Unmarshal([]byte(data.Cmd), &cmd)
if eer != nil {
}
remodel := models.NewTaskType{
Id: data.Id,
Name: data.Name,
BaseModel: data.BaseModel,
Version: data.Version,
Desc: data.Desc,
Price: float64(data.Price / 1000000),
PublicKey: data.PublicKey,
Complexity: data.Complexity,
Type: models.ModelType(data.Type),
TypeDesc: models.ModelType(data.Type).String(),
Kind: data.Kind,
KindDesc: models.TaskKind(data.Kind).String(),
HardwareRequire: hardwareRequire,
ImageId: data.ImageId,
ImageUrl: data.ImageUrl,
Cmd: cmd,
Workload: data.Workload,
ApiPath: data.ApiPath,
ImageName: data.ImageName,
SignUrl: data.SignUrl,
Username: data.Username,
Password: data.Password,
}
remodels = append(remodels, &remodel)
}
server.respond(http.StatusOK, "", remodels)
//qb, _ := orm.NewQueryBuilder("mysql")
//
//// 构建查询对象
//qb.Select("name", "type", "").
// From("user").
// InnerJoin("profile").On("user.id_user = profile.fk_user").
// Where("age > ?").
// OrderBy("name").Desc().
// Limit(10).Offset(0)
//
//// 导出 SQL 语句
////sql := qb.String()
//sql := "SELECT `name` AS tit,type,`desc` AS content, tags ,examples,codes,base_model,api_path,version FROM task_type WHERE deleted = 0;"
//
//// 执行 SQL 语句
//o := orm.NewOrm()
//o.Raw(sql, 20).QueryRows(&types)
//qs := mysql.GetMysqlInstace().Ormer.QueryTable("task_type")
//mysql.GetMysqlInstace().Ormer.LoadRelated(types, "UserLevelTaskType")
//count, err := qs.Count()
//logs.Debug("types = ", count)
//var types []*models.TaskType
//if count > 0 {
// qs.All(&types)
// //mysql.GetMysqlInstace().Ormer.LoadRelated(types, "UserLevelTaskType")
// //for _, dbType := range types {
// // var levels []*models.UserLevelTaskType
// // qs := mysql.GetMysqlInstace().Ormer.QueryTable(" user_level_task_type ")
// //}
//}
//server.respond(http.StatusOK, "", types)
}
func (server *TaskController) AddOrUpdateExamples() {
_, err := server.Check()
if err != nil {
server.respond(http.StatusUnauthorized, err.Error())
return
}
body := server.Ctx.Input.RequestBody
appRequest := models.NewTaskType{}
err = json.Unmarshal(body, &appRequest) //解析body中数据
logs.Debug("appRequest", appRequest)
if err != nil {
server.respond(models.NoRequestBody, err.Error())
return
}
if appRequest.Id == 0 {
server.respond(models.MissingParameter, "type id 不能为空")
return
}
checkType := &models.TaskType{Id: appRequest.Id}
err = mysql.GetMysqlInstace().Ormer.Read(checkType)
if err != nil {
server.respond(models.BusinessFailed, err.Error())
return
}
if appRequest.Examples != nil {
examples, _ := json.Marshal(appRequest.Examples)
checkType.Examples = string(examples)
}
if appRequest.Codes != nil {
codes, _ := json.Marshal(appRequest.Codes)
checkType.Codes = string(codes)
}
if appRequest.Tags != nil {
tags, _ := json.Marshal(appRequest.Tags)
checkType.Tags = string(tags)
}
checkType.ApiDocUrl = appRequest.ApiDocUrl
checkType.ApiDocContent = appRequest.ApiDocContent
_, err = mysql.GetMysqlInstace().Ormer.Update(checkType)
if err != nil {
server.respond(models.BusinessFailed, err.Error())
return
}
server.respond(http.StatusOK, "示例修改成功")
}
func (server *TaskController) Examples() {
body := server.Ctx.Input.RequestBody
appRequest := models.AppRequest{}
//if len(body) <= 0 {
// appRequest.Page == 1
//}
_ = json.Unmarshal(body, &appRequest) //解析body中数据
logs.Debug("appRequest", appRequest, string(body))
//if err != nil {
// server.respond(models.NoRequestBody, err.Error())
// return
//}
if appRequest.Page == 0 {
appRequest.Page = 1
}
if appRequest.Size == 0 {
appRequest.Size = 10
}
offset := (appRequest.Page - 1) * appRequest.Size
where := ""
if appRequest.Id != 0 {
where = fmt.Sprintf("and id = %d", appRequest.Id)
}
var types []*models.Model
sql := fmt.Sprintf("SELECT id, `name` AS tit,type,`desc` AS content, tags ,examples,codes,base_model,api_path,version FROM task_type WHERE deleted = 0 %s LIMIT %d,%d;", where, offset, appRequest.Size)
mysql.GetMysqlInstace().Ormer.Raw(sql).QueryRows(&types)
var remodels []*models.ResonseModel
for _, data := range types {
var examples []models.ExampleType
eer := json.Unmarshal([]byte(data.Examples), &examples)
if eer != nil {
}
var codes interface{}
eer = json.Unmarshal([]byte(data.Codes), &codes)
if eer != nil {
}
var tags interface{}
eer = json.Unmarshal([]byte(data.Tags), &tags)
if eer != nil {
}
remodel := models.ResonseModel{
Id: data.Id,
Tit: data.Tit,
Version: data.Version,
Content: data.Content,
Type: data.Type,
ApiPath: data.ApiPath,
BaseModel: data.BaseModel,
Examples: examples,
ApiDocUrl: data.ApiDocUrl,
ApiDocContent: data.ApiDocContent,
Codes: codes,
Tags: tags,
}
remodels = append(remodels, &remodel)
}
server.respond(http.StatusOK, "", remodels)
}
func (server *TaskController) GetLevelsByTypeId() {
_, err := server.Check()
if err != nil {
server.respond(http.StatusUnauthorized, err.Error())
return
}
body := server.Ctx.Input.RequestBody
appRequest := models.AppRequest{}
err = json.Unmarshal(body, &appRequest) //解析body中数据
logs.Debug("appRequest", appRequest)
if err != nil {
server.respond(models.NoRequestBody, err.Error())
return
}
if appRequest.Id == 0 {
server.respond(models.MissingParameter, "id不能为空")
return
}
var types []*models.UserLevelTaskType
qs := mysql.GetMysqlInstace().Ormer.QueryTable("user_level_task_type").Filter("task_type_id", appRequest.Id)
//mysql.GetMysqlInstace().Ormer.LoadRelated(types, "UserLevelTaskType")
count, err := qs.Count()
logs.Debug("types = ", count)
//var types []*models.TaskType
if count > 0 {
qs.All(&types)
//mysql.GetMysqlInstace().Ormer.LoadRelated(types, "UserLevelTaskType")
//for _, dbType := range types {
// var levels []*models.UserLevelTaskType
// qs := mysql.GetMysqlInstace().Ormer.QueryTable(" user_level_task_type ")
//}
}
server.respond(http.StatusOK, "", types)
}
func initTypeInRedis() []models.TaskHeat {
qs := mysql.GetMysqlInstace().Ormer.QueryTable("task_type")
count, _ := qs.Count()
logs.Debug("types = ", count)
var types []*models.TaskType
if count > 0 {
qs.All(&types)
}
var response []models.TaskHeat
for _, dbType := range types {
var hardwareRequire interface{}
eer := json.Unmarshal([]byte(dbType.HardwareRequire), &hardwareRequire)
if eer != nil {
}
retask := models.TaskHeat{
TaskId: dbType.Id,
User: dbType.Username,
Pwd: dbType.Password,
Repository: dbType.ImageUrl,
SignUrl: dbType.SignUrl,
ImageName: dbType.ImageName,
ImageId: dbType.ImageId,
HardwareRequire: hardwareRequire,
Count: int64(0),
Kind: dbType.Kind,
}
response = append(response, retask)
}
dataRedis, err := json.Marshal(response)
if err == nil {
redis.SetKeyAndData(cronjob.HeatKey, string(dataRedis), 0)
}
return response
}
func (server *TaskController) TaskHeat() {
data, err := redis.GetDataToString("task:heat")
data, err := redis.GetDataToString(cronjob.HeatKey)
if data == "" {
response := initTypeInRedis()
server.respond(http.StatusOK, "", response)
return
}
var response []models.TaskHeat
if err != nil {
server.respond(http.StatusOK, "", response)
......
......@@ -19,7 +19,7 @@ func (server *UserLevelController) Levels() {
server.respond(http.StatusUnauthorized, err.Error())
return
}
qs := mysql.GetMysqlInstace().Ormer.QueryTable("user_level")
qs := mysql.GetMysqlInstace().Ormer.QueryTable("user_level").Filter("deleted", 0)
count, err := qs.Count()
logs.Debug("Levels = ", count)
var levels []*models.UserLevel
......@@ -101,6 +101,8 @@ func (server *UserLevelController) UpdateLevel() {
return
}
request.CreatedTime = checkLevel.CreatedTime
request.UpdatedTime = time.Now()
_, err = mysql.GetMysqlInstace().Ormer.Update(&request)
if err != nil {
server.respond(models.BusinessFailed, "更新失败")
......@@ -135,7 +137,8 @@ func (server *UserLevelController) DelLevel() {
server.respond(models.MissingParameter, "默认等级不能删除")
return
}
request.Deleted = 1
mysql.GetMysqlInstace().Ormer.Delete(&request)
mysql.GetMysqlInstace().Ormer.Update(&request)
server.respond(http.StatusOK, "删除成功")
}
{"/Users/brent/Documents/wubanWork/ai_developer_admin/controllers":1708598583449330754}
\ No newline at end of file
package cronjob
import (
"ai_developer_admin/libs/odysseus"
"ai_developer_admin/libs/postgres"
"ai_developer_admin/libs/redis"
"ai_developer_admin/models"
......@@ -13,10 +12,14 @@ import (
var loopCronTask = cron.New(cron.WithSeconds())
var HeatKey = "task:heat"
func Start() {
//defer loopCronTask.Stop()
spec := "0 0 * * * ?" //"@every 1h"
//spec := "0 0 * * * ?" //"@every 1h"
spec := "@every 1h" //"@every 1h"
//spec := "*/1 * * * * ?" //"@every 1h"
loopCronTask.AddFunc(spec, func() {
logs.Debug("loopCronTask")
sql := "SELECT type,count(type) FROM bills GROUP BY type ORDER BY count DESC;"
......@@ -24,39 +27,107 @@ func Start() {
if err != nil {
return
}
dataString, err := redis.GetDataToString(HeatKey)
var response []models.TaskHeat
if err != nil {
return
}
err = json.Unmarshal([]byte(dataString), &response)
if err != nil {
return
}
for _, value := range tasks {
taskId, err := strconv.Atoi(value.Type)
if err != nil {
continue
}
taskType, err1 := odysseus.GetTaskType(int64(taskId))
if err1 != nil {
continue
}
var hardwareRequire models.Hardware
eer := json.Unmarshal([]byte(taskType.HardwareRequire), &hardwareRequire)
if eer != nil {
}
count, _ := strconv.Atoi(value.Count)
retask := models.TaskHeat{
TaskId: taskId,
User: taskType.Username,
Pwd: taskType.Password,
Repository: taskType.ImageUrl,
SignUrl: taskType.SignUrl,
ImageName: taskType.ImageName,
ImageId: taskType.ImageId,
HardwareRequire: hardwareRequire,
Count: int64(count),
for _, taskType := range response {
if taskType.TaskId == taskId {
taskType.Count = int64(count)
}
}
response = append(response, retask)
}
//for _, value := range tasks {
// taskId, err := strconv.Atoi(value.Type)
// if err != nil {
// continue
// }
// taskType, err1 := odysseus.GetTaskType(int64(taskId))
// if err1 != nil {
// continue
// }
// var hardwareRequire models.Hardware
// eer := json.Unmarshal([]byte(taskType.HardwareRequire), &hardwareRequire)
// if eer != nil {
//
// }
// count, _ := strconv.Atoi(value.Count)
// retask := models.TaskHeat{
// TaskId: taskId,
// User: taskType.Username,
// Pwd: taskType.Password,
// Repository: taskType.ImageUrl,
// SignUrl: taskType.SignUrl,
// ImageName: taskType.ImageName,
// ImageId: taskType.ImageId,
// HardwareRequire: hardwareRequire,
// Count: int64(count),
// }
// response = append(response, retask)
//}
data, err := json.Marshal(response)
if err == nil {
redis.SetKeyAndData("task:heat", string(data), 0)
redis.SetKeyAndData(HeatKey, string(data), 0)
}
})
loopCronTask.Start()
}
//func Start() {
// //defer loopCronTask.Stop()
//
// spec := "*/1 * * * * ?" //"@every 1h"
// loopCronTask.AddFunc(spec, func() {
// logs.Debug("loopCronTask")
// //sql := "SELECT type,count(type) FROM bills GROUP BY type ORDER BY count DESC;"
// //tasks, err := postgres.CountTasks(sql)
// //if err != nil {
// // return
// //}
// var response []models.TaskHeat
// //for _, value := range tasks {
// // taskId, err := strconv.Atoi(value.Type)
// // if err != nil {
// // continue
// // }
// taskType, err1 := odysseus.GetTaskType(int64(12))
// if err1 != nil {
// //continue
// }
// var hardwareRequire models.Hardware
// eer := json.Unmarshal([]byte(taskType.HardwareRequire), &hardwareRequire)
// if eer != nil {
//
// }
// //count, _ := strconv.Atoi(value.Count)
// retask := models.TaskHeat{
// TaskId: 12,
// User: taskType.Username,
// Pwd: taskType.Password,
// Repository: taskType.ImageUrl,
// SignUrl: taskType.SignUrl,
// ImageName: taskType.ImageName,
// ImageId: taskType.ImageId,
// HardwareRequire: hardwareRequire,
// Count: int64(0),
// }
// response = append(response, retask)
// //}
// data, err := json.Marshal(response)
// if err == nil {
// redis.SetKeyAndData("task:heat", string(data), 0)
// }
// })
// loopCronTask.Start()
//}
......@@ -28,6 +28,7 @@ func GetMysqlInstace() *Singleton {
func init() {
logs.Debug("mysql lib init")
//return
orm.Debug = true
if err := orm.RegisterDriver("mysql", orm.DRMySQL); err != nil {
logs.Error(err.Error())
......
......@@ -15,6 +15,7 @@ import (
var syncinfo *cachedata.CacheData
func init() {
//return
host, _ := beego.AppConfig.String("balancehost")
db, _ := beego.AppConfig.Int("balancedb")
pass, _ := beego.AppConfig.String("balancepass")
......@@ -60,3 +61,7 @@ func GetUserBalance(id int64) (int64, error) {
func GetTaskType(id int64) (*model.TaskType, error) {
return syncinfo.GetTaskWithId(id)
}
func PublichTaskUpdate(path string) error {
return syncinfo.PublichTaskUpdate(path)
}
......@@ -13,6 +13,7 @@ import (
var ormpost orm.Ormer
func init() {
//return
logs.Debug("postgres lib init")
orm.Debug = true
if err := orm.RegisterDriver("postgres", orm.DRPostgres); err != nil {
......@@ -55,6 +56,28 @@ func init() {
}
}
func QueryTset(sql string, args ...interface{}) ([]models.Bills, error) {
logs.Debug("QueryBills = ", sql)
qs := ormpost.Raw(sql, args)
var params []orm.Params
_, err := qs.Values(&params)
if err != nil {
return nil, err
}
arr, err := json.Marshal(params)
if err != nil {
return nil, err
}
var containers []models.Bills
logs.Debug("QueryBills = ", string(arr))
err = json.Unmarshal(arr, &containers)
if err != nil {
return nil, err
}
return containers, nil
}
func QueryBills(sql string) ([]models.Bills, error) {
logs.Debug("QueryBills = ", sql)
qs := ormpost.Raw(sql)
......
package redis
import (
"fmt"
"github.com/beego/beego/v2/core/logs"
beego "github.com/beego/beego/v2/server/web"
"github.com/google/uuid"
"gopkg.in/redis.v5"
"strconv"
"strings"
"time"
)
var redisCache *redis.Client
func init() {
//return
host, _ := beego.AppConfig.String("tokenhost")
db, _ := beego.AppConfig.Int("tokendb")
pass, _ := beego.AppConfig.String("tokenpass")
......@@ -31,6 +36,59 @@ func createClient(redisHost string, password string, dataBase int) *redis.Client
return client
}
func tryAcquire(rs *redis.Client, lockKey string, lockTimeout time.Duration) (acquired bool, release func(), _ error) {
timeout := time.Now().Add(lockTimeout).UnixNano()
lockToken := fmt.Sprintf("%d,%s", timeout, uuid.New().String())
release = func() {
// Best effort to check we're releasing the lock we think we have. Note that it
// is still technically possible the lock token has changed between the GET and
// DEL since these are two separate operations, i.e. when the current lock happen
// to be expired at this very moment.
get, _ := rs.Get(lockKey).Result()
if get == lockToken {
_ = rs.Del(lockKey)
}
}
set, err := rs.SetNX(lockKey, lockToken, lockTimeout).Result()
if err != nil {
return false, nil, err
} else if set {
return true, release, nil
}
// We didn't get the lock, but we can check if the lock is expired.
currentLockToken, err := rs.Get(lockKey).Result()
if err == redis.Nil {
// Someone else got the lock and released it already.
return false, nil, nil
} else if err != nil {
return false, nil, err
}
currentTimeout, _ := strconv.ParseInt(strings.SplitN(currentLockToken, ",", 2)[0], 10, 64)
if currentTimeout > time.Now().UnixNano() {
// The lock is still valid.
return false, nil, nil
}
// The lock has expired, try to acquire it.
get, err := rs.GetSet(lockKey, lockToken).Result()
if err != nil {
return false, nil, err
} else if get != currentLockToken {
// Someone else got the lock
return false, nil, nil
}
// We got the lock.
return true, release, nil
}
func SetHeat(key string, value interface{}, time time.Duration) {
}
func SetKeyAndData(key string, value interface{}, time time.Duration) error {
err := redisCache.Set(key, value, time).Err()
if err != nil {
......
package utils
import "time"
func InSameDay(t1, t2 time.Time) bool {
y1, m1, d1 := t1.Date()
y2, m2, d2 := t2.Date()
return y1 == y2 && m1 == m2 && d1 == d2
}
func SplitDate(beginDate, endDate, format string) []string {
bDate, _ := time.ParseInLocation(format, beginDate, time.Local)
eDate, _ := time.ParseInLocation(format, endDate, time.Local)
day := int(eDate.Sub(bDate).Hours() / 24)
dlist := make([]string, 0)
dlist = append(dlist, beginDate)
for i := 1; i < day; i++ {
result := bDate.AddDate(0, 0, i)
dlist = append(dlist, result.Format(format))
}
dlist = append(dlist, endDate)
return dlist
}
......@@ -4,9 +4,11 @@ import (
"ai_developer_admin/libs/cronjob"
"ai_developer_admin/libs/mysql"
_ "ai_developer_admin/routers"
"fmt"
beego "github.com/beego/beego/v2/server/web"
"github.com/beego/beego/v2/server/web/filter/cors"
_ "github.com/beego/beego/v2/server/web/session/redis"
"time"
)
func init() {
......@@ -34,6 +36,28 @@ func main() {
// logs.SetLogger(logs.AdapterFile, config)
//}
str := "2024-02-01T18:41:30"
layout := "2006-01-02T15:04:05"
t, _ := time.Parse(layout, str)
fmt.Print("t = %s", t)
//currentTime := time.Now()
////if appRequest.EndTime == nil {
//tempendTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, currentTime.Location())
//endTime := &tempendTime
////}
////if appRequest.StartTime == nil {
//temp := fmt.Sprintf("-%dh", 24*7)
//m, _ := time.ParseDuration(temp)
//tempTime := currentTime.Add(m)
//tempTime = time.Date(tempTime.Year(), tempTime.Month(), tempTime.Day(), 0, 0, 0, 0, tempTime.Location())
//startTime := &tempTime
////}
//startTimeStr := fmt.Sprintf(startTime.Format("2006-01-02T15:04:05.000000Z"))
//endTimeStr := fmt.Sprintf(endTime.Format("2006-01-02T15:04:05.000000Z"))
//
//dates := utils.SplitDate(startTimeStr, endTimeStr, "2006-01-02T15:04:05.000000Z")
//logs.Debug("dates = ", dates)
cronjob.Start()
mysql.GetMysqlInstace()
//postgres.Query("")
......
......@@ -39,12 +39,12 @@ type JwtToken struct {
}
type AppRequest struct {
Id int `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Page int64 `json:"page,omitempty"`
Size int64 `json:"size,omitempty"`
StartTime *time.Time `json:"start_time,omitempty"`
EndTime *time.Time `json:"end_time,omitempty"`
ProfitAcc string `json:"profit_acc,omitempty"`
WorkerAcc string `json:"worker_acc,omitempty"`
Id int `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Page int64 `json:"page,omitempty"`
Size int64 `json:"size,omitempty"`
StartTime string `json:"start_time,omitempty"`
EndTime string `json:"end_time,omitempty"`
ProfitAcc string `json:"profit_acc,omitempty"`
WorkerAcc string `json:"worker_acc,omitempty"`
}
......@@ -4,26 +4,42 @@ import (
"time"
)
type Hardware struct {
DiskSize int64 `json:"disk_size,omitempty"`
MemorySize int64 `json:"memory_size,omitempty"`
Gpus []string `json:"gpus,omitempty"`
}
//type Hardware struct {
// DiskSize int64 `json:"disk_size,omitempty"`
// MemorySize int64 `json:"memory_size,omitempty"`
// Gpus []string `json:"gpus,omitempty"`
//}
//
//type CMD struct {
// ImageName string `json:"image_name"`
// DockerCmd struct {
// ContainerPort string `json:"container_port"`
// } `json:"docker_cmd"`
// ApiUrl string `json:"api_url"`
//}
type CMD struct {
ImageName string `json:"image_name"`
DockerCmd struct {
ContainerPort string `json:"container_port"`
} `json:"docker_cmd"`
ApiUrl string `json:"api_url"`
type ExampleType struct {
Title string `json:"title"`
Input struct {
Prompt string `json:"prompt,omitempty"`
Image string `json:"image,omitempty"`
} `json:"input"`
Output struct {
Text string `json:"text,omitempty"`
Url string `json:"url,omitempty"`
} `json:"output"`
}
type TaskType struct {
Id int `orm:"column(id);auto"`
Name string `json:"name";orm:"column(name);size(20)"`
Version string `json:"version,omitempty";orm:"column(version)"`
Desc string `json:"desc";orm:"column(desc);size(20)"`
Price int64 `json:"price";orm:"column(price)"`
PublicKey string `json:"public_key";orm:"column(public_key)"`
Complexity int `json:"complexity";orm:"column(complexity)"`
Type int `json:"type";orm:"column(type)"`
Kind int `json:"kind";orm:"column(kind)"`
HardwareRequire string `json:"hardware_require";orm:"column(hardware_require)"`
ImageId string `json:"image_id";orm:"column(image_id)"`
ImageUrl string `json:"image_url";orm:"column(image_url)"`
......@@ -34,30 +50,78 @@ type TaskType struct {
SignUrl string `json:"sign_url";orm:"column(sign_url)"`
Username string `json:"username";orm:"column(username)"`
Password string `json:"password";orm:"column(password)"`
BaseModel string `json:"base_model";orm:"column(base_model)"`
Examples string `json:"examples";orm:"column(examples)"`
ApiDocUrl string `json:"api_doc_url";orm:"column(api_doc_url)"`
ApiDocContent string `json:"api_doc_content";orm:"column(api_doc_content)"`
Codes string `json:"codes";orm:"column(codes)"`
Tags string `json:"tags";orm:"column(tags)"`
CreatedTime time.Time `json:"created_time";orm:"column(created_time);type(datetime)"`
UpdatedTime time.Time `json:"updated_time";orm:"column(updated_time);type(datetime)"`
Deleted int `json:"deleted";orm:"column(deleted);size(1)"`
}
type NewTaskType struct {
Id int `orm:"column(id);auto"`
Desc string `json:"desc";orm:"column(desc);size(20)"`
Price int64 `json:"price";orm:"column(price)"`
PublicKey string `json:"public_key";orm:"column(public_key)"`
Complexity int `json:"complexity";orm:"column(complexity)"`
HardwareRequire Hardware `json:"hardware_require";orm:"column(hardware_require)"`
ImageId string `json:"image_id";orm:"column(image_id)"`
ImageUrl string `json:"image_url";orm:"column(image_url)"`
Cmd CMD `json:"cmd";orm:"column(cmd)"`
Workload int `json:"workload";orm:"column(workload)"`
ApiPath string `json:"api_path";orm:"column(api_path)"`
ImageName string `json:"image_name";orm:"column(image_name)"`
SignUrl string `json:"sign_url";orm:"column(sign_url)"`
Username string `json:"username";orm:"column(username)"`
Password string `json:"password";orm:"column(password)"`
CreatedTime time.Time `json:"created_time";orm:"column(created_time);type(datetime)"`
UpdatedTime time.Time `json:"updated_time";orm:"column(updated_time);type(datetime)"`
Deleted int `json:"deleted";orm:"column(deleted);size(1)"`
Id int `orm:"column(id);auto"`
Name string `json:"name";orm:"column(desc)"`
BaseModel string `json:"base_model";orm:"column(desc)"`
Version string `json:"version";orm:"column(desc)"`
Desc string `json:"desc";orm:"column(desc);size(20)"`
Price float64 `json:"price";orm:"column(price)"`
PublicKey string `json:"public_key";orm:"column(public_key)"`
Complexity int `json:"complexity";orm:"column(complexity)"`
Type ModelType `json:"type,omitempty";orm:"column(type)"`
Kind int `json:"kind";orm:"column(kind)"`
TypeDesc string `json:"type_desc"`
KindDesc string `json:"kind_desc"`
HardwareRequire interface{} `json:"hardware_require";orm:"column(hardware_require)"`
ImageId string `json:"image_id";orm:"column(image_id)"`
ImageUrl string `json:"image_url";orm:"column(image_url)"`
Cmd interface{} `json:"cmd";orm:"column(cmd)"`
Workload int `json:"workload";orm:"column(workload)"`
ApiPath string `json:"api_path";orm:"column(api_path)"`
ImageName string `json:"image_name";orm:"column(image_name)"`
SignUrl string `json:"sign_url";orm:"column(sign_url)"`
Username string `json:"username";orm:"column(username)"`
Password string `json:"password";orm:"column(password)"`
Examples []ExampleType `json:"examples,omitempty";orm:"column(examples)"`
ApiDocUrl string `json:"api_doc_url,omitempty";orm:"column(api_doc_url)"`
ApiDocContent string `json:"api_doc_content,omitempty";orm:"column(api_doc_content)"`
Codes interface{} `json:"codes,omitempty";orm:"column(codes)"`
Tags []string `json:"tags,omitempty";orm:"column(tags)"`
CreatedTime time.Time `json:"created_time";orm:"column(created_time);type(datetime)"`
UpdatedTime time.Time `json:"updated_time";orm:"column(updated_time);type(datetime)"`
Deleted int `json:"deleted";orm:"column(deleted);size(1)"`
}
type Model struct {
Id int `orm:"column(id);auto"`
Tit string `json:"tit";orm:"column(tit);size(20)"`
Version string `json:"version,omitempty";orm:"column(version)"`
Content string `json:"content";orm:"column(content);size(20)"`
Type int `json:"type";orm:"column(type)"`
ApiPath string `json:"api_path";orm:"column(api_path)"`
BaseModel string `json:"base_model";orm:"column(base_model)"`
Examples string `json:"examples";orm:"column(examples)"`
ApiDocUrl string `json:"api_doc_url";orm:"column(api_doc_url)"`
ApiDocContent string `json:"api_doc_content";orm:"column(api_doc_content)"`
Codes string `json:"codes";orm:"column(codes)"`
Tags string `json:"tags";orm:"column(tags)"`
}
type ResonseModel struct {
Id int `json:"id";orm:"column(id)"`
Tit string `json:"tit";orm:"column(tit);size(20)"`
Version string `json:"version,omitempty";orm:"column(version)"`
Content string `json:"content";orm:"column(content);size(20)"`
Type int `json:"type";orm:"column(type)"`
ApiPath string `json:"api_path";orm:"column(api_path)"`
BaseModel string `json:"base_model";orm:"column(base_model)"`
Examples interface{} `json:"examples";orm:"column(examples)"`
ApiDocUrl string `json:"api_doc_url,omitempty";orm:"column(api_doc_url)"`
ApiDocContent string `json:"api_doc_content,omitempty";orm:"column(api_doc_content)"`
Codes interface{} `json:"codes";orm:"column(codes)"`
Tags interface{} `json:"tags";orm:"column(tags)"`
}
type Bills struct {
......@@ -98,17 +162,18 @@ type TaskCount struct {
}
type TaskHeat struct {
Time time.Time `json:"time,omitempty"`
Count int64 `json:"count,omitempty"`
ApiPath string `json:"api_path,omitempty"`
HardwareRequire Hardware `json:"hardware_require,omitempty"`
ImageId string `json:"image_id,omitempty"`
Repository string `json:"repository,omitempty"`
ImageName string `json:"image_name,omitempty"`
SignUrl string `json:"sign_url,omitempty"`
User string `json:"user,omitempty"`
Pwd string `json:"pwd,omitempty"`
TaskId int `json:"task_id,omitempty"`
Time time.Time `json:"time,omitempty"`
Count int64 `json:"count,omitempty"`
ApiPath string `json:"api_path,omitempty"`
HardwareRequire interface{} `json:"hardware_require,omitempty"`
ImageId string `json:"image_id,omitempty"`
Repository string `json:"repository,omitempty"`
ImageName string `json:"image_name,omitempty"`
SignUrl string `json:"sign_url,omitempty"`
User string `json:"user,omitempty"`
Pwd string `json:"pwd,omitempty"`
TaskId int `json:"task_id,omitempty"`
Kind int `json:"kind";orm:"column(kind)"`
}
//type Tasks struct {
......@@ -123,6 +188,51 @@ type TaskHeat struct {
//}
type AddTaskType struct {
Type NewTaskType `json:"type"`
Levels []UserLevelTaskType `json:"levels"`
TaskTypeIn NewTaskType `json:"task_type"`
Levels []UserLevelTaskType `json:"levels"`
}
type ModelType int
const (
TXTTOIMG ModelType = iota + 1
TXTTOTXT
TXTTOVIDEO
)
func (m ModelType) String() string {
switch m {
case TXTTOIMG:
return "txt2img"
case TXTTOTXT:
return "txt2txt"
case TXTTOVIDEO:
return "txt2video"
default:
return "未知类型"
}
}
type TaskKind int
const (
SystemTask TaskKind = iota
ComputeTask = 1
CustomTask = 2
StandardTask = 3
)
func (m TaskKind) String() string {
switch m {
case SystemTask:
return "系统任务"
case ComputeTask:
return "计算任务"
case CustomTask:
return "自定义任务"
case StandardTask:
return "标准任务"
default:
return "未知类型"
}
}
......@@ -60,7 +60,7 @@ type UserLevel struct {
}
type UserLevelTaskType struct {
ID int `orm:"column(id);auto"`
Id int `orm:"column(id);auto"`
FreeCallCountDay int `json:"free_call_count_day"orm:"column(free_call_count_day)"`
FreeCallCountMonth int `json:"free_call_count_month"orm:"column(free_call_count_month)"`
FreeCallCountYear int `json:"free_call_count_year"orm:"column(free_call_count_year)"`
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment