From cdff8aeb0ca0b9ca53cfdc9a75983215c3f73500 Mon Sep 17 00:00:00 2001 From: zhangwei <894646498@qq.com> Date: Fri, 7 Mar 2025 16:10:56 +0800 Subject: [PATCH 1/7] =?UTF-8?q?=E5=88=9B=E5=BB=BA=E4=BB=BB=E5=8A=A1?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0user=5Fid?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/logic/adapters/createclusterlogic.go | 3 +++ internal/logic/cloud/commitgeneraltasklogic.go | 1 + internal/logic/hpc/commithpctasklogic.go | 1 + pkg/models/taskmodel_gen.go | 1 + 4 files changed, 6 insertions(+) diff --git a/internal/logic/adapters/createclusterlogic.go b/internal/logic/adapters/createclusterlogic.go index 4e14fc47..2832f933 100644 --- a/internal/logic/adapters/createclusterlogic.go +++ b/internal/logic/adapters/createclusterlogic.go @@ -13,6 +13,7 @@ import ( "k8s.io/apimachinery/pkg/util/json" "net/http" "net/url" + "strconv" "time" "github.com/zeromicro/go-zero/core/logx" @@ -65,7 +66,9 @@ func (l *CreateClusterLogic) CreateCluster(req *types.ClusterCreateReq) (resp *t return nil, errors.New("cluster create failed") } // 创建资源价格信息 + clusterId, _ := strconv.ParseInt(cluster.Id, 10, 64) resourcePrice := &types.ResourcePrice{ + ResourceID: clusterId, Price: req.Price, ResourceType: constants.CLUSTER, CostType: req.CostType, diff --git a/internal/logic/cloud/commitgeneraltasklogic.go b/internal/logic/cloud/commitgeneraltasklogic.go index 8b4f0453..345664a8 100644 --- a/internal/logic/cloud/commitgeneraltasklogic.go +++ b/internal/logic/cloud/commitgeneraltasklogic.go @@ -99,6 +99,7 @@ func (l *CommitGeneralTaskLogic) CommitGeneralTask(req *types.GeneralTaskReq) er AdapterTypeDict: "0", SynergyStatus: synergyStatus, Strategy: strategy, + UserId: req.UserId, } var taskClouds []cloud.TaskCloudModel adapterName := "" diff --git a/internal/logic/hpc/commithpctasklogic.go b/internal/logic/hpc/commithpctasklogic.go index e22e150d..62d04001 100644 --- a/internal/logic/hpc/commithpctasklogic.go +++ b/internal/logic/hpc/commithpctasklogic.go @@ -48,6 +48,7 @@ func (l *CommitHpcTaskLogic) CommitHpcTask(req *types.CommitHpcTaskReq) (resp *t CommitTime: time.Now(), Status: "Running", AdapterTypeDict: "2", + UserId: req.UserId, } // 保存任务数据到数据库 diff --git a/pkg/models/taskmodel_gen.go b/pkg/models/taskmodel_gen.go index e57c0f5d..f099c4dc 100644 --- a/pkg/models/taskmodel_gen.go +++ b/pkg/models/taskmodel_gen.go @@ -51,6 +51,7 @@ type ( NsID string `db:"ns_id" json:"nsID"` AdapterTypeDict string `db:"adapter_type_dict" json:"adapterTypeDict"` //任务类型(对应字典表的值) TaskTypeDict string `db:"task_type_dict" json:"taskTypeDict"` + UserId int64 `db:"user_id" json:"userId"` } ) From 1ec680a49ab20eab5e53e131683e7e9f3f7dc234 Mon Sep 17 00:00:00 2001 From: tzwang Date: Mon, 10 Mar 2025 16:08:25 +0800 Subject: [PATCH 2/7] update statusReport --- internal/scheduler/schedulers/aiScheduler.go | 16 +++++++------- .../scheduler/service/utils/jcs/middleware.go | 8 +++---- .../service/utils/status/taskStatusSync.go | 22 +++++++++++++++++++ 3 files changed, 33 insertions(+), 13 deletions(-) diff --git a/internal/scheduler/schedulers/aiScheduler.go b/internal/scheduler/schedulers/aiScheduler.go index 052be43f..8174f528 100644 --- a/internal/scheduler/schedulers/aiScheduler.go +++ b/internal/scheduler/schedulers/aiScheduler.go @@ -259,9 +259,9 @@ func (as *AiScheduler) handleErrors(errs []interface{}, clusters []*strategy.Ass //report msg report := &jcs.JobStatusReportReq{ - JobSetID: "", - LocalJobID: "", - Messages: make([]*jcs.ReportMessage, 0), + TaskName: "", + TaskID: strconv.FormatInt(taskId, 10), + Messages: make([]*jcs.ReportMessage, 0), } var errmsg string @@ -282,11 +282,10 @@ func (as *AiScheduler) handleErrors(errs []interface{}, clusters []*strategy.Ass //add report msg jobMsg := &jcs.ReportMessage{ - TaskName: as.option.TaskName, - TaskID: strconv.FormatInt(as.option.TaskId, 10), Status: false, Message: msg, ClusterID: e.clusterId, + Output: "", } report.Messages = append(report.Messages, jobMsg) } @@ -311,17 +310,18 @@ func (as *AiScheduler) handleErrors(errs []interface{}, clusters []*strategy.Ass } //add report msg jobMsg := &jcs.ReportMessage{ - TaskName: as.option.TaskName, - TaskID: strconv.FormatInt(as.option.TaskId, 10), Status: false, Message: s.Msg, ClusterID: s.ClusterId, + Output: "", } report.Messages = append(report.Messages, jobMsg) } //report status - _ = jcs.StatusReport(as.AiService.Conf.JcsMiddleware.Url, report) + if mode == executor.SUBMIT_MODE_STORAGE_SCHEDULE { + _ = jcs.StatusReport(as.AiService.Conf.JcsMiddleware.Url, report) + } logx.Errorf(errors.New(errmsg).Error()) return errors.New(errmsg) diff --git a/internal/scheduler/service/utils/jcs/middleware.go b/internal/scheduler/service/utils/jcs/middleware.go index 94331924..0ff5c374 100644 --- a/internal/scheduler/service/utils/jcs/middleware.go +++ b/internal/scheduler/service/utils/jcs/middleware.go @@ -5,13 +5,11 @@ import ( ) type JobStatusReportReq struct { - JobSetID string `json:"jobSetID"` - LocalJobID string `json:"localJobID"` - Messages []*ReportMessage `json:"messages"` + TaskName string `json:"taskName"` + TaskID string `json:"taskID"` + Messages []*ReportMessage `json:"messages"` } type ReportMessage struct { - TaskName string `json:"taskName"` - TaskID string `json:"taskID"` Status bool `json:"status"` Message string `json:"message"` ClusterID string `json:"clusterID"` diff --git a/internal/scheduler/service/utils/status/taskStatusSync.go b/internal/scheduler/service/utils/status/taskStatusSync.go index d33e82b4..e6c0f455 100644 --- a/internal/scheduler/service/utils/status/taskStatusSync.go +++ b/internal/scheduler/service/utils/status/taskStatusSync.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "github.com/zeromicro/go-zero/core/logx" + "gitlink.org.cn/JointCloud/pcm-coordinator/internal/scheduler/service/utils/jcs" "gitlink.org.cn/JointCloud/pcm-coordinator/internal/svc" "gitlink.org.cn/JointCloud/pcm-coordinator/internal/types" "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/constants" @@ -61,6 +62,7 @@ func UpdateTaskStatus(svc *svc.ServiceContext, tasklist []*types.TaskModel) { if len(aiTask) == 1 { if aiTask[0].Status == constants.Completed { task.Status = constants.Succeeded + _ = reportStatusMessages(svc, task, aiTask[0]) } else { task.Status = aiTask[0].Status } @@ -142,6 +144,26 @@ func UpdateTaskStatus(svc *svc.ServiceContext, tasklist []*types.TaskModel) { } } +func reportStatusMessages(svc *svc.ServiceContext, task *types.TaskModel, aiTask *models.TaskAi) error { + report := &jcs.JobStatusReportReq{ + TaskName: task.Name, + TaskID: strconv.FormatInt(task.Id, 10), + Messages: make([]*jcs.ReportMessage, 0), + } + //add report msg + jobMsg := &jcs.ReportMessage{ + Status: true, + Message: "", + ClusterID: strconv.FormatInt(aiTask.ClusterId, 10), + Output: aiTask.JobId, + } + report.Messages = append(report.Messages, jobMsg) + + _ = jcs.StatusReport(svc.Scheduler.AiService.Conf.JcsMiddleware.Url, report) + + return nil +} + func updateInferTaskStatus(svc *svc.ServiceContext, task types.TaskModel) { aiTask, err := svc.Scheduler.AiStorages.GetAiTaskListById(task.Id) if err != nil { From cc166fb74596a9e0f671758b9a9252a5af6141ad Mon Sep 17 00:00:00 2001 From: tzwang Date: Mon, 10 Mar 2025 16:21:08 +0800 Subject: [PATCH 3/7] update aiservice --- internal/scheduler/service/aiService.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/scheduler/service/aiService.go b/internal/scheduler/service/aiService.go index bdf3bc1e..9d6064f7 100644 --- a/internal/scheduler/service/aiService.go +++ b/internal/scheduler/service/aiService.go @@ -93,7 +93,7 @@ func InitAiClusterMap(conf *config.Config, clusters []types.ClusterInfo) (map[st inferenceMap[c.Id] = sgai case OPENI: id, _ := strconv.ParseInt(c.Id, 10, 64) - openi := storeLink.NewOpenI("http://localhost:2024", id, c.Username, c.Token) + openi := storeLink.NewOpenI(c.Server, id, c.Username, c.Token) collectorMap[c.Id] = openi executorMap[c.Id] = openi inferenceMap[c.Id] = openi From 84540521b6222ebed0bfc004ea50f58992084d06 Mon Sep 17 00:00:00 2001 From: zhangwei <894646498@qq.com> Date: Mon, 10 Mar 2025 18:48:31 +0800 Subject: [PATCH 4/7] =?UTF-8?q?=E6=95=B0=E6=8D=AE=E4=B8=8A=E9=93=BE?= =?UTF-8?q?=E6=8F=90=E4=BA=A4=E9=87=91=E9=A2=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/logic/cloud/commitgeneraltasklogic.go | 9 +++++++++ internal/logic/hpc/commithpctasklogic.go | 5 +++++ pkg/utils/remoteUtil/BlockChain.go | 1 + 3 files changed, 15 insertions(+) diff --git a/internal/logic/cloud/commitgeneraltasklogic.go b/internal/logic/cloud/commitgeneraltasklogic.go index 345664a8..da206698 100644 --- a/internal/logic/cloud/commitgeneraltasklogic.go +++ b/internal/logic/cloud/commitgeneraltasklogic.go @@ -145,6 +145,14 @@ func (l *CommitGeneralTaskLogic) CommitGeneralTask(req *types.GeneralTaskReq) er if err != nil { return err } + // 查询资源价格 + var price int64 + for _, clusterId := range req.ClusterIds { + var clusterPrice int64 + l.svcCtx.DbEngin.Raw("select price from resource_cost where resource_id = ?", clusterId).Scan(&clusterPrice) + price = price + clusterPrice + } + remoteUtil.Evidence(remoteUtil.EvidenceParam{ UserIp: req.UserIp, Url: l.svcCtx.Config.BlockChain.Url, @@ -152,6 +160,7 @@ func (l *CommitGeneralTaskLogic) CommitGeneralTask(req *types.GeneralTaskReq) er FunctionName: l.svcCtx.Config.BlockChain.FunctionName, Type: l.svcCtx.Config.BlockChain.Type, Token: req.Token, + Amount: price, Args: []string{strconv.FormatInt(taskModel.Id, 10), string(bytes)}, }) return nil diff --git a/internal/logic/hpc/commithpctasklogic.go b/internal/logic/hpc/commithpctasklogic.go index 62d04001..e8364c53 100644 --- a/internal/logic/hpc/commithpctasklogic.go +++ b/internal/logic/hpc/commithpctasklogic.go @@ -113,6 +113,10 @@ func (l *CommitHpcTaskLogic) CommitHpcTask(req *types.CommitHpcTaskReq) (resp *t JobId: string(""), } // 数据上链 + // 查询资源价格 + var price int64 + l.svcCtx.DbEngin.Raw("select price from resource_cost where resource_id = ?", clusterId).Scan(&price) + bytes, _ := json.Marshal(taskModel) remoteUtil.Evidence(remoteUtil.EvidenceParam{ UserIp: req.UserIp, @@ -121,6 +125,7 @@ func (l *CommitHpcTaskLogic) CommitHpcTask(req *types.CommitHpcTaskReq) (resp *t FunctionName: l.svcCtx.Config.BlockChain.FunctionName, Type: l.svcCtx.Config.BlockChain.Type, Token: req.Token, + Amount: price, Args: []string{strconv.FormatInt(taskModel.Id, 10), string(bytes)}, }) // 提交job到指定集群 diff --git a/pkg/utils/remoteUtil/BlockChain.go b/pkg/utils/remoteUtil/BlockChain.go index 18f7a3a6..ab02934e 100644 --- a/pkg/utils/remoteUtil/BlockChain.go +++ b/pkg/utils/remoteUtil/BlockChain.go @@ -14,6 +14,7 @@ type EvidenceParam struct { Args []string `json:"args"` Token string `json:"token"` UserIp string `json:"userIp"` + Amount int64 `json:"amount"` } func Evidence(EvidenceParam EvidenceParam) error { From 7440da141f50552123b043155ab0c5d3ab8143e6 Mon Sep 17 00:00:00 2001 From: zhangwei <894646498@qq.com> Date: Tue, 11 Mar 2025 10:06:50 +0800 Subject: [PATCH 5/7] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E9=9B=86=E7=BE=A4?= =?UTF-8?q?=E6=96=B0=E5=A2=9E=E4=BB=B7=E6=A0=BC=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- desc/core/pcm-core.api | 2 +- internal/logic/adapters/createclusterlogic.go | 2 +- internal/logic/adapters/updateclusterlogic.go | 22 +++++++++++++++++++ internal/types/types.go | 2 +- 4 files changed, 25 insertions(+), 3 deletions(-) diff --git a/desc/core/pcm-core.api b/desc/core/pcm-core.api index 8ddb18e7..55025f48 100644 --- a/desc/core/pcm-core.api +++ b/desc/core/pcm-core.api @@ -1372,7 +1372,7 @@ type ( } ) -type ResourcePrice { +type ResourceCost { ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"` ResourceID int64 `json:"resourceId" gorm:"column:resource_id"` Price int `json:"price" gorm:"column:price"` diff --git a/internal/logic/adapters/createclusterlogic.go b/internal/logic/adapters/createclusterlogic.go index 2832f933..c97a70bf 100644 --- a/internal/logic/adapters/createclusterlogic.go +++ b/internal/logic/adapters/createclusterlogic.go @@ -67,7 +67,7 @@ func (l *CreateClusterLogic) CreateCluster(req *types.ClusterCreateReq) (resp *t } // 创建资源价格信息 clusterId, _ := strconv.ParseInt(cluster.Id, 10, 64) - resourcePrice := &types.ResourcePrice{ + resourcePrice := &types.ResourceCost{ ResourceID: clusterId, Price: req.Price, ResourceType: constants.CLUSTER, diff --git a/internal/logic/adapters/updateclusterlogic.go b/internal/logic/adapters/updateclusterlogic.go index 1067a689..9d0bc69c 100644 --- a/internal/logic/adapters/updateclusterlogic.go +++ b/internal/logic/adapters/updateclusterlogic.go @@ -3,8 +3,11 @@ package adapters import ( "context" "github.com/pkg/errors" + "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/constants" "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils" "gorm.io/gorm" + "gorm.io/gorm/clause" + "strconv" "gitlink.org.cn/JointCloud/pcm-coordinator/internal/svc" "gitlink.org.cn/JointCloud/pcm-coordinator/internal/types" @@ -40,5 +43,24 @@ func (l *UpdateClusterLogic) UpdateCluster(req *types.ClusterCreateReq) (resp *t } cluster.Location = location l.svcCtx.DbEngin.Table("t_cluster").Model(&cluster).Updates(&cluster) + // 更新资源价格表 + clusterId, err := strconv.ParseInt(req.Id, 10, 64) + if err != nil { + return nil, err + } + resourceCost := &types.ResourceCost{ + ResourceID: clusterId, + Price: req.Price, + ResourceType: constants.CLUSTER, + CostType: req.CostType, + } + dbResult := l.svcCtx.DbEngin.Clauses(clause.OnConflict{ + Columns: []clause.Column{{Name: "resource_id"}}, + DoUpdates: clause.AssignmentColumns([]string{"price", "cost_type"}), + }).Create(&resourceCost) + + if dbResult.Error != nil { + panic(dbResult.Error) + } return } diff --git a/internal/types/types.go b/internal/types/types.go index e633fe24..b1b4e762 100644 --- a/internal/types/types.go +++ b/internal/types/types.go @@ -1287,7 +1287,7 @@ type CommonResp struct { Data interface{} `json:"data,omitempty"` } -type ResourcePrice struct { +type ResourceCost struct { ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"` ResourceID int64 `json:"resourceId" gorm:"column:resource_id"` Price int `json:"price" gorm:"column:price"` From 6a249ff23e2c72f342f4df67a4da89ba947e206a Mon Sep 17 00:00:00 2001 From: tzwang Date: Tue, 11 Mar 2025 15:36:51 +0800 Subject: [PATCH 6/7] update taskStatusSync --- etc/pcm.yaml | 2 +- internal/config/config.go | 2 +- internal/scheduler/schedulers/aiScheduler.go | 2 +- .../scheduler/service/utils/status/taskStatusSync.go | 11 ++++++++--- 4 files changed, 11 insertions(+), 6 deletions(-) diff --git a/etc/pcm.yaml b/etc/pcm.yaml index 90805d77..c92091af 100644 --- a/etc/pcm.yaml +++ b/etc/pcm.yaml @@ -84,4 +84,4 @@ BlockChain: Type: "2" JcsMiddleware: - Url: 101.201.215.196:7891 \ No newline at end of file + JobStatusReportUrl: 101.201.215.196:7891/jobSet/jobStatusReport \ No newline at end of file diff --git a/internal/config/config.go b/internal/config/config.go index 76131a02..64d525ea 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -65,5 +65,5 @@ type SnowflakeConf struct { } type JcsMiddleware struct { - Url string + JobStatusReportUrl string } diff --git a/internal/scheduler/schedulers/aiScheduler.go b/internal/scheduler/schedulers/aiScheduler.go index 8174f528..2589790b 100644 --- a/internal/scheduler/schedulers/aiScheduler.go +++ b/internal/scheduler/schedulers/aiScheduler.go @@ -320,7 +320,7 @@ func (as *AiScheduler) handleErrors(errs []interface{}, clusters []*strategy.Ass //report status if mode == executor.SUBMIT_MODE_STORAGE_SCHEDULE { - _ = jcs.StatusReport(as.AiService.Conf.JcsMiddleware.Url, report) + _ = jcs.StatusReport(as.AiService.Conf.JcsMiddleware.JobStatusReportUrl, report) } logx.Errorf(errors.New(errmsg).Error()) diff --git a/internal/scheduler/service/utils/status/taskStatusSync.go b/internal/scheduler/service/utils/status/taskStatusSync.go index e6c0f455..64f32bb8 100644 --- a/internal/scheduler/service/utils/status/taskStatusSync.go +++ b/internal/scheduler/service/utils/status/taskStatusSync.go @@ -60,12 +60,17 @@ func UpdateTaskStatus(svc *svc.ServiceContext, tasklist []*types.TaskModel) { } if len(aiTask) == 1 { - if aiTask[0].Status == constants.Completed { + switch aiTask[0].Status { + case constants.Completed: task.Status = constants.Succeeded _ = reportStatusMessages(svc, task, aiTask[0]) - } else { + case constants.Failed: + task.Status = constants.Failed + _ = reportStatusMessages(svc, task, aiTask[0]) + default: task.Status = aiTask[0].Status } + task.StartTime = aiTask[0].StartTime task.EndTime = aiTask[0].EndTime err := svc.Scheduler.AiStorages.UpdateTask(task) @@ -159,7 +164,7 @@ func reportStatusMessages(svc *svc.ServiceContext, task *types.TaskModel, aiTask } report.Messages = append(report.Messages, jobMsg) - _ = jcs.StatusReport(svc.Scheduler.AiService.Conf.JcsMiddleware.Url, report) + _ = jcs.StatusReport(svc.Scheduler.AiService.Conf.JcsMiddleware.JobStatusReportUrl, report) return nil } From 2c4a912a605d312ccd14807ba71a5319edd6c8ab Mon Sep 17 00:00:00 2001 From: tzwang Date: Wed, 12 Mar 2025 18:07:16 +0800 Subject: [PATCH 7/7] update openI submit --- internal/storeLink/openi.go | 35 ++++++++++++++++++++++++++++++++++- pkg/utils/string.go | 11 +++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/internal/storeLink/openi.go b/internal/storeLink/openi.go index f2805606..1dcec340 100644 --- a/internal/storeLink/openi.go +++ b/internal/storeLink/openi.go @@ -16,6 +16,7 @@ import ( "gitlink.org.cn/JointCloud/pcm-openi/model" "mime/multipart" "net/http" + "net/url" "strconv" "strings" "sync" @@ -202,6 +203,12 @@ func (o *OpenI) SubmitTask(ctx context.Context, imageId string, cmd string, envs //params := "{\"parameter\":[{\"label\":\"a\",\"value\":\"1\"},{\"label\":\"b\",\"value\":\"2\"}]}" + // choose imageId and imageUrl + imgId, imgUrl, err := swapImageIdAndImageUrl(imageId) + if err != nil { + return nil, err + } + taskParam := &model.CreateTaskParam{ Description: algorithmId, // temporarily set reponame contained in the algorithmId to desc for missing taskdetail's reponame JobType: TRAIN, @@ -210,7 +217,8 @@ func (o *OpenI) SubmitTask(ctx context.Context, imageId string, cmd string, envs ComputeSource: computeSource, SpecId: int(specId), BranchName: branchName, - ImageId: imageId, + ImageId: imgId, + ImageUrl: imgUrl, DatasetUuidStr: datasetsId, BootFile: bootFile, HasInternet: 2, // 0 不限制;1 不需要互联网;2 需要互联网 @@ -251,6 +259,29 @@ func (o *OpenI) SubmitTask(ctx context.Context, imageId string, cmd string, envs return resp.Data, nil } +func swapImageIdAndImageUrl(imageId string) (string, string, error) { + if imageId == "" { + return "", "", errors.New("imageId is empty") + } + var imgId string + var imgUrl string + + parsedURL, err := url.Parse("http://" + imageId) + if err != nil { + return "", "", err + } + + if utils.IsValidHostAddress(parsedURL.Host) { + imgId = "" + imgUrl = imageId + } else { + imgId = imageId + imgUrl = "" + } + + return imgId, imgUrl, nil +} + func (o OpenI) Stop(ctx context.Context, id string) error { task, err := o.getTrainingTask(ctx, id) if err != nil { @@ -454,6 +485,8 @@ func (o OpenI) GetTrainingTask(ctx context.Context, taskId string) (*collector.T resp.Status = constants.Completed case "FAILED": resp.Status = constants.Failed + case "CREATED_FAILED": + resp.Status = constants.Failed case "RUNNING": resp.Status = constants.Running case "STOPPED": diff --git a/pkg/utils/string.go b/pkg/utils/string.go index 440a56da..a2c26a6d 100644 --- a/pkg/utils/string.go +++ b/pkg/utils/string.go @@ -16,6 +16,7 @@ package utils import ( "math/rand" + "regexp" "strings" "time" ) @@ -37,3 +38,13 @@ func RandomString(n int) string { func TimeString() string { return time.Now().Format(TIMEFORMAT) } + +func IsValidHostAddress(input string) bool { + //pattern := `^(([a-zA-Z0-9]+\.)*[a-zA-Z0-9]+\.[a-zA-Z]{2,}|(\d{1,3}\.){3}\d{1,3}):\d{1,5}$` + pattern := `^((([a-zA-Z0-9]+\.)*[a-zA-Z0-9]+\.[a-zA-Z]{2,}|(\d{1,3}\.){3}\d{1,3}):\d{1,5})$|^.*\.com$` + re, err := regexp.Compile(pattern) + if err != nil { + return false + } + return re.MatchString(input) +}