liuxiaolong
2019-08-02 0e323ad7f5e91710afec7a01e3186268bf3e97f6
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package controllers
 
import (
    "basic.com/dbapi.git"
    "encoding/json"
    "fmt"
    "github.com/gin-gonic/gin"
    "github.com/satori/go.uuid"
    "log"
    "time"
    "webserver/extend/code"
    "webserver/extend/config"
    "webserver/extend/esutil"
    "webserver/extend/logger"
    "webserver/extend/util"
    "webserver/models"
)
 
type DbTableController struct {
}
 
// @Summary 显示底库列表
// @Description 显示同步或本地库列表
// @Accept  x-www-form-urlencoded
// @Produce json
// @Tags dbtable
// @Param isSync path string true "是否同步库  1 同步库 2本地库  qita 全部库"
// @Success 200 {string} json "{"code":200, msg:"目录结构数据", success:true}"
// @Failure 500 {string} json "{"code":500,  msg:"返回错误信息", success:false}"
// @Router /data/api-v/dbtable/queryDbTables/{isSync} [POST]
func (dbt DbTableController) QueryDbTables(c *gin.Context) {
    url := "http://" + config.EsInfo.Masterip + ":" + config.EsInfo.Httpport +
        "/" + config.EsInfo.EsIndex.DbTables.IndexName + "/_search"
    isSync := c.Params.ByName("isSync")
    var setApi dbapi.SysSetApi
    _, sysconf := setApi.GetServerInfo()
    analyServerFilterStr := ""
    if isSync == "1" {
        analyServerFilterStr = "{\"term\":{\"analyServerId\":\"\"}}" // / 同步库
    } else if isSync == "2" {
        analyServerFilterStr = "{\"term\":{\"analyServerId\":\"" + sysconf.ServerId + "\"}}" // 本地库
    }
    if analyServerFilterStr != "" {
        analyServerFilterStr = "," + analyServerFilterStr
    }
    params := "{\"query\":{\"bool\":{\"must\":[" +
        "{\"term\":{\"isDelete\":\"0\"}}" + analyServerFilterStr + "]}}," +
        "\"from\":0,\"size\":1000,\"sort\":{\"id\":{\"order\":\"asc\"}}}"
    logger.Debug("请求url:%s;\n 请求参数params:%s", url, params)
 
    data := esutil.GetEsDataReq(url, params, true)
    //c.JSON(200, data)
    util.ResponseFormat(c, code.Success, data)
}
 
// 依据底库id  查询数据
func QueryDbTableInfo(tableId string) map[string]interface{} {
    url := "http://" + config.EsInfo.Masterip + ":" + config.EsInfo.Httpport +
        "/" + config.EsInfo.EsIndex.DbTables.IndexName + "/" + config.EsInfo.EsIndex.DbTables.IndexName + "/" + tableId
    logger.Debug("请求url:%s;", url)
    data := esutil.GetEsDataInfo(url, true)
    return data
}
 
// @Summary 修改底库
// @Description 修改同步或本地库
// @Accept  json
// @Produce json
// @Tags dbtable
// @Param table body models.Dbtables true "底库数据"
// @Success 200 {string} json "{"code":200, msg:"目录结构数据", success:true}"
// @Failure 500 {string} json "{"code":500,  msg:"返回错误信息", success:false}"
// @Router /data/api-v/dbtable/updateDbTables [POST]
func (dbt DbTableController) UpdateDbTables(c *gin.Context) {
    dbtable := new(models.Dbtables)
    c.BindJSON(&dbtable)
    uuid := c.Params.ByName("id")
    if uuid == "" {
        uuid = dbtable.Id
        logger.Debug("body中获取底库id")
    }
    if dbtable.EndTime == "" {
        flag := UpdateEndTime(dbtable.Id)
        if flag == false {
            util.ResponseFormat(c, code.ServiceInsideError, "修改失败")
        }
    }
    url := "http://" + config.EsInfo.Masterip + ":" + config.EsInfo.Httpport +
        "/" + config.EsInfo.EsIndex.DbTables.IndexName + "/" + config.EsInfo.EsIndex.DbTables.IndexType + "/" + uuid + "/_update?refresh=wait_for"
    dbtable.PriUpdate()
    dbTableByte, err := json.Marshal(dbtable)
    if err != nil {
        log.Fatalf("Json marshaling failed:%s", err)
    }
    logger.Debug("%s\n", dbTableByte)
    params := "{\"doc\":" + string(dbTableByte) + "}"
    logger.Debug("请求url:%s;\n 请求参数params:%s", url, params)
    data := esutil.GetEsDataReq(url, params, false)
    //c.JSON(200, changeEsRespData(data, "修改成功"))
    result := changeEsRespData(data, "修改成功")
    if result["success"].(bool) {
        //code.Success.Message = "修改底库成功"
        //if dbtable.Enable ==1 {
        //    discovery.AddDbMessage(&protomsg.EsPersonCacheChange{
        //        Type: protomsg.EsCacheChanged_T_DbTable,
        //        PersonId: "",
        //        TableId: []string{ dbtable.Id },
        //        Feature: "",
        //        Action: protomsg.DbAction_Insert,
        //    })
        //} else {
        //    discovery.AddDbMessage(&protomsg.EsPersonCacheChange{
        //        Type: protomsg.EsCacheChanged_T_DbTable,
        //        PersonId: "",
        //        TableId: []string{ dbtable.Id },
        //        Feature: "",
        //        Action: protomsg.DbAction_Delete,
        //    })
        //}
        util.ResponseFormat(c, code.Success, result["data"])
    } else {
        //code.ServiceInsideError.Message += result["msg"].(string)
        util.ResponseFormat(c, code.ServiceInsideError, result["data"])
    }
}
 
func UpdateEndTime(id string) (flag bool) {
    flag = false
    url := "http://" + config.EsInfo.Masterip + ":" + config.EsInfo.Httpport +
        "/" + config.EsInfo.EsIndex.DbTables.IndexName + "/" + config.EsInfo.EsIndex.DbTables.IndexType + "/" + id + "/_update?refresh=wait_for"
    prama := "{\"script\":\"ctx._source.remove(\\\"endTime\\\")\"}"
    buf, err := esutil.EsReq("POST", url, []byte(prama))
    if err != nil {
        fmt.Println("http request info is err!")
        return
    }
    var info interface{}
    json.Unmarshal(buf, &info)
    out, ok := info.(map[string]interface{})
    if !ok {
        fmt.Println("http response interface can not change map[string]interface{}")
        return
    }
    middle, ok := out["result"].(string)
    if !ok {
        fmt.Println("first result change error!")
        return
    }
    if middle == "updated" {
        flag = true
    }
    return flag
}
 
// @Summary 添加底库
// @Description 添加同步或本地库
// @Accept  json
// @Produce json
// @Tags dbtable
// @Param obj body models.Dbtables true "底库数据"
// @Success 200 {string} json "{"code":200, msg:"目录结构数据", success:true}"
// @Failure 500 {string} json "{"code":500,  msg:"返回错误信息", success:false}"
// @Router /data/api-v/dbtable/addDbTableInfo [PUT]
func (dbt DbTableController) AddDbTableInfo(c *gin.Context) {
    dbtable := new(models.Dbtables)
    c.BindJSON(&dbtable)
    tableId := uuid.NewV4().String()
    dbtable.Id = tableId
    if dbtable.AnalyServerId == "sync" {
        dbtable.AnalyServerId = ""
    }
    if dbtable.AnalyServerId == "local" {
        var setApi dbapi.SysSetApi
        _, sysconf := setApi.GetServerInfo()
        dbtable.AnalyServerId = sysconf.ServerId
    }
    url := "http://" + config.EsInfo.Masterip + ":" + config.EsInfo.Httpport +
        "/" + config.EsInfo.EsIndex.DbTables.IndexName + "/" + config.EsInfo.EsIndex.DbTables.IndexType + "/" + tableId + "?refresh=wait_for"
    dbtable.PriInsert() // 添加时间和创建人
 
    currentTime := time.Now()
    startTime := dbtable.StartTime
    endTime := ""
    if dbtable.EndTime != "" {
        endTime = dbtable.EndTime
    }
    st, _ := time.ParseInLocation("2006-01-02 15:04:05", startTime, time.Local)
    if endTime != "" {
        et, _ := time.ParseInLocation("2006-01-02 15:04:05", endTime, time.Local)
        if et.After(currentTime) && st.Before(currentTime) {
            dbtable.Enable = 1
        } else {
            dbtable.Enable = 0
        }
    } else if st.Before(currentTime) && endTime == "" {
        dbtable.Enable = 1
    } else {
        dbtable.Enable = 0
    }
    dbTableByte, err := json.Marshal(dbtable)
    if err != nil {
        log.Fatalf("Json marshaling failed:%s", err)
    }
    //logger.Debugf("%s\n", dbTableByte)
    params := string(dbTableByte)
    logger.Debug("请求url:%s;\n 请求参数params:%s", url, params)
    data, _ := esutil.PutEsDataReq(url, params)
    //c.JSON(200, changeEsRespData(data, "添加成功"))
    result := changeEsRespData(data, "添加成功")
    if result["success"].(bool) {
        //code.Success.Message = "添加底库成功"
        util.ResponseFormat(c, code.Success, result["data"])
    } else {
        //code.ServiceInsideError.Message += result["msg"].(string)
        util.ResponseFormat(c, code.ServiceInsideError, result["data"])
    }
}
 
// @Summary 删除底库
// @Description 删除同步或本地库
// @Accept  x-www-form-urlencoded
// @Produce json
// @Tags dbtable
// @Param uuid path string true "底库id "
// @Success 200 {string} json "{"code":200, msg:"目录结构数据", success:true}"
// @Failure 500 {string} json "{"code":500,  msg:"返回错误信息", success:false}"
// @Router /data/api-v/dbtable/deleteDBtablesById/{id} [POST]
func (dbt DbTableController) DeleteDbTables(c *gin.Context) {
    uuid := c.Params.ByName("id")
    url := "http://" + config.EsInfo.Masterip + ":" + config.EsInfo.Httpport +
        "/" + config.EsInfo.EsIndex.DbTables.IndexName + "/" + config.EsInfo.EsIndex.DbTables.IndexType + "/" + uuid + "/_update?refresh=wait_for"
    params := "{\"doc\":{\"isDelete\":1}}"
    logger.Debug("删除请求url:%s;\n 请求参数params:%s", url, params)
    data := esutil.GetEsDataReq(url, params, false)
    //c.JSON(200, changeEsRespData(data, "删除成功"))
    result := changeEsRespData(data, "删除成功")
    if result["success"].(bool) {
        //code.Success.Message = "删除底库成功"
        util.ResponseFormat(c, code.Success, result["data"])
    } else {
        //code.ServiceInsideError.Message += result["msg"].(string)
        util.ResponseFormat(c, code.ServiceInsideError, result["data"])
    }
}
 
func changeEsRespData(respData map[string]interface{}, successMsg string) (result map[string]interface{}) {
    id := respData["_id"]
    result = map[string]interface{}{}
    if id != "" {
        result["code"] = 200
        data := make(map[string]interface{})
        data["uuid"] = id
        result["data"] = data
        result["success"] = true
        result["msg"] = successMsg
    } else {
        result["data"] = nil
        result["success"] = false
        status := respData["status"]
        if status != nil {
            result["code"] = status
            result["msg"] = respData["error"].(map[string]interface{})["reason"]
        } else {
            result["msg"] = "服务器异常"
            result["code"] = 500
        }
    }
    return result
}