actionlog.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package models
  15. import (
  16. "context"
  17. "fmt"
  18. "strings"
  19. "time"
  20. "yunion.io/x/jsonutils"
  21. "yunion.io/x/log"
  22. "yunion.io/x/pkg/errors"
  23. "yunion.io/x/pkg/tristate"
  24. "yunion.io/x/pkg/util/timeutils"
  25. "yunion.io/x/pkg/utils"
  26. "yunion.io/x/sqlchemy"
  27. "yunion.io/x/onecloud/pkg/apis"
  28. api "yunion.io/x/onecloud/pkg/apis/logger"
  29. noapi "yunion.io/x/onecloud/pkg/apis/notify"
  30. "yunion.io/x/onecloud/pkg/cloudcommon/consts"
  31. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  32. "yunion.io/x/onecloud/pkg/cloudcommon/notifyclient"
  33. "yunion.io/x/onecloud/pkg/logger/extern"
  34. "yunion.io/x/onecloud/pkg/logger/options"
  35. "yunion.io/x/onecloud/pkg/mcclient"
  36. "yunion.io/x/onecloud/pkg/util/logclient"
  37. )
  38. var WhiteListMap = make(map[string]bool)
  39. func InitActionWhiteList() {
  40. for _, value := range logclient.WhiteList {
  41. WhiteListMap[value] = true
  42. }
  43. }
  44. func IsInActionWhiteList(key string) bool {
  45. return WhiteListMap[key]
  46. }
  47. type SActionlogManager struct {
  48. db.SOpsLogManager
  49. db.SRecordChecksumResourceBaseManager
  50. lastExceedCountNotifyTime time.Time
  51. }
  52. type SActionlog struct {
  53. db.SOpsLog
  54. db.SRecordChecksumResourceBase
  55. // 开始时间
  56. StartTime time.Time `nullable:"true" list:"user" create:"optional"`
  57. // 结果
  58. Success bool `list:"user" create:"required"`
  59. // 服务类别
  60. Service string `width:"32" charset:"utf8" nullable:"true" list:"user" create:"optional"`
  61. // 系统账号
  62. IsSystemAccount tristate.TriState `default:"false" list:"user" create:"optional"`
  63. // 用户IP
  64. Ip string `width:"17" charset:"ascii" nullable:"true" list:"user" create:"optional"`
  65. // 风险级别 0 紧急(Emergency) 1 警报(Alert) 2 关键(Critical) 3 错误(Error) 4 警告(Warning) 5 通知(Notice) 6 信息(informational) 7 调试(debug)
  66. Severity api.TEventSeverity `width:"32" charset:"ascii" nullable:"false" default:"INFO" list:"user" create:"optional"`
  67. // 行为类别,0 一般行为(normal) 1 异常行为(abnormal) 2 违规行为(illegal)
  68. Kind api.TEventKind `width:"16" charset:"ascii" nullable:"false" default:"NORMAL" list:"user" create:"optional"`
  69. }
  70. var ActionLog *SActionlogManager
  71. var AdminActionLog *SActionlogManager
  72. var logQueue = make(chan *SActionlog, 50)
  73. func InitActionLog() {
  74. InitActionWhiteList()
  75. initTable := func(tbname string) *SActionlogManager {
  76. tbl := &SActionlogManager{
  77. SOpsLogManager: db.NewOpsLogManager(SActionlog{}, tbname, "action", "actions", "ops_time", consts.OpsLogWithClickhouse),
  78. }
  79. if consts.OpsLogWithClickhouse {
  80. tbl.SRecordChecksumResourceBaseManager = *db.NewRecordChecksumResourceBaseManager()
  81. }
  82. return tbl
  83. }
  84. ActionLog = initTable("action_tbl")
  85. ActionLog.SetVirtualObject(ActionLog)
  86. if options.Options.EnableSeparateAdminLog {
  87. AdminActionLog = initTable("admin_action_tbl")
  88. AdminActionLog.SetVirtualObject(AdminActionLog)
  89. }
  90. }
  91. func isRoleInNames(userCred mcclient.TokenCredential, roles []string) bool {
  92. for _, r := range userCred.GetRoles() {
  93. if utils.IsInStringArray(r, roles) {
  94. return true
  95. }
  96. }
  97. return false
  98. }
  99. func (manager *SActionlogManager) GetImmutableInstance(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject) db.IModelManager {
  100. match := isRoleInNames(userCred, options.Options.AuditorRoleNames)
  101. log.Debugf("roles: %s auditor: %s match auditor: %v", userCred.GetRoles(), options.Options.AuditorRoleNames, match)
  102. if options.Options.EnableSeparateAdminLog && match {
  103. return AdminActionLog
  104. }
  105. return ActionLog
  106. }
  107. func (manager *SActionlogManager) GetMutableInstance(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) db.IModelManager {
  108. matchSec := isRoleInNames(userCred, options.Options.SecadminRoleNames)
  109. matchOps := isRoleInNames(userCred, options.Options.OpsadminRoleNames)
  110. log.Debugf("roles: %s sec: %s match: %v ops: %s match: %v", userCred.GetRoles(), options.Options.SecadminRoleNames, matchSec, options.Options.OpsadminRoleNames, matchOps)
  111. if options.Options.EnableSeparateAdminLog && (matchSec || matchOps) {
  112. return AdminActionLog
  113. }
  114. return ActionLog
  115. }
  116. func (action *SActionlog) CustomizeCreate(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data jsonutils.JSONObject) error {
  117. log.Debugf("action: %s", data)
  118. now := time.Now().UTC()
  119. action.OpsTime = now
  120. if action.StartTime.IsZero() {
  121. action.StartTime = now
  122. }
  123. if len(action.Severity) == 0 {
  124. if action.Success {
  125. action.Severity = api.SeverityInfo
  126. } else {
  127. action.Severity = api.SeverityError
  128. }
  129. }
  130. return action.SOpsLog.CustomizeCreate(ctx, userCred, ownerId, query, data)
  131. }
  132. func (self *SActionlog) PostCreate(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data jsonutils.JSONObject) {
  133. self.SOpsLog.PostCreate(ctx, userCred, ownerId, query, data)
  134. parts := []string{}
  135. // 厂商代码
  136. parts = append(parts, options.Options.SyslogVendorCode)
  137. // 事件ID
  138. parts = append(parts, fmt.Sprintf("%d", self.Id))
  139. // 用户名
  140. parts = append(parts, self.User)
  141. // 模块类型
  142. parts = append(parts, self.Service)
  143. // 事件时间
  144. parts = append(parts, timeutils.MysqlTime(self.OpsTime))
  145. // 事件类型
  146. parts = append(parts, self.Action)
  147. succ := "success"
  148. if !self.Success {
  149. succ = "fail"
  150. }
  151. // 事件结果
  152. parts = append(parts, succ)
  153. // 事件描述
  154. notes := fmt.Sprintf("%s %s %s(%s)", self.Action, self.ObjType, self.ObjName, self.ObjId)
  155. if len(self.Notes) > 0 {
  156. notes = fmt.Sprintf("%s: %s", notes, self.Notes)
  157. }
  158. notes = extern.FormatMsg(notes, options.Options.SyslogSeparator, options.Options.SyslogSepEscape)
  159. parts = append(parts, notes)
  160. kind := ""
  161. switch self.Kind {
  162. case api.KindNormal:
  163. kind = "0"
  164. case api.KindAbnormal:
  165. kind = "1"
  166. case api.KindIllegal:
  167. kind = "2"
  168. }
  169. // 行为类别
  170. parts = append(parts, kind)
  171. parts = append(parts, "")
  172. msg := strings.Join(parts, options.Options.SyslogSeparator)
  173. if len(self.Severity) == 0 {
  174. if self.Success {
  175. extern.Info(msg)
  176. } else {
  177. extern.Error(msg)
  178. }
  179. } else {
  180. switch self.Severity {
  181. case api.SeverityEmergency:
  182. extern.Emergency(msg)
  183. case api.SeverityAlert:
  184. extern.Alert(msg)
  185. case api.SeverityCritical:
  186. extern.Critical(msg)
  187. case api.SeverityError:
  188. extern.Error(msg)
  189. case api.SeverityWarning:
  190. extern.Warning(msg)
  191. case api.SeverityNotice:
  192. extern.Notice(msg)
  193. case api.SeverityInfo:
  194. extern.Info(msg)
  195. case api.SeverityDebug:
  196. extern.Debug(msg)
  197. default:
  198. extern.Info(msg)
  199. }
  200. }
  201. for k, v := range map[string]string{
  202. "service": self.Service,
  203. "action": self.Action,
  204. "obj_type": self.ObjType,
  205. "severity": string(self.Severity),
  206. "kind": string(self.Kind),
  207. } {
  208. db.DistinctFieldManager.InsertOrUpdate(ctx, ActionLog, k, v)
  209. }
  210. ActionLog.notifyIfExceedCount(ctx, self)
  211. }
  212. func (manager *SActionlogManager) notifyIfExceedCount(ctx context.Context, l *SActionlog) {
  213. exceedCnt := options.Options.ActionLogExceedCount
  214. if exceedCnt <= 0 {
  215. return
  216. }
  217. interval := utils.ToDuration(options.Options.ActionLogExceedCountNotifyInterval)
  218. if time.Since(manager.lastExceedCountNotifyTime) < interval {
  219. return
  220. }
  221. totalCnt := ActionLog.Query().Count()
  222. if totalCnt >= exceedCnt {
  223. result := map[string]interface{}{
  224. "action": jsonutils.Marshal(l),
  225. "current_count": totalCnt,
  226. "exceed_count": exceedCnt,
  227. }
  228. resultObj := jsonutils.Marshal(result).(*jsonutils.JSONDict)
  229. notifyclient.SystemExceptionNotifyWithResult(ctx, noapi.ActionExceedCount, noapi.TOPIC_RESOURCE_ACTION_LOG, "", resultObj)
  230. manager.lastExceedCountNotifyTime = time.Now()
  231. }
  232. }
  233. // 操作日志列表
  234. func (manager *SActionlogManager) ListItemFilter(
  235. ctx context.Context,
  236. q *sqlchemy.SQuery,
  237. userCred mcclient.TokenCredential,
  238. input api.ActionLogListInput,
  239. ) (*sqlchemy.SQuery, error) {
  240. var err error
  241. q, err = manager.SOpsLogManager.ListItemFilter(ctx, q, userCred, input.OpsLogListInput)
  242. if err != nil {
  243. return nil, errors.Wrapf(err, "ListItemFilter")
  244. }
  245. if len(input.Service) > 0 {
  246. if len(input.Service) == 1 {
  247. q = q.Equals("service", input.Service[0])
  248. } else {
  249. q = q.In("service", input.Service)
  250. }
  251. }
  252. if input.Success != nil {
  253. q = q.Equals("success", *input.Success)
  254. }
  255. if input.IsSystemAccount != nil {
  256. q = q.Equals("is_system_account", *input.IsSystemAccount)
  257. }
  258. if len(input.Ip) > 0 {
  259. if len(input.Ip) == 1 {
  260. q = q.Equals("ip", input.Ip[0])
  261. } else {
  262. q = q.In("ip", input.Ip)
  263. }
  264. }
  265. if len(input.Severity) > 0 {
  266. if len(input.Severity) == 1 {
  267. q = q.Equals("severity", input.Severity[0])
  268. } else {
  269. q = q.In("severity", input.Severity)
  270. }
  271. }
  272. if len(input.Kind) > 0 {
  273. if len(input.Kind) == 1 {
  274. q = q.Equals("kind", input.Kind[0])
  275. } else {
  276. q = q.In("kind", input.Kind)
  277. }
  278. }
  279. return q, nil
  280. }
  281. func (manager *SActionlogManager) GetPropertyDistinctField(ctx context.Context, userCred mcclient.TokenCredential, input apis.DistinctFieldInput) (jsonutils.JSONObject, error) {
  282. fields, err := db.DistinctFieldManager.GetObjectDistinctFields(manager.Keyword())
  283. if err != nil {
  284. return nil, errors.Wrapf(err, "DistinctFieldManager.GetObjectDistinctFields")
  285. }
  286. fieldMaps := map[string][]string{}
  287. for _, field := range fields {
  288. _, ok := fieldMaps[field.Key]
  289. if !ok {
  290. fieldMaps[field.Key] = []string{}
  291. }
  292. fieldMaps[field.Key] = append(fieldMaps[field.Key], field.Value)
  293. }
  294. ret := map[string][]string{}
  295. for _, key := range input.Field {
  296. ret[key], _ = fieldMaps[key]
  297. }
  298. return jsonutils.Marshal(ret), nil
  299. }
  300. func (action *SActionlog) GetI18N(ctx context.Context) *jsonutils.JSONDict {
  301. r := jsonutils.NewDict()
  302. act18 := logclient.OpsActionI18nTable.Lookup(ctx, action.Action)
  303. ser18 := logclient.OpsServiceI18nTable.Lookup(ctx, action.Service)
  304. obj18 := logclient.OpsObjTypeI18nTable.Lookup(ctx, action.ObjType)
  305. r.Set("action", jsonutils.NewString(act18))
  306. r.Set("service", jsonutils.NewString(ser18))
  307. r.Set("obj_type", jsonutils.NewString(obj18))
  308. return r
  309. }
  310. func (action *SActionlog) GetModelManager() db.IModelManager {
  311. return action.SModelBase.GetModelManager()
  312. }
  313. func (man *SActionlogManager) GetI18N(ctx context.Context, idstr string, resObj jsonutils.JSONObject) *jsonutils.JSONDict {
  314. if idstr != "distinct-field" {
  315. return nil
  316. }
  317. res := &struct {
  318. Action []string `json:"action"`
  319. Service []string `json:"service"`
  320. ObjType []string `json:"obj_type"`
  321. }{}
  322. if err := resObj.Unmarshal(res); err != nil {
  323. return nil
  324. }
  325. for i, act := range res.Action {
  326. act18 := logclient.OpsActionI18nTable.Lookup(ctx, act)
  327. res.Action[i] = act18
  328. }
  329. for i, ser := range res.Service {
  330. ser18 := logclient.OpsServiceI18nTable.Lookup(ctx, ser)
  331. res.Service[i] = ser18
  332. }
  333. for i, obj := range res.ObjType {
  334. obj18 := logclient.OpsObjTypeI18nTable.Lookup(ctx, obj)
  335. res.ObjType[i] = obj18
  336. }
  337. robj := jsonutils.Marshal(res)
  338. rdict := robj.(*jsonutils.JSONDict)
  339. return rdict
  340. }
  341. // Websockets 不再拉取 ActionLog 的消息,因此注释掉如下代码
  342. // 可以保留,以便有需求时,再次打开
  343. // func (manager *SActionlogManager) OnCreateComplete(ctx context.Context, items []db.IModel, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) {
  344. // actionLog := items[0].(*SActionlog)
  345. // if IsInActionWhiteList(actionLog.Action) {
  346. // select {
  347. // case logQueue <- actionLog:
  348. // return
  349. // default:
  350. // log.Warningf("Log queue full, insert failed, log ignored: %s", actionLog.Action)
  351. // }
  352. // }
  353. // }
  354. //
  355. // func StartNotifyToWebsocketWorker() {
  356. // go func() {
  357. // for {
  358. // actionLog := <-logQueue
  359. // params := jsonutils.Marshal(actionLog)
  360. // s := auth.GetAdminSession(context.Background(), "", "")
  361. // _, err := websocket.Websockets.PerformClassAction(s, "action-log", params)
  362. // if err != nil {
  363. // log.Errorf("Send action log error %s", err)
  364. // }
  365. // }
  366. // }()
  367. // }
  368. func (manager *SActionlogManager) InitializeData() error {
  369. fileds, err := db.DistinctFieldManager.GetObjectDistinctFields(manager.Keyword())
  370. if err != nil {
  371. return errors.Wrapf(err, "GetObjectDistinctFields")
  372. }
  373. if len(fileds) > 0 {
  374. return nil
  375. }
  376. for _, key := range []string{"service", "obj_type", "action", "severity", "kind"} {
  377. values, err := db.FetchDistinctField(manager, key)
  378. if err != nil {
  379. return errors.Wrapf(err, "db.FetchDistinctField")
  380. }
  381. for _, value := range values {
  382. if len(value) > 0 {
  383. err = db.DistinctFieldManager.InsertOrUpdate(context.TODO(), manager, key, value)
  384. if err != nil {
  385. return errors.Wrapf(err, "DistinctFieldManager.InsertOrUpdate(%s, %s)", key, value)
  386. }
  387. }
  388. }
  389. }
  390. return nil
  391. }