Merge pull request #5711 from zhaoxiangchun/feature/zxc-suggest-mon

优化建议
This commit is contained in:
Zexi Li
2020-04-16 17:58:09 +08:00
committed by GitHub
36 changed files with 1831 additions and 5 deletions
@@ -1,3 +1,17 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package monitor
import (
@@ -0,0 +1,53 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package monitor
import (
"yunion.io/x/jsonutils"
"yunion.io/x/onecloud/pkg/mcclient"
"yunion.io/x/onecloud/pkg/mcclient/modules/monitor"
options "yunion.io/x/onecloud/pkg/mcclient/options/monitor"
)
func init() {
aN := cmdN("suggestsysalert")
R(&options.SuggestSysAlertListOptions{}, aN("list"), "List all suggestsysrules",
func(s *mcclient.ClientSession, args *options.SuggestSysAlertListOptions) error {
params, err := args.Params()
if err != nil {
return err
}
if len(args.Type) > 0 {
params.Add(jsonutils.NewString(args.Type), "type")
}
ret, err := monitor.SuggestSysAlertManager.List(s, params)
if err != nil {
return err
}
printList(ret, monitor.SuggestSysAlertManager.GetColumns(s))
return nil
})
R(&options.SSuggestAlertShowOptions{}, aN("show"), "Show details of a alert rule",
func(s *mcclient.ClientSession, args *options.SSuggestAlertShowOptions) error {
ret, err := monitor.SuggestSysAlertManager.Get(s, args.ID, nil)
if err != nil {
return err
}
printObject(ret)
return nil
})
}
+84
View File
@@ -0,0 +1,84 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package monitor
import (
"yunion.io/x/onecloud/pkg/mcclient"
"yunion.io/x/onecloud/pkg/mcclient/modules/monitor"
options "yunion.io/x/onecloud/pkg/mcclient/options/monitor"
)
func init() {
aN := cmdN("suggestsysrule")
R(&options.SuggestRuleListOptions{}, aN("list"), "List all suggestsysrules",
func(s *mcclient.ClientSession, args *options.SuggestRuleListOptions) error {
params, err := args.Params()
if err != nil {
return err
}
ret, err := monitor.SuggestSysRuleManager.List(s, params)
if err != nil {
return err
}
printList(ret, monitor.SuggestSysRuleManager.GetColumns(s))
return nil
})
R(&options.SuggestRuleCreateOptions{}, aN("create"), "Create suggestsys rule",
func(s *mcclient.ClientSession, args *options.SuggestRuleCreateOptions) error {
params, err := args.Params()
if err != nil {
return err
}
ret, err := monitor.SuggestSysRuleManager.Create(s, params)
if err != nil {
return err
}
printObject(ret)
return nil
})
R(&options.SuggestRuleShowOptions{}, aN("show"), "Show details of a alert rule",
func(s *mcclient.ClientSession, args *options.SuggestRuleShowOptions) error {
ret, err := monitor.SuggestSysRuleManager.Get(s, args.ID, nil)
if err != nil {
return err
}
printObject(ret)
return nil
})
R(&options.SuggestRuleUpdateOptions{}, aN("update"), "Update a alert rule",
func(s *mcclient.ClientSession, args *options.SuggestRuleUpdateOptions) error {
params, err := args.Params()
if err != nil {
return err
}
ret, err := monitor.SuggestSysRuleManager.Update(s, args.ID, params)
if err != nil {
return err
}
printObject(ret)
return nil
})
R(&options.SuggestRuleDeleteOptions{}, aN("delete"), "Delete alerts",
func(s *mcclient.ClientSession, args *options.SuggestRuleDeleteOptions) error {
ret := monitor.SuggestSysRuleManager.BatchDelete(s, args.ID, nil)
printBatchResults(ret, monitor.SuggestSysRuleManager.GetColumns(s))
return nil
})
}
+1 -1
View File
@@ -130,7 +130,7 @@ require (
yunion.io/x/executor v0.0.0-20200227030256-a18417815e74
yunion.io/x/jsonutils v0.0.0-20200330063846-589d9924bb8b
yunion.io/x/log v0.0.0-20200313080802-57a4ce5966b3
yunion.io/x/pkg v0.0.0-20200312093207-f07f4cb157e0
yunion.io/x/pkg v0.0.0-20200403115157-880d716ed624
yunion.io/x/s3cli v0.0.0-20190917004522-13ac36d8687e
yunion.io/x/sqlchemy v0.0.0-20200312002602-1177cd8fbc57
yunion.io/x/structarg v0.0.0-20190809075558-115bed041de3
+2 -2
View File
@@ -1116,8 +1116,8 @@ yunion.io/x/log v0.0.0-20200313080802-57a4ce5966b3/go.mod h1:LC6f/4FozL0iaAbnFt2
yunion.io/x/pkg v0.0.0-20190620104149-945c25821dbf/go.mod h1:t6rEGG2sQ4J7DhFxSZVOTjNd0YO/KlfWQyK1W4tog+E=
yunion.io/x/pkg v0.0.0-20190628082551-f4033ba2ea30/go.mod h1:t6rEGG2sQ4J7DhFxSZVOTjNd0YO/KlfWQyK1W4tog+E=
yunion.io/x/pkg v0.0.0-20200302034534-fdf44d54b070/go.mod h1:t6rEGG2sQ4J7DhFxSZVOTjNd0YO/KlfWQyK1W4tog+E=
yunion.io/x/pkg v0.0.0-20200312093207-f07f4cb157e0 h1:ZgNhWrnxnVjw53rjx5uV5yQCYcwM8lpVHsrchmHWQI4=
yunion.io/x/pkg v0.0.0-20200312093207-f07f4cb157e0/go.mod h1:t6rEGG2sQ4J7DhFxSZVOTjNd0YO/KlfWQyK1W4tog+E=
yunion.io/x/pkg v0.0.0-20200403115157-880d716ed624 h1:yPayJlTJHOP0vKY6ovliZyTwJY9RvdWEF+QDqnxt/iw=
yunion.io/x/pkg v0.0.0-20200403115157-880d716ed624/go.mod h1:t6rEGG2sQ4J7DhFxSZVOTjNd0YO/KlfWQyK1W4tog+E=
yunion.io/x/s3cli v0.0.0-20190917004522-13ac36d8687e h1:v+EzIadodSwkdZ/7bremd7J8J50Cise/HCylsOJngmo=
yunion.io/x/s3cli v0.0.0-20190917004522-13ac36d8687e/go.mod h1:0iFKpOs1y4lbCxeOmq3Xx/0AcQoewVPwj62eRluioEo=
yunion.io/x/sqlchemy v0.0.0-20200312002602-1177cd8fbc57 h1:KtQAuLJ00RSUVqkiRmJ1DiDABiw0U3xxXnzD3lGavaY=
+14
View File
@@ -1,3 +1,17 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package proxy
import (
+14
View File
@@ -1,3 +1,17 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package monitor
import (
+39
View File
@@ -0,0 +1,39 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package monitor
const (
EIP_UN_USED = "EIP_UNUSED"
DISK_UN_USED = "DISK_UNUSED"
DRIVER_ACTION = "DELETE"
EIP_UNUSED_START_DELETE = "start_delete"
EIP_UNUSED_DELETE_FAIL = "delete_fail"
)
type MonitorSuggest string
type MonitorResourceType string
const (
EIP_MONITOR_RES_TYPE = MonitorResourceType("弹性EIP")
DISK_MONITOR_RES_TYPE = MonitorResourceType("云硬盘")
)
const (
EIP_MONITOR_SUGGEST = MonitorSuggest("释放未使用的EIP")
DISK_MONITOR_SUGGEST = MonitorSuggest("释放未使用的Disk")
)
+74
View File
@@ -0,0 +1,74 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package monitor
import (
"time"
"yunion.io/x/onecloud/pkg/apis"
"yunion.io/x/onecloud/pkg/apis/compute"
)
type SuggestSysAlertListInput struct {
apis.VirtualResourceListInput
apis.EnabledResourceBaseListInput
compute.ManagedResourceListInput
//监控规则typeRule Type
Type string `json:"type"`
ResId string `json:"res_id"`
}
type SuggestSysAlertCreateInput struct {
apis.VirtualResourceCreateInput
Enabled *bool `json:"enabled"`
MonitorConfig *SSuggestSysAlertSetting `json:"monitor_config"`
//转换成ResId
ResID string `json:"res_id"`
Type string `json:"type"`
//Problem jsonutils.JSONObject `json:"problem"`
Suggest string `json:"suggest"`
Action string `json:"action"`
RuleAt time.Time `json:"rule_at"`
}
type SuggestSysAlertDetails struct {
apis.VirtualResourceDetails
compute.CloudregionResourceInfo
RuleName string `json:"rule_name"`
ResType string `json:"res_type"`
Suggest string `json:"suggest"`
Brand string `json:"brand"`
Account string `json:"account"`
}
type SuggestSysAlertUpdateInput struct {
apis.VirtualResourceBaseUpdateInput
Enabled *bool `json:"enabled"`
MonitorConfig *SSuggestSysAlertSetting `json:"monitor_config"`
//转换成ResId
ResID string `json:"res_id"`
Type string `json:"type"`
//Problem jsonutils.JSONObject `json:"problem"`
Suggest string `json:"suggest"`
Action string `json:"action"`
RuleAt time.Time `json:"rule_at"`
}
+69
View File
@@ -0,0 +1,69 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package monitor
import (
"time"
"yunion.io/x/onecloud/pkg/apis"
)
type SuggestSysRuleListInput struct {
apis.VirtualResourceListInput
apis.EnabledResourceBaseListInput
}
type SuggestSysRuleCreateInput struct {
apis.VirtualResourceCreateInput
// 查询指标周期
Period string `json:"period"`
Type string `json:"type"`
Enabled *bool `json:"enabled"`
Setting *SSuggestSysAlertSetting `json:"setting"`
}
type SuggestSysRuleUpdateInput struct {
apis.Meta
// 查询指标周期
Period string `json:"period"`
Name string `json:"name"`
Type string `json:"type"`
Setting *SSuggestSysAlertSetting `json:"setting"`
Enabled *bool `json:"enabled"`
ExecTime time.Time `json:"exec_time"`
}
type SuggestSysRuleDetails struct {
apis.VirtualResourceDetails
ID string `json:"id"`
Name string `json:"name"`
Setting *SSuggestSysAlertSetting `json:"setting"`
Enabled bool `json:"enabled"`
}
type SSuggestSysAlertSetting struct {
EIPUnused *EIPUnused `json:"eip_unused"`
DiskUnused *DiskUnused `json:"disk_unused"`
}
type EIPUnused struct {
//Status string `json:"status"`
}
type DiskUnused struct {
}
+25
View File
@@ -82,3 +82,28 @@ type SNotification struct {
Frequency int64 `json:"frequency"`
Settings interface{} `json:"settings"`
}
// SSuggestSysAlert is an autogenerated struct via yunion.io/x/onecloud/pkg/monitor/models.SSuggestSysAlert.
type SSuggestSysAlert struct {
apis.SVirtualResourceBase
apis.SEnabledResourceBase
// 监控规则对应的json对象
MonitorConfig interface{} `json:"monitor_config"`
// 监控规则typeRule Type
Type string `json:"type"`
ResMeta interface{} `json:"res_meta"`
Problem interface{} `json:"problem"`
Suggest string `json:"suggest"`
Action string `json:"action"`
ResId string `json:"res_id"`
}
// SSuggestSysRule is an autogenerated struct via yunion.io/x/onecloud/pkg/monitor/models.SSuggestSysRule.
type SSuggestSysRule struct {
apis.SVirtualResourceBase
apis.SEnabledResourceBase
Type string `json:"type"`
Period string `json:"period"`
Setting interface{} `json:"setting"`
ExecTime time.Time `json:"exec_time"`
}
@@ -1,3 +1,17 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tasks
import (
+14
View File
@@ -1,3 +1,17 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package guestman
import (
@@ -1,3 +1,17 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package guesthandlers
import (
@@ -1,3 +1,17 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: deploy.proto
@@ -0,0 +1,61 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package modules
import (
"yunion.io/x/onecloud/pkg/mcclient/modulebase"
)
var (
SuggestSysRuleManager *SSuggestSysRuleManager
SuggestSysAlertManager *SSuggestSysAlertManager
)
func init() {
SuggestSysRuleManager = NewSuggestSysRuleManager()
SuggestSysAlertManager = NewSuggestSysAlertManager()
for _, m := range []modulebase.IBaseManager{
SuggestSysRuleManager,
SuggestSysAlertManager,
} {
Register(m)
}
}
type SSuggestSysRuleManager struct {
*modulebase.ResourceManager
}
type SSuggestSysAlertManager struct {
*modulebase.ResourceManager
}
func NewSuggestSysRuleManager() *SSuggestSysRuleManager {
man := NewMonitorV2Manager("suggestsysrule", "suggestsysrules",
[]string{"id", "name", "type", "enabled", "setting"},
[]string{})
return &SSuggestSysRuleManager{
ResourceManager: &man,
}
}
func NewSuggestSysAlertManager() *SSuggestSysAlertManager {
man := NewMonitorV2Manager("suggestsysalert", "suggestsysalerts",
[]string{"id", "name", "type", "res_id", "monitor_config"},
[]string{})
return &SSuggestSysAlertManager{
ResourceManager: &man,
}
}
+14
View File
@@ -1,3 +1,17 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package monitor
import (
@@ -1,3 +1,17 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package monitor
import (
@@ -0,0 +1,62 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package monitor
import (
"yunion.io/x/onecloud/pkg/mcclient/modulebase"
"yunion.io/x/onecloud/pkg/mcclient/modules"
)
var (
SuggestSysRuleManager *SSuggestSysRuleManager
SuggestSysAlertManager *SSuggestSysAlertManager
)
func init() {
SuggestSysRuleManager = NewSuggestSysRuleManager()
SuggestSysAlertManager = NewSuggestSysAlertManager()
for _, m := range []modulebase.IBaseManager{
SuggestSysRuleManager,
SuggestSysAlertManager,
} {
modules.Register(m)
}
}
type SSuggestSysRuleManager struct {
*modulebase.ResourceManager
}
type SSuggestSysAlertManager struct {
*modulebase.ResourceManager
}
func NewSuggestSysRuleManager() *SSuggestSysRuleManager {
man := modules.NewMonitorV2Manager("suggestsysrule", "suggestsysrules",
[]string{"id", "name", "type", "enabled", "setting"},
[]string{})
return &SSuggestSysRuleManager{
ResourceManager: &man,
}
}
func NewSuggestSysAlertManager() *SSuggestSysAlertManager {
man := modules.NewMonitorV2Manager("suggestsysalert", "suggestsysalerts",
[]string{"id", "name", "type", "res_id", "monitor_config"},
[]string{})
return &SSuggestSysAlertManager{
ResourceManager: &man,
}
}
@@ -0,0 +1,28 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package monitor
import (
"yunion.io/x/onecloud/pkg/mcclient/options"
)
type SuggestSysAlertListOptions struct {
options.BaseListOptions
Type string `help:"Type of suggest rule" choices:"EIP_UNUSED|"`
}
type SSuggestAlertShowOptions struct {
ID string `help:"ID or name of the alert" json:"-"`
}
@@ -0,0 +1,84 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package monitor
import (
"strings"
"yunion.io/x/jsonutils"
"yunion.io/x/onecloud/pkg/apis/monitor"
"yunion.io/x/onecloud/pkg/mcclient/options"
)
type SuggestRuleListOptions struct {
options.BaseListOptions
}
type SuggestRuleShowOptions struct {
ID string `help:"ID or name of the alert" json:"-"`
}
type SuggestSysRuleAlertSettingOptions struct {
Status string `help:"Status of eip_unused rule"`
}
type SuggestRuleCreateOptions struct {
SuggestSysRuleAlertSettingOptions
Name string `help:"Name of the alert"`
Type string `help:"Type of suggest rule" choices:"EIP_UNUSED|DISK_UNUSED"`
Enabled bool `help:"Enable rule"`
Period string `help:"Period of suggest rule e.g. '5s', '1m'" default:"30s""`
}
func (opt SuggestRuleCreateOptions) Params() (jsonutils.JSONObject, error) {
input := new(monitor.SuggestSysRuleCreateInput)
input.Name = opt.Name
input.Period = opt.Period
input.Type = strings.ToUpper(opt.Type)
input.Enabled = &opt.Enabled
if input.Type == monitor.EIP_UN_USED {
input.Setting = &monitor.SSuggestSysAlertSetting{
EIPUnused: &monitor.EIPUnused{},
}
}
return input.JSON(input), nil
}
type SuggestRuleUpdateOptions struct {
SuggestSysRuleAlertSettingOptions
ID string `help:"ID or name of the alert" json:"-"`
Name string `help:"Name of the alert"`
Period string `help:"Period of suggest rule e.g. '5s', '1m'" default:"30s""`
Enabled bool `help:"Enable rule"`
Type string `help:"Type of suggest rule" choices:"EIP_UNUSED|"`
}
func (opt SuggestRuleUpdateOptions) Params() (jsonutils.JSONObject, error) {
input := new(monitor.SuggestSysRuleUpdateInput)
input.Period = opt.Period
input.Enabled = &opt.Enabled
input.Name = opt.Name
if input.Type == monitor.EIP_UN_USED {
input.Setting = &monitor.SSuggestSysAlertSetting{
EIPUnused: &monitor.EIPUnused{},
}
}
return input.JSON(input), nil
}
type SuggestRuleDeleteOptions struct {
ID []string `help:"ID of alert to delete"`
}
+268
View File
@@ -0,0 +1,268 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package models
import (
"context"
"strings"
"yunion.io/x/jsonutils"
"yunion.io/x/log"
"yunion.io/x/pkg/errors"
"yunion.io/x/sqlchemy"
"yunion.io/x/onecloud/pkg/apis/monitor"
api "yunion.io/x/onecloud/pkg/apis/monitor"
"yunion.io/x/onecloud/pkg/cloudcommon/db"
"yunion.io/x/onecloud/pkg/httperrors"
"yunion.io/x/onecloud/pkg/mcclient"
"yunion.io/x/onecloud/pkg/util/stringutils2"
)
var (
SuggestSysAlertManager *SSuggestSysAlertManager
)
type SSuggestSysAlertManager struct {
db.SVirtualResourceBaseManager
db.SEnabledResourceBaseManager
}
func init() {
SuggestSysAlertManager = &SSuggestSysAlertManager{
SVirtualResourceBaseManager: db.NewVirtualResourceBaseManager(
&SSuggestSysAlert{},
"suggestsysalert_tbl",
"suggestsysalert",
"suggestsysalerts",
),
}
SuggestSysAlertManager.SetVirtualObject(SuggestSysAlertManager)
}
type SSuggestSysAlert struct {
db.SVirtualResourceBase
db.SEnabledResourceBase
//监控规则对应的json对象
RuleName string `list:"user" update:"user"`
MonitorConfig jsonutils.JSONObject `list:"user" create:"required" update:"user"`
//监控规则typeRule Type
Type string `width:"256" charset:"ascii" list:"user" update:"user"`
ResMeta jsonutils.JSONObject `list:"user" update:"user"`
Problem jsonutils.JSONObject `list:"user" update:"user"`
//Suggest string `width:"256" list:"user" update:"user"`
Action string `width:"256" charset:"ascii" list:"user" update:"user"`
ResId string `width:"256" charset:"ascii" list:"user" update:"user"`
//
CloudEnv string `list:"user" update:"user"`
Provider string `list:"user" update:"user"`
Project string `list:"user" update:"user"`
Cloudaccount string `list:"user" update:"user"`
}
func NewSuggestSysAlertManager(dt interface{}, keyword, keywordPlural string) *SSuggestSysAlertManager {
man := &SSuggestSysAlertManager{
SVirtualResourceBaseManager: db.NewVirtualResourceBaseManager(
dt,
"sugalart_tbl",
keyword,
keywordPlural,
),
}
man.SetVirtualObject(man)
return man
}
func (manager *SSuggestSysAlertManager) ListItemFilter(
ctx context.Context,
q *sqlchemy.SQuery,
userCred mcclient.TokenCredential,
query monitor.SuggestSysAlertListInput) (*sqlchemy.SQuery, error) {
var err error
q, err = manager.SVirtualResourceBaseManager.ListItemFilter(ctx, q, userCred, query.VirtualResourceListInput)
if err != nil {
return nil, errors.Wrap(err, "SVirtualResourceBaseManager.ListItemFilter")
}
q, err = manager.SEnabledResourceBaseManager.ListItemFilter(ctx, q, userCred, query.EnabledResourceBaseListInput)
if err != nil {
return nil, errors.Wrap(err, "SEnabledResourceBaseManager.ListItemFilter")
}
if len(query.Type) > 0 {
q = q.Equals("type", query.Type)
}
if len(query.ResId) > 0 {
q = q.Equals("res_id", query.ResId)
}
//if len(query.Project) > 0 {
//
// q = q.Equals("project", query.Project)
//}
if len(query.Providers) > 0 {
q = q.In("provider", query.Providers)
}
if len(query.Brands) > 0 {
q = q.In("provider", query.Brands)
}
if len(query.Cloudaccount) > 0 {
q.Equals("cloudaccount", query.Cloudaccount)
}
return q, nil
}
func (manager *SSuggestSysAlertManager) GetAlert(id string) (*SSuggestSysAlert, error) {
obj, err := manager.FetchById(id)
if err != nil {
return nil, err
}
return obj.(*SSuggestSysAlert), nil
}
func (man *SSuggestSysAlertManager) OrderByExtraFields(
ctx context.Context,
q *sqlchemy.SQuery,
userCred mcclient.TokenCredential,
input monitor.SuggestSysAlertListInput,
) (*sqlchemy.SQuery, error) {
var err error
q, err = man.SVirtualResourceBaseManager.OrderByExtraFields(ctx, q, userCred, input.VirtualResourceListInput)
if err != nil {
return nil, errors.Wrap(err, "SVirtualResourceBaseManager.OrderByExtraFields")
}
return q, nil
}
func (man *SSuggestSysAlertManager) ValidateCreateData(
ctx context.Context, userCred mcclient.TokenCredential,
ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject,
data monitor.SuggestSysAlertCreateInput) (monitor.SuggestSysAlertCreateInput, error) {
//rule 查询到资源信息后没有将资源id,进行转换
if len(data.ResID) == 0 {
return data, httperrors.NewInputParameterError("not found res_id %q", data.ResID)
}
if len(data.Type) == 0 {
return data, httperrors.NewInputParameterError("not found type %q", data.Type)
}
return data, nil
}
func (man *SSuggestSysAlertManager) FetchCustomizeColumns(
ctx context.Context,
userCred mcclient.TokenCredential,
query jsonutils.JSONObject,
objs []interface{},
fields stringutils2.SSortedStrings,
isList bool,
) []monitor.SuggestSysAlertDetails {
rows := make([]monitor.SuggestSysAlertDetails, len(objs))
virtRows := man.SVirtualResourceBaseManager.FetchCustomizeColumns(ctx, userCred, query, objs, fields, isList)
for i := range rows {
rows[i] = monitor.SuggestSysAlertDetails{
VirtualResourceDetails: virtRows[i],
}
rows[i] = objs[i].(*SSuggestSysAlert).getMoreDetails(rows[i])
}
return rows
}
func (self *SSuggestSysAlert) getMoreDetails(out monitor.SuggestSysAlertDetails) monitor.SuggestSysAlertDetails {
err := self.ResMeta.Unmarshal(&out)
if err != nil {
log.Errorln("SSuggestSysAlert getMoreDetails's error:", err)
}
out.Account = self.Cloudaccount
suggestSysSettingMap, _ := SuggestSysRuleManager.FetchSuggestSysAlartSettings(self.Type)
out.ResType = GetSuggestSysRuleDrivers()[self.Type].GetResourceType()
out.RuleName = strings.ToLower(GetSuggestSysRuleDrivers()[self.Type].GetType())
if _, ok := suggestSysSettingMap[self.Type]; ok {
out.RuleName = suggestSysSettingMap[self.Type].Name
}
switch self.Type {
case monitor.EIP_UN_USED:
out.Suggest = string(monitor.EIP_MONITOR_SUGGEST)
case monitor.DISK_UN_USED:
out.Suggest = string(monitor.DISK_MONITOR_SUGGEST)
}
return out
}
func (manager *SSuggestSysAlertManager) QueryDistinctExtraField(q *sqlchemy.SQuery, field string) (*sqlchemy.SQuery, error) {
var err error
q, err = manager.SVirtualResourceBaseManager.QueryDistinctExtraField(q, field)
if err == nil {
return q, nil
}
switch field {
case "account":
q.AppendField(sqlchemy.DISTINCT(field, q.Field("cloudaccount"))).Distinct()
q.NotEquals("cloudaccount", "")
return q, nil
}
return q, httperrors.ErrNotFound
}
func (alert *SSuggestSysAlert) ValidateUpdateData(
ctx context.Context, userCred mcclient.TokenCredential,
query jsonutils.JSONObject,
data monitor.SuggestSysAlertUpdateInput) (monitor.SuggestSysAlertUpdateInput, error) {
//rule 查询到资源信息后没有将资源id,进行转换
if len(data.ResID) == 0 {
return data, httperrors.NewInputParameterError("not found res_id ")
}
if len(data.Type) == 0 {
return data, httperrors.NewInputParameterError("not found type ")
}
var err error
data.VirtualResourceBaseUpdateInput, err = alert.SVirtualResourceBase.ValidateUpdateData(ctx, userCred, query,
data.VirtualResourceBaseUpdateInput)
if err != nil {
return data, errors.Wrap(err, "SVirtualResourceBase.ValidateUpdateData")
}
return data, nil
}
func (self *SSuggestSysAlert) GetExtraDetails(
ctx context.Context,
userCred mcclient.TokenCredential,
query jsonutils.JSONObject,
isList bool,
) (monitor.SuggestSysAlertDetails, error) {
return monitor.SuggestSysAlertDetails{}, nil
}
func (self *SSuggestSysAlert) PostDelete(ctx context.Context, userCred mcclient.TokenCredential) {
}
func (self *SSuggestSysAlert) CustomizeDelete(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) error {
return self.StartDeleteTask(ctx, userCred)
}
func (self *SSuggestSysAlert) Delete(ctx context.Context, userCred mcclient.TokenCredential) error {
log.Infof("SSuggestSysAlert delete do nothing")
return nil
}
func (self *SSuggestSysAlert) RealDelete(ctx context.Context, userCred mcclient.TokenCredential) error {
return self.SVirtualResourceBase.Delete(ctx, userCred)
}
func (self *SSuggestSysAlert) StartDeleteTask(
ctx context.Context, userCred mcclient.TokenCredential) error {
params := jsonutils.NewDict()
self.SetStatus(userCred, api.EIP_UNUSED_START_DELETE, "")
return GetSuggestSysRuleDrivers()[self.Type].StartResolveTask(ctx, userCred, self, params)
}
+256
View File
@@ -0,0 +1,256 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package models
import (
"context"
"database/sql"
"fmt"
"time"
"yunion.io/x/jsonutils"
"yunion.io/x/log"
"yunion.io/x/pkg/errors"
"yunion.io/x/pkg/tristate"
"yunion.io/x/sqlchemy"
"yunion.io/x/onecloud/pkg/apis/monitor"
"yunion.io/x/onecloud/pkg/cloudcommon/cronman"
"yunion.io/x/onecloud/pkg/cloudcommon/db"
"yunion.io/x/onecloud/pkg/httperrors"
"yunion.io/x/onecloud/pkg/mcclient"
"yunion.io/x/onecloud/pkg/util/stringutils2"
)
var (
SuggestSysRuleManager *SSuggestSysRuleManager
)
func init() {
SuggestSysRuleManager = &SSuggestSysRuleManager{
SVirtualResourceBaseManager: db.NewVirtualResourceBaseManager(
&SSuggestSysRule{},
"suggestsysrule_tbl",
"suggestsysrule",
"suggestsysrules",
),
}
SuggestSysRuleManager.SetVirtualObject(SuggestSysRuleManager)
}
type SSuggestSysRuleManager struct {
db.SVirtualResourceBaseManager
db.SEnabledResourceBaseManager
}
type SSuggestSysRule struct {
db.SVirtualResourceBase
db.SEnabledResourceBase
Type string `width:"256" charset:"ascii" list:"user" update:"user"`
Period string `width:"256" charset:"ascii" list:"user" update:"user"`
Setting jsonutils.JSONObject ` list:"user" update:"user"`
ExecTime time.Time `json:"exec_time"`
}
func (man *SSuggestSysRuleManager) FetchSuggestSysAlartSettings(ruleTypes ...string) (map[string]*monitor.SuggestSysRuleDetails, error) {
objs := make([]SSuggestSysRule, 0)
suggestSysAlerSettingMap := make(map[string]*monitor.SuggestSysRuleDetails, 0)
q := man.Query()
if q == nil {
fmt.Println(" query is nil")
}
if len(ruleTypes) != 0 {
q.Equals("type", ruleTypes)
}
err := db.FetchModelObjects(man, q, &objs)
if err != nil && err != sql.ErrNoRows {
return suggestSysAlerSettingMap, errors.Wrap(err, "FetchSuggestSysAlartSettings")
}
for _, config := range objs {
suggestSysRuleDetails := config.getMoreDetails(monitor.SuggestSysRuleDetails{})
if err != nil {
return suggestSysAlerSettingMap, errors.Wrap(err, "FetchSuggestSysAlartSettings")
}
suggestSysAlerSettingMap[config.Type] = &suggestSysRuleDetails
}
return suggestSysAlerSettingMap, nil
}
//根据数据库中查询得到的信息进行适配转换,同时更新drivers中的内容
func (dConfig *SSuggestSysRule) getSuggestSysAlertSetting() (*monitor.SSuggestSysAlertSetting, error) {
setting := new(monitor.SSuggestSysAlertSetting)
switch dConfig.Type {
case monitor.EIP_UN_USED:
setting.EIPUnused = new(monitor.EIPUnused)
err := dConfig.Setting.Unmarshal(setting.EIPUnused)
if err != nil {
return nil, errors.Wrap(err, "SSuggestSysRule getSuggestSysAlertSetting error")
}
}
return setting, nil
}
type DiskUnsed struct {
Status string
}
func (manager *SSuggestSysRuleManager) ListItemFilter(
ctx context.Context,
q *sqlchemy.SQuery,
userCred mcclient.TokenCredential,
query monitor.SuggestSysRuleListInput) (*sqlchemy.SQuery, error) {
var err error
q, err = manager.SVirtualResourceBaseManager.ListItemFilter(ctx, q, userCred, query.VirtualResourceListInput)
if err != nil {
return nil, errors.Wrap(err, "SVirtualResourceBaseManager.ListItemFilter")
}
q, err = manager.SEnabledResourceBaseManager.ListItemFilter(ctx, q, userCred, query.EnabledResourceBaseListInput)
if err != nil {
return nil, errors.Wrap(err, "SEnabledResourceBaseManager.ListItemFilter")
}
return q, nil
}
func (man *SSuggestSysRuleManager) ValidateCreateData(
ctx context.Context, userCred mcclient.TokenCredential,
ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject,
data monitor.SuggestSysRuleCreateInput) (monitor.SuggestSysRuleCreateInput, error) {
if data.Period == "" {
// default 30s
data.Period = "30s"
}
if _, err := time.ParseDuration(data.Period); err != nil {
return data, httperrors.NewInputParameterError("Invalid period format: %s", data.Period)
}
if dri, ok := suggestSysRuleDrivers[data.Type]; !ok {
return data, httperrors.NewInputParameterError("not support type %q", data.Type)
} else {
//Type is uniq
err := db.NewNameValidator(man, ownerId, data.Type, "")
if err != nil {
return data, err
}
if data.Setting != nil {
err = dri.ValidateSetting(data.Setting)
if err != nil {
return data, errors.Wrap(err, "validate setting error")
}
}
}
return data, nil
}
func (rule *SSuggestSysRule) ValidateUpdateData(
ctx context.Context, userCred mcclient.TokenCredential,
query jsonutils.JSONObject,
data monitor.SuggestSysRuleUpdateInput) (monitor.SuggestSysRuleUpdateInput, error) {
if data.Period == "" {
// default 30s
data.Period = "30s"
}
if data.Enabled != nil {
rule.SetEnabled(*data.Enabled)
}
if _, err := time.ParseDuration(data.Period); err != nil {
return data, httperrors.NewInputParameterError("Invalid period format: %s", data.Period)
}
if data.Setting != nil {
err := suggestSysRuleDrivers[rule.Type].ValidateSetting(data.Setting)
if err != nil {
return data, errors.Wrap(err, "validate setting error")
}
}
return data, nil
}
func (man *SSuggestSysRuleManager) FetchCustomizeColumns(
ctx context.Context,
userCred mcclient.TokenCredential,
query jsonutils.JSONObject,
objs []interface{},
fields stringutils2.SSortedStrings,
isList bool,
) []monitor.SuggestSysRuleDetails {
rows := make([]monitor.SuggestSysRuleDetails, len(objs))
virtRows := man.SVirtualResourceBaseManager.FetchCustomizeColumns(ctx, userCred, query, objs, fields, isList)
for i := range rows {
rows[i] = monitor.SuggestSysRuleDetails{
VirtualResourceDetails: virtRows[i],
}
}
return rows
}
func (self *SSuggestSysRule) getMoreDetails(out monitor.SuggestSysRuleDetails) monitor.SuggestSysRuleDetails {
var err error
out.Setting, err = self.getSuggestSysAlertSetting()
if err != nil {
log.Errorln("getMoreDetails err:", err)
}
out.ID = self.Id
out.Name = self.Name
out.Enabled = self.GetEnabled()
return out
}
func (self *SSuggestSysRule) GetExtraDetails(
ctx context.Context,
userCred mcclient.TokenCredential,
query jsonutils.JSONObject,
isList bool,
) (monitor.SuggestSysRuleDetails, error) {
return monitor.SuggestSysRuleDetails{}, nil
}
//after create, update Cronjob's info
func (self *SSuggestSysRule) PostCreate(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data jsonutils.JSONObject) {
self.SVirtualResourceBase.PostCreate(ctx, userCred, ownerId, query, data)
cronman.GetCronJobManager().Remove(self.Type)
if self.Enabled.Bool() {
dur, _ := time.ParseDuration(self.Period)
cronman.GetCronJobManager().AddJobAtIntervalsWithStartRun(self.Type, dur,
suggestSysRuleDrivers[self.Type].DoSuggestSysRule, true)
}
}
//after update, update Cronjob's info
func (self *SSuggestSysRule) PostUpdate(
ctx context.Context, userCred mcclient.TokenCredential,
query jsonutils.JSONObject, data jsonutils.JSONObject) {
cronman.GetCronJobManager().Remove(self.Type)
if self.Enabled.Bool() {
dur, _ := time.ParseDuration(self.Period)
cronman.GetCronJobManager().AddJobAtIntervalsWithStartRun(self.Type, dur,
suggestSysRuleDrivers[self.Type].DoSuggestSysRule, true)
}
}
func (self *SSuggestSysRule) AllowPerformEnable(ctx context.Context, userCred mcclient.TokenCredential,
query jsonutils.JSONObject, data jsonutils.JSONObject) bool {
return db.IsAdminAllowPerform(userCred, self, "Enable")
}
func (self *SSuggestSysRule) PerformEnable(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) (jsonutils.JSONObject, error) {
if !self.Enabled.Bool() {
db.Update(self, func() error {
self.Enabled = tristate.True
return nil
})
db.OpsLog.LogEvent(self, db.ACT_ENABLE, "", userCred)
self.PostUpdate(ctx, userCred, query, data)
}
return nil, nil
}
@@ -0,0 +1,55 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package models
import (
"context"
"yunion.io/x/jsonutils"
"yunion.io/x/onecloud/pkg/apis/monitor"
"yunion.io/x/onecloud/pkg/mcclient"
)
var (
//存储初始化的内容,同时起到默认配置的作用。
suggestSysRuleDrivers = make(map[string]ISuggestSysRuleDriver, 0)
)
type ISuggestSysRuleDriver interface {
GetType() string
GetResourceType() string
//validate on create
ValidateSetting(input *monitor.SSuggestSysAlertSetting) error
//method call for cronjob
DoSuggestSysRule(ctx context.Context, userCred mcclient.TokenCredential, isStart bool)
Run(instance *monitor.SSuggestSysAlertSetting)
//resolve thing for the rule
StartResolveTask(ctx context.Context, userCred mcclient.TokenCredential, suggestSysAlert *SSuggestSysAlert,
params *jsonutils.JSONDict) error
Resolve(data *SSuggestSysAlert) error
}
func RegisterSuggestSysRuleDrivers(drvs ...ISuggestSysRuleDriver) {
for _, drv := range drvs {
suggestSysRuleDrivers[drv.GetType()] = drv
}
}
func GetSuggestSysRuleDrivers() map[string]ISuggestSysRuleDriver {
return suggestSysRuleDrivers
}
+11
View File
@@ -18,6 +18,7 @@ import (
"yunion.io/x/onecloud/pkg/appsrv"
"yunion.io/x/onecloud/pkg/appsrv/dispatcher"
"yunion.io/x/onecloud/pkg/cloudcommon/db"
"yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
"yunion.io/x/onecloud/pkg/monitor/models"
)
@@ -27,6 +28,14 @@ func InitHandlers(app *appsrv.Application) {
db.RegisterModelManager(db.TenantCacheManager)
db.RegisterModelManager(db.UserCacheManager)
db.RegistUserCredCacheUpdater()
for _, manager := range []db.IModelManager{
taskman.TaskManager,
taskman.SubTaskManager,
taskman.TaskObjectManager,
} {
db.RegisterModelManager(manager)
}
for _, manager := range []db.IModelManager{
db.OpsLog,
db.Metadata,
@@ -35,6 +44,8 @@ func InitHandlers(app *appsrv.Application) {
models.NodeAlertManager,
models.MeterAlertManager,
models.NotificationManager,
models.SuggestSysRuleManager,
models.SuggestSysAlertManager,
} {
db.RegisterModelManager(manager)
handler := db.NewModelHandler(manager)
+8 -1
View File
@@ -25,6 +25,7 @@ import (
"yunion.io/x/onecloud/pkg/cloudcommon"
common_app "yunion.io/x/onecloud/pkg/cloudcommon/app"
"yunion.io/x/onecloud/pkg/cloudcommon/cronman"
"yunion.io/x/onecloud/pkg/cloudcommon/db"
common_options "yunion.io/x/onecloud/pkg/cloudcommon/options"
_ "yunion.io/x/onecloud/pkg/monitor/alerting"
@@ -34,6 +35,8 @@ import (
_ "yunion.io/x/onecloud/pkg/monitor/notifydrivers"
"yunion.io/x/onecloud/pkg/monitor/options"
"yunion.io/x/onecloud/pkg/monitor/registry"
"yunion.io/x/onecloud/pkg/monitor/suggestsysdrivers"
_ "yunion.io/x/onecloud/pkg/monitor/tasks"
_ "yunion.io/x/onecloud/pkg/monitor/tsdb/driver/influxdb"
)
@@ -57,6 +60,11 @@ func StartService() {
go startServices()
cron := cronman.InitCronJobManager(true, opts.CronJobWorkerCount)
suggestsysdrivers.InitSuggestSysRuleCronjob()
cron.Start()
defer cron.Stop()
common_app.ServeForever(app, baseOpts)
}
@@ -96,7 +104,6 @@ func startServices() {
return nil
})
}
defer func() {
log.Debugf("Waiting on services...")
if waitErr := childRoutines.Wait(); waitErr != nil {
+144
View File
@@ -0,0 +1,144 @@
package suggestsysdrivers
import (
"context"
"database/sql"
"yunion.io/x/jsonutils"
"yunion.io/x/log"
"yunion.io/x/pkg/errors"
"yunion.io/x/onecloud/pkg/apis/monitor"
"yunion.io/x/onecloud/pkg/cloudcommon/db"
"yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
"yunion.io/x/onecloud/pkg/mcclient"
"yunion.io/x/onecloud/pkg/mcclient/auth"
"yunion.io/x/onecloud/pkg/mcclient/modules"
"yunion.io/x/onecloud/pkg/monitor/models"
)
type DiskUnused struct {
monitor.DiskUnused
}
func NewDiskUnusedDriver() models.ISuggestSysRuleDriver {
return &DiskUnused{
monitor.DiskUnused{},
}
}
func (rule *DiskUnused) GetType() string {
return monitor.DISK_UN_USED
}
func (rule *DiskUnused) GetResourceType() string {
return string(monitor.DISK_MONITOR_RES_TYPE)
}
func (rule *DiskUnused) DoSuggestSysRule(ctx context.Context, userCred mcclient.TokenCredential, isStart bool) {
var instance *monitor.SSuggestSysAlertSetting
suggestSysSettingMap, err := models.SuggestSysRuleManager.FetchSuggestSysAlartSettings(rule.GetType())
if err != nil {
log.Errorln("DoSuggestSysRule error :", err)
return
}
if details, ok := suggestSysSettingMap[rule.GetType()]; ok {
instance = details.Setting
}
rule.Run(instance)
}
func (rule *DiskUnused) Run(instance *monitor.SSuggestSysAlertSetting) {
oldAlert, err := rule.getLastAlerts()
if err != nil {
log.Errorln(err)
return
}
newAlerts, err := rule.getLatestAlerts(instance)
if err != nil {
log.Errorln(errors.Wrap(err, "DiskUnused getLatestAlerts error"))
return
}
DealAlertData(oldAlert, newAlerts.Value())
}
func (rule *DiskUnused) getLastAlerts() ([]models.SSuggestSysAlert, error) {
oldAlert := make([]models.SSuggestSysAlert, 0)
q := models.SuggestSysAlertManager.Query()
q.Equals("type", monitor.DISK_UN_USED)
err := db.FetchModelObjects(models.SuggestSysAlertManager, q, &oldAlert)
if err != nil && err != sql.ErrNoRows {
log.Errorln(errors.Wrap(err, "db.FetchModelObjects"))
return oldAlert, err
}
return oldAlert, nil
}
func (rule *DiskUnused) getLatestAlerts(instance *monitor.SSuggestSysAlertSetting) (*jsonutils.JSONArray, error) {
session := auth.GetAdminSession(context.Background(), "", "")
query := jsonutils.NewDict()
query.Add(jsonutils.NewString("0"), "limit")
query.Add(jsonutils.NewBool(true), "unused")
query.Add(jsonutils.NewString("system"), "scope")
disks, err := modules.Disks.List(session, query)
if err != nil {
return nil, err
}
DiskUnusedArr := jsonutils.NewArray()
for _, disk := range disks.Data {
suggestSysAlert := new(models.SSuggestSysAlert)
alertData := jsonutils.DeepCopy(disk).(*jsonutils.JSONDict)
id, _ := alertData.GetString("id")
alertData.Add(jsonutils.NewString(id), "res_id")
alertData.Remove("id")
err := alertData.Unmarshal(suggestSysAlert)
if err != nil {
return DiskUnusedArr, errors.Wrap(err, "getEIPUnused's alertData Unmarshal error")
}
input := &monitor.SSuggestSysAlertSetting{
DiskUnused: &monitor.DiskUnused{},
}
suggestSysAlert.MonitorConfig = jsonutils.Marshal(input)
if instance != nil {
suggestSysAlert.MonitorConfig = jsonutils.Marshal(instance)
}
problem := jsonutils.NewDict()
problem.Add(jsonutils.NewString(rule.GetType()), "disk")
suggestSysAlert.Problem = problem
suggestSysAlert.Type = rule.GetType()
suggestSysAlert.Action = monitor.DRIVER_ACTION
suggestSysAlert.ResMeta = disk
DiskUnusedArr.Add(jsonutils.Marshal(suggestSysAlert))
}
return DiskUnusedArr, nil
}
func (rule *DiskUnused) ValidateSetting(input *monitor.SSuggestSysAlertSetting) error {
obj := new(monitor.DiskUnused)
input.DiskUnused = obj
return nil
}
func (rule *DiskUnused) StartResolveTask(ctx context.Context, userCred mcclient.TokenCredential,
suggestSysAlert *models.SSuggestSysAlert, params *jsonutils.JSONDict) error {
task, err := taskman.TaskManager.NewTask(ctx, "ResolveUnusedTask", suggestSysAlert, userCred, params, "", "", nil)
if err != nil {
return err
}
task.ScheduleRun(nil)
return nil
}
func (rule *DiskUnused) Resolve(data *models.SSuggestSysAlert) error {
session := auth.GetAdminSession(context.Background(), "", "")
_, err := modules.Disks.Delete(session, data.ResId, jsonutils.NewDict())
if err != nil {
log.Errorln("delete unused eip error", err)
return err
}
return nil
}
+15
View File
@@ -0,0 +1,15 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package suggestsysdrivers // import "yunion.io/x/onecloud/pkg/monitor/suggestsysdrivers"
@@ -0,0 +1,98 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package suggestsysdrivers
import (
"context"
"database/sql"
"fmt"
"time"
"yunion.io/x/jsonutils"
"yunion.io/x/log"
"yunion.io/x/onecloud/pkg/cloudcommon/cronman"
"yunion.io/x/onecloud/pkg/cloudcommon/db"
"yunion.io/x/onecloud/pkg/mcclient/auth"
"yunion.io/x/onecloud/pkg/monitor/models"
)
func init() {
models.RegisterSuggestSysRuleDrivers(NewEIPUsedDriver(), NewDiskUnusedDriver())
}
func InitSuggestSysRuleCronjob() {
objs := make([]models.SSuggestSysRule, 0)
q := models.SuggestSysRuleManager.Query()
if q == nil {
fmt.Println(" query is nil")
}
err := db.FetchModelObjects(models.SuggestSysRuleManager, q, &objs)
if err != nil && err != sql.ErrNoRows {
log.Errorln("InitSuggestSysRuleCronjob db.FetchModelObjects error")
}
for _, driver := range models.GetSuggestSysRuleDrivers() {
cronman.GetCronJobManager().AddJobAtIntervalsWithStartRun(driver.GetType(), time.Duration(30)*time.Second,
driver.DoSuggestSysRule, true)
}
for _, suggestSysRuleConfig := range objs {
cronman.GetCronJobManager().Remove(suggestSysRuleConfig.Type)
if suggestSysRuleConfig.Enabled.Bool() {
dur, _ := time.ParseDuration(suggestSysRuleConfig.Period)
cronman.GetCronJobManager().AddJobAtIntervalsWithStartRun(suggestSysRuleConfig.Type, dur,
models.GetSuggestSysRuleDrivers()[suggestSysRuleConfig.Type].DoSuggestSysRule, true)
}
}
}
func DealAlertData(oldAlerts []models.SSuggestSysAlert, newAlerts []jsonutils.JSONObject) {
oldMap := make(map[string]models.SSuggestSysAlert, 0)
for _, alert := range oldAlerts {
oldMap[alert.ResId] = alert
}
for _, newAlert := range newAlerts {
res_id, _ := newAlert.GetString("res_id")
if oldAlert, ok := oldMap[res_id]; ok {
//更新的alert
_, err := db.Update(&oldAlert, func() error {
err := newAlert.Unmarshal(&oldAlert)
if err != nil {
errMsg := fmt.Sprintf("unmarshal fail: %s", err)
log.Errorf(errMsg)
}
return nil
})
if err != nil {
log.Errorln("更新alert失败", err)
}
delete(oldMap, res_id)
} else {
//新增的alert
adminCredential := auth.AdminCredential()
_, err := db.DoCreate(models.SuggestSysAlertManager, context.Background(), adminCredential, nil, newAlert,
adminCredential)
if err != nil {
log.Errorln(err)
}
}
}
for _, oldAlert := range oldMap {
err := oldAlert.Delete(context.Background(), auth.AdminCredential())
if err != nil {
log.Errorln("删除旧alert数据失败", err)
}
}
}
+160
View File
@@ -0,0 +1,160 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package suggestsysdrivers
import (
"context"
"database/sql"
"yunion.io/x/jsonutils"
"yunion.io/x/log"
"yunion.io/x/pkg/errors"
"yunion.io/x/onecloud/pkg/apis/monitor"
"yunion.io/x/onecloud/pkg/cloudcommon/db"
"yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
"yunion.io/x/onecloud/pkg/mcclient"
"yunion.io/x/onecloud/pkg/mcclient/auth"
"yunion.io/x/onecloud/pkg/mcclient/modules"
"yunion.io/x/onecloud/pkg/monitor/models"
)
type EIPUnused struct {
monitor.EIPUnused
}
func (_ *EIPUnused) GetType() string {
return monitor.EIP_UN_USED
}
func (_ *EIPUnused) GetResourceType() string {
return string(monitor.EIP_MONITOR_RES_TYPE)
}
func NewEIPUsedDriver() models.ISuggestSysRuleDriver {
return &EIPUnused{
monitor.EIPUnused{
//Status: "",
},
}
}
func (dri *EIPUnused) ValidateSetting(input *monitor.SSuggestSysAlertSetting) error {
obj := new(monitor.EIPUnused)
input.EIPUnused = obj
return nil
}
func (rule *EIPUnused) Run(instance *monitor.SSuggestSysAlertSetting) {
oldAlert := make([]models.SSuggestSysAlert, 0)
q := models.SuggestSysAlertManager.Query()
q.Equals("type", monitor.EIP_UN_USED)
err := db.FetchModelObjects(models.SuggestSysAlertManager, q, &oldAlert)
if err != nil && err != sql.ErrNoRows {
log.Errorln(errors.Wrap(err, "db.FetchModelObjects"))
return
}
newAlert, err := rule.getEIPUnused(instance)
if err != nil {
log.Errorln(errors.Wrap(err, "getEIPUnused error"))
return
}
DealAlertData(oldAlert, newAlert.Value())
}
func (rule *EIPUnused) getEIPUnused(instance *monitor.SSuggestSysAlertSetting) (*jsonutils.JSONArray, error) {
//处理逻辑
session := auth.GetAdminSession(context.Background(), "", "")
query := jsonutils.NewDict()
query.Add(jsonutils.NewString("0"), "limit")
query.Add(jsonutils.NewString("system"), "scope")
rtn, err := modules.Elasticips.List(session, query)
if err != nil {
return nil, err
}
EIPUnsedArr := jsonutils.NewArray()
for _, row := range rtn.Data {
if row.ContainsIgnoreCases("associate_type") || row.ContainsIgnoreCases("associate_id") {
continue
}
suggestSysAlert := new(models.SSuggestSysAlert)
alertData := jsonutils.DeepCopy(row).(*jsonutils.JSONDict)
id, _ := alertData.GetString("id")
alertData.Add(jsonutils.NewString(id), "res_id")
alertData.Remove("id")
err := alertData.Unmarshal(suggestSysAlert)
if err != nil {
return EIPUnsedArr, errors.Wrap(err, "getEIPUnused's alertData Unmarshal error")
}
if val, err := alertData.GetString("account"); err == nil {
suggestSysAlert.Cloudaccount = val
}
input := &monitor.SSuggestSysAlertSetting{
EIPUnused: &monitor.EIPUnused{},
}
suggestSysAlert.MonitorConfig = jsonutils.Marshal(input)
if instance != nil {
suggestSysAlert.MonitorConfig = jsonutils.Marshal(instance)
}
problem := jsonutils.NewDict()
problem.Add(jsonutils.NewString(rule.GetType()), "eip")
suggestSysAlert.Problem = problem
suggestSysAlert.Type = rule.GetType()
suggestSysAlert.Action = monitor.DRIVER_ACTION
suggestSysAlert.ResMeta = row
EIPUnsedArr.Add(jsonutils.Marshal(suggestSysAlert))
}
return EIPUnsedArr, nil
}
func (rule *EIPUnused) DoSuggestSysRule(ctx context.Context, userCred mcclient.TokenCredential,
isStart bool) {
var instance *monitor.SSuggestSysAlertSetting
suggestSysSettingMap, err := models.SuggestSysRuleManager.FetchSuggestSysAlartSettings(rule.GetType())
if err != nil {
log.Errorln("DoSuggestSysRule error :", err)
return
}
if details, ok := suggestSysSettingMap[rule.GetType()]; ok {
instance = details.Setting
}
rule.Run(instance)
}
func (rule *EIPUnused) Resolve(data *models.SSuggestSysAlert) error {
session := auth.GetAdminSession(context.Background(), "", "")
_, err := modules.Elasticips.Delete(session, data.ResId, jsonutils.NewDict())
if err != nil {
log.Errorln("delete unused eip error", err)
return err
}
return nil
}
func (rule *EIPUnused) StartResolveTask(ctx context.Context, userCred mcclient.TokenCredential,
suggestSysAlert *models.SSuggestSysAlert, params *jsonutils.JSONDict) error {
task, err := taskman.TaskManager.NewTask(ctx, "ResolveUnusedTask", suggestSysAlert, userCred, params, "", "", nil)
if err != nil {
return err
}
task.ScheduleRun(nil)
return nil
}
+15
View File
@@ -0,0 +1,15 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tasks // import "yunion.io/x/onecloud/pkg/monitor/tasks"
+60
View File
@@ -0,0 +1,60 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tasks
import (
"context"
"fmt"
"yunion.io/x/jsonutils"
api "yunion.io/x/onecloud/pkg/apis/monitor"
"yunion.io/x/onecloud/pkg/cloudcommon/db"
"yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
"yunion.io/x/onecloud/pkg/monitor/models"
"yunion.io/x/onecloud/pkg/util/logclient"
)
type ResolveUnusedTask struct {
taskman.STask
}
func init() {
taskman.RegisterTask(ResolveUnusedTask{})
}
func (self *ResolveUnusedTask) OnInit(ctx context.Context, obj db.IStandaloneModel, data jsonutils.JSONObject) {
suggestSysAlert := obj.(*models.SSuggestSysAlert)
err := models.GetSuggestSysRuleDrivers()[suggestSysAlert.Type].Resolve(suggestSysAlert)
if err != nil {
msg := fmt.Sprintf("fail to delete EIP %s", err)
self.taskFail(ctx, suggestSysAlert, msg)
}
err = suggestSysAlert.RealDelete(ctx, self.UserCred)
if err != nil {
msg := fmt.Sprintf("fail to delete SSuggestSysAlert %s", err)
self.taskFail(ctx, suggestSysAlert, msg)
}
logclient.AddActionLogWithStartable(self, suggestSysAlert, logclient.ACT_DELETE, nil, self.UserCred, true)
self.SetStageComplete(ctx, nil)
}
func (self *ResolveUnusedTask) taskFail(ctx context.Context, alert *models.SSuggestSysAlert, msg string) {
alert.SetStatus(self.UserCred, api.EIP_UNUSED_DELETE_FAIL, msg)
db.OpsLog.LogEvent(alert, db.ACT_DELOCATE, msg, self.GetUserCred())
logclient.AddActionLogWithStartable(self, alert, logclient.ACT_DELETE, msg, self.UserCred, false)
self.SetStageFailed(ctx, msg)
return
}
+14
View File
@@ -1 +1,15 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package vcenter // import "yunion.io/x/onecloud/pkg/multicloud/esxi/vcenter"
+14
View File
@@ -1,3 +1,17 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package vcenter
type SVCenterAccessInfo struct {
+1 -1
View File
@@ -1019,7 +1019,7 @@ yunion.io/x/jsonutils
# yunion.io/x/log v0.0.0-20200313080802-57a4ce5966b3
yunion.io/x/log
yunion.io/x/log/hooks
# yunion.io/x/pkg v0.0.0-20200312093207-f07f4cb157e0
# yunion.io/x/pkg v0.0.0-20200403115157-880d716ed624
yunion.io/x/pkg/errors
yunion.io/x/pkg/gotypes
yunion.io/x/pkg/prettytable
+4
View File
@@ -33,3 +33,7 @@ func Wrapf(err error, format string, args ...interface{}) error {
func Cause(err error) error {
return errors.Cause(err)
}
func Errorf(format string, args ...interface{}) error {
return errors.Errorf(format, args...)
}