1
13693261870
2022-09-16 762f2fb45db004618ba099aa3c0bd89dba1eb843
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package com.landtool.lanbase.modules.sys.controller;
 
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.landtool.lanbase.common.utils.RedisUtils;
import com.landtool.lanbase.modules.sys.service.MonitorService;
import com.landtool.lanbase.modules.sys.service.impl.MonitorServiceImpl;
 
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
 
@RequestMapping("/api/monitor")
@Controller
@CrossOrigin
public class SecModController {
    @Autowired
    private MonitorService monitor;
 
    @Autowired
    public RedisUtils redisUtils;
 
 
    /**
     * 用户在线人数统计
     */
    @RequestMapping("/onlineUser")
    public @ResponseBody String onlineUser() {
        ConcurrentHashMap<String, Double> info = redisUtils.get("onlineuser", ConcurrentHashMap.class);
        JSONObject json = new JSONObject();
        Map<String,Object> col=new HashMap<>();
        
        // 查询在线用户信息
        info.forEach(new BiConsumer<String, Double>() {
 
        
            @Override
            public void accept(String t, Double u) {
                col.put(t, new Date(u.longValue()) );
                
                
            }
        });
        json.put("count", col.size());
        json.put("onlineUser", col);
        return JSONObject.toJSONStringWithDateFormat(json, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue);
    }
 
 
    /**
     *查询异常系统
     */
    @RequestMapping("/queryErrorSystem")
    public @ResponseBody String queryErrorSystem(Integer page,Integer limit) {
        JSONObject json = new JSONObject();
        Map<String,Object> param=new HashMap<>();
        param.put("page", page);
        param.put("limit", limit);
         List<Map> list=monitor.queryProblemSystem(param);
        json.put("count", list.size());
        json.put("errorsystem", list);
        return JSONObject.toJSONStringWithDateFormat(json, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue);
    }
 
    /**
     * 查询用户访问行为
     */
    @RequestMapping("/queryUserTrace")
    public @ResponseBody String queryUserTrace(String username,Integer page,Integer limit) {
        JSONObject json = new JSONObject();
        Map<String,Object> param=new HashMap<>();
        param.put("username",username);
        param.put("page", page);
        param.put("limit", limit);
        List<Map> list=monitor.queryUserTrace(param);
        json.put("total", list.size());
        json.put("data", list);
        return JSONObject.toJSONStringWithDateFormat(json, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue);
    }
 
 
 
    /**
     * 用户在线人数查询
     */
    @RequestMapping("/queryonlineUser")
    public @ResponseBody String queryonlineUser() {
           if(!redisUtils.exists("onlineuser")){
            return "not exist";
        }else{    
        ConcurrentHashMap<String, Object> info = redisUtils.get("onlineuser", ConcurrentHashMap.class);
        ConcurrentHashMap<String, Object> vkinfo=new ConcurrentHashMap<>();
        List<String> list = new ArrayList<String>();
        Consumer<String> consumer = (str) -> {
            JSONObject json=JSON.parseObject(info.get(str).toString());
            vkinfo.put(json.getString("username"), json.getLong("time"));
            list.add(json.getString("username"));
        };
        info.forEachKey(info.size(), consumer);
        List<Map> personlist = new ArrayList<>();
        if(!list.isEmpty()){
        personlist = monitor.queryUsers(list);
        }
        JSONObject json = new JSONObject();
        // 查询在线用户信息
        json.put("count", info.size());
        personlist.forEach(new Consumer<Map>() {
 
            @Override
            public void accept(Map t) {
                /** modified by qufangxu**/
                Long times = (Long) vkinfo.get((String)t.get("loginname"));
                t.put("time", new Date(  times.longValue() ));
            }
        });
        json.put("onlineUser", personlist);
        return JSONObject.toJSONStringWithDateFormat(json, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue);
        }
    }
    
    
    /**
     * 用户行为分析
     */
    @RequestMapping("/analysisUser")
    public @ResponseBody String analysisUserAction(Integer userid,Integer day,String startdate,String enddate, String username) {
        //分析
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("day",day);
        map.put("startdate",startdate);
        map.put("enddate",enddate);
        map.put("userid",userid );
        map.put("username",username );
        List<Map> list=monitor.queryUserops(map);
        return JSONObject.toJSONString(list, SerializerFeature.WriteMapNullValue);
    }
    public String serverstatus() throws InterruptedException {
        JSONObject json=new JSONObject();
        json.put("cpuinfo", printlnCpuInfo());
        json.put("meminfo", MemInfo());
        return JSONObject.toJSONStringWithDateFormat(json, "yyyy-MM-dd HH:mm:ss", SerializerFeature.PrettyFormat);
        
    }
    private static JSONObject printlnCpuInfo() throws InterruptedException {
        //map.put("----------------cpu信息----------------");
        SystemInfo systemInfo = new SystemInfo();
        CentralProcessor processor = systemInfo.getHardware().getProcessor();
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        // 睡眠1s
        TimeUnit.SECONDS.sleep(1);
        long[] ticks = processor.getSystemCpuLoadTicks();
        long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
        long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()];
        long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];
        long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()];
        long cSys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
        long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()];
        long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
        long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
        long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
        JSONObject map=new JSONObject();
      
    
        map.put("cpuCore", processor.getLogicalProcessorCount());
        map.put("cpuSysUsage", new DecimalFormat("#.##%").format(cSys * 1.0 / totalCpu));
        map.put("cpuUserUsage", new DecimalFormat("#.##%").format(user * 1.0 / totalCpu));
        map.put("cpuRtcWaitUsage", new DecimalFormat("#.##%").format(iowait * 1.0 / totalCpu));
        map.put("cpuRtcUseUsage", new DecimalFormat("#.##%").format(1.0-(idle * 1.0 / totalCpu)));
        return map;
    }
 
    public static JSONObject MemInfo(){
        JSONObject map=new JSONObject();
        SystemInfo systemInfo = new SystemInfo();
        GlobalMemory memory = systemInfo.getHardware().getMemory();
        //总内存
        long totalByte = memory.getTotal();
        //剩余
        long acaliableByte = memory.getAvailable();
        map.put("totalmem", formatByte(totalByte));
        map.put("use", formatByte(totalByte-acaliableByte));
        map.put("remainmem", formatByte(acaliableByte));
        map.put("usage", new DecimalFormat("#.##%").format((totalByte-acaliableByte)*1.0/totalByte));
        return map;
    }
    public static String formatByte(long byteNumber){
        //换算单位
        double FORMAT = 1024.0;
        double kbNumber = byteNumber/FORMAT;
        if(kbNumber<FORMAT){
            return new DecimalFormat("#.##KB").format(kbNumber);
        }
        double mbNumber = kbNumber/FORMAT;
        if(mbNumber<FORMAT){
            return new DecimalFormat("#.##MB").format(mbNumber);
        }
        double gbNumber = mbNumber/FORMAT;
        if(gbNumber<FORMAT){
            return new DecimalFormat("#.##GB").format(gbNumber);
        }
        double tbNumber = gbNumber/FORMAT;
        return new DecimalFormat("#.##TB").format(tbNumber);
    }
 
}