importer.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. package importer
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "os"
  7. "path/filepath"
  8. "regexp"
  9. "strings"
  10. "sync"
  11. "sync/atomic"
  12. "time"
  13. "git.wecise.com/wecise/cgimport/graph"
  14. "git.wecise.com/wecise/cgimport/odbc"
  15. "git.wecise.com/wecise/cgimport/reader"
  16. "git.wecise.com/wecise/cgimport/schema"
  17. "git.wecise.com/wecise/util/filewalker"
  18. "git.wecise.com/wecise/util/merrs"
  19. "git.wecise.com/wecise/util/rc"
  20. )
  21. var mcfg = odbc.Config
  22. var logger = odbc.Logger
  23. type Importer struct {
  24. datapath string
  25. parallel int
  26. reload bool
  27. importstatus *CGIStatus
  28. fileimportrc *rc.RoutinesController
  29. odbcqueryrc *rc.RoutinesController
  30. odbcimporter *ODBCImporter
  31. starttime time.Time
  32. currentstarttime time.Time
  33. }
  34. func ImportDir(datapath string, parallel int, reload bool) (totalfilescount, totalrecordscount int64, totalusetime time.Duration, filescount, recordscount int64, usetime time.Duration, err error) {
  35. importer := &Importer{
  36. datapath: datapath,
  37. parallel: parallel,
  38. reload: reload,
  39. importstatus: NewCGIStatus(),
  40. fileimportrc: rc.NewRoutinesController("", parallel),
  41. odbcqueryrc: rc.NewRoutinesController("", parallel*10),
  42. odbcimporter: NewODBCImporter(),
  43. }
  44. return importer.Import()
  45. }
  46. func (importer *Importer) Import() (totalfilescount, totalrecordscount int64, totalusetime time.Duration, filescount, recordscount int64, usetime time.Duration, err error) {
  47. if odbc.DevPhase&odbc.DP_PROCESSCONTINUE != 0 && !importer.reload {
  48. err = importer.importstatus.Load()
  49. if err != nil {
  50. return
  51. }
  52. } else {
  53. // reload
  54. // 清除已有类
  55. err = importer.odbcimporter.reload()
  56. if err != nil {
  57. return
  58. }
  59. }
  60. // 建类
  61. err = importer.odbcimporter.ReviseClassStruct()
  62. if err != nil {
  63. return
  64. }
  65. totalfilescount = int64(len(importer.importstatus.ImportStatus))
  66. for _, v := range importer.importstatus.ImportStatus {
  67. totalrecordscount += v.RecordsCount
  68. }
  69. totalusetime = importer.importstatus.TotalUseTime
  70. importer.starttime = time.Now().Add(-totalusetime)
  71. importer.currentstarttime = time.Now()
  72. reedgefile := regexp.MustCompile("(?i).*edge.*.csv")
  73. fc, rc, ut, e := importer.ImportEdgeFiles(reedgefile)
  74. if e != nil {
  75. err = e
  76. return
  77. }
  78. totalfilescount += fc
  79. totalrecordscount += rc
  80. filescount += fc
  81. recordscount += rc
  82. usetime += ut
  83. totalusetime = importer.importstatus.TotalUseTime
  84. fc, rc, ut, e = importer.ImportNonEdgeFiles(reedgefile)
  85. if e != nil {
  86. err = e
  87. return
  88. }
  89. totalfilescount += fc
  90. totalrecordscount += rc
  91. filescount += fc
  92. recordscount += rc
  93. usetime += ut
  94. totalusetime = importer.importstatus.TotalUseTime
  95. importer.importstatus.WaitSaveDone()
  96. importer.alldone()
  97. return
  98. }
  99. func (importer *Importer) ImportEdgeFiles(reedgefile *regexp.Regexp) (filescount, recordscount int64, usetime time.Duration, err error) {
  100. return importer.ImportFiles(func(basedir string, fpath string) FWOP {
  101. if !reedgefile.MatchString(filepath.Base(fpath)) {
  102. // 忽略非EDGE文件
  103. return FWOP_IGNORE
  104. }
  105. return FWOP_CONTINUE
  106. })
  107. }
  108. func (importer *Importer) ImportNonEdgeFiles(reedgefile *regexp.Regexp) (filescount, recordscount int64, usetime time.Duration, err error) {
  109. return importer.ImportFiles(func(basedir string, fpath string) FWOP {
  110. if reedgefile.MatchString(filepath.Base(fpath)) {
  111. // 忽略EDGE文件
  112. return FWOP_IGNORE
  113. }
  114. return FWOP_CONTINUE
  115. })
  116. }
  117. type FWOP int
  118. const (
  119. FWOP_IGNORE FWOP = iota + 1
  120. FWOP_BREAK
  121. FWOP_CONTINUE
  122. )
  123. func (importer *Importer) ImportFiles(fwop func(basedir string, fpath string) FWOP) (filescount, recordscount int64, usetime time.Duration, err error) {
  124. // 遍历文件目录
  125. var wg sync.WaitGroup
  126. fw, e := filewalker.NewFileWalker([]string{importer.datapath}, ".*")
  127. if e != nil {
  128. err = e
  129. return
  130. }
  131. e = fw.List(func(basedir string, fpath string) bool {
  132. if err != nil {
  133. // 前方发生错误,结束遍历
  134. return false
  135. }
  136. if strings.Contains(fpath, string(filepath.Separator)) {
  137. // 忽略子目录,fw.List有序,目录排在文件后面,遇到子目录即可结束遍历
  138. return false
  139. }
  140. switch fwop(basedir, fpath) {
  141. case FWOP_IGNORE:
  142. // 忽略当前文件,继续处理下一文件
  143. return true
  144. case FWOP_BREAK:
  145. // 结束遍历
  146. return false
  147. case FWOP_CONTINUE:
  148. default:
  149. }
  150. // 继续处理当前文件
  151. filename := filepath.Join(basedir, fpath)
  152. wg.Add(1)
  153. // 并发处理
  154. importer.fileimportrc.ConcurCall(1,
  155. func() {
  156. defer wg.Done()
  157. importer.importstatus.mutex.RLock()
  158. importstatus := importer.importstatus.ImportStatus[filename]
  159. importer.importstatus.mutex.RUnlock()
  160. importedrecordscount := int64(0)
  161. if importstatus != nil {
  162. importedrecordscount = importstatus.RecordsCount
  163. return
  164. }
  165. records, e := importer.ImportFile(filename, importedrecordscount)
  166. if e != nil {
  167. err = e
  168. return
  169. }
  170. atomic.AddInt64(&filescount, 1)
  171. atomic.AddInt64(&recordscount, records)
  172. usetime = time.Since(importer.currentstarttime)
  173. importer.importstatus.mutex.Lock()
  174. importer.importstatus.ImportStatus[filename] = &ImportStatus{RecordsCount: importedrecordscount + records}
  175. importer.importstatus.TotalUseTime = time.Since(importer.starttime)
  176. importer.importstatus.mutex.Unlock()
  177. importer.importstatus.Save()
  178. },
  179. )
  180. return true
  181. })
  182. wg.Wait()
  183. if e != nil {
  184. if os.IsNotExist(e) {
  185. err = merrs.NewError(`directory "`+importer.datapath+`" not exist specified by "datapath"`, e)
  186. } else {
  187. err = merrs.NewError(e)
  188. }
  189. return
  190. }
  191. return
  192. }
  193. func (importer *Importer) ImportFile(filepath string, skiprecordscount int64) (blockcount int64, err error) {
  194. f, e := os.Open(filepath)
  195. if e != nil {
  196. return blockcount, merrs.NewError(e, merrs.SSMaps{{"filename": filepath}})
  197. }
  198. defer f.Close()
  199. return importer.importReader(filepath, f, skiprecordscount)
  200. }
  201. func (importer *Importer) importReader(filename string, buf io.Reader, skiprecordscount int64) (blockcount int64, err error) {
  202. var filetype schema.FileType
  203. switch {
  204. case strings.Contains(filename, "_L1_"):
  205. filetype = schema.FT_LEVEL1
  206. case strings.Contains(filename, "_L2_"):
  207. filetype = schema.FT_LEVEL2
  208. case strings.Contains(filename, "_L3_"):
  209. filetype = schema.FT_LEVEL3
  210. case strings.Contains(filename, "_L4_"):
  211. filetype = schema.FT_LEVEL4
  212. case strings.Contains(filename, "_L5_"):
  213. filetype = schema.FT_LEVEL5
  214. case strings.Contains(filename, "_L6_"):
  215. filetype = schema.FT_LEVEL6
  216. case strings.Contains(filename, "_L7_"):
  217. filetype = schema.FT_LEVEL7
  218. case strings.Contains(filename, "_L8_"):
  219. filetype = schema.FT_LEVEL8
  220. case strings.Contains(filename, "MASTER"):
  221. filetype = schema.FT_MASTER
  222. case strings.Contains(filename, "EDGE"):
  223. filetype = schema.FT_EDGE
  224. default:
  225. err = merrs.NewError("filename does not conform to the agreed format " + filename)
  226. return
  227. }
  228. br, e := reader.NewBlockReader(filename, filetype, buf)
  229. if e != nil {
  230. return blockcount, merrs.NewError(e, merrs.SSMaps{{"filename": filename}})
  231. }
  232. var wg sync.WaitGroup
  233. defer importer.done()
  234. defer wg.Wait()
  235. n := int64(0)
  236. for {
  237. if err != nil {
  238. break
  239. }
  240. block, line, linecount, e := br.ReadBlock()
  241. if e != nil {
  242. return blockcount, merrs.NewError(e, merrs.SSMaps{{"filename": filename}, {"linecount": fmt.Sprint(linecount)}, {"line": line}})
  243. }
  244. if block == nil {
  245. return
  246. }
  247. n++
  248. if n <= skiprecordscount {
  249. continue
  250. }
  251. wg.Add(1)
  252. e = importer.odbcqueryrc.ConcurCall(1, func() {
  253. defer wg.Done()
  254. e = importer.importRecord(block, line, filename, filetype, linecount)
  255. if e != nil {
  256. err = merrs.NewError(e, merrs.SSMaps{{"filename": filename}, {"linecount": fmt.Sprint(linecount)}, {"line": line}})
  257. return
  258. }
  259. atomic.AddInt64(&blockcount, 1)
  260. })
  261. if e != nil {
  262. return blockcount, merrs.NewError(e, merrs.SSMaps{{"filename": filename}, {"linecount": fmt.Sprint(linecount)}, {"line": line}})
  263. }
  264. }
  265. return
  266. }
  267. func (importer *Importer) importRecord(record map[string]any, line string, filename string, filetype schema.FileType, linecount int) (err error) {
  268. if odbc.LogDebug {
  269. bs, e := json.MarshalIndent(record, "", " ")
  270. if e != nil {
  271. return merrs.NewError(e)
  272. }
  273. logger.Debug(fmt.Sprint("import ", filename, "[", linecount, "]:", string(bs)))
  274. }
  275. var classname string
  276. switch filetype {
  277. case schema.FT_EDGE:
  278. // err = importer.odbcimporter.InsertEdge(record)
  279. // if err != nil {
  280. // err = merrs.NewError(err, merrs.SSMaps{{"filename": filename}, {"linecount": fmt.Sprint(linecount)}, {"line": line}})
  281. // return
  282. // }
  283. graph.CacheEdgeInfo(record)
  284. default:
  285. classname = string(filetype)
  286. err = importer.odbcimporter.InsertData(classname, record)
  287. if err != nil {
  288. err = merrs.NewError(err, merrs.SSMaps{{"filename": filename}, {"linecount": fmt.Sprint(linecount)}, {"line": line}})
  289. return
  290. }
  291. }
  292. return
  293. }
  294. func (importer *Importer) alldone() {
  295. importer.odbcimporter.alldone()
  296. }
  297. func (importer *Importer) done() {
  298. importer.odbcimporter.done()
  299. }
  300. func Check() {
  301. client := odbc.ODBClient
  302. if client == nil {
  303. return
  304. }
  305. {
  306. mql := "select id,uniqueid,tags,contain,day,vtime from level1 where uniqueid='E2E:OTR0002L'"
  307. r, e := client.Query(mql).Do()
  308. if e != nil {
  309. panic(merrs.NewError(e))
  310. }
  311. bs, _ := json.MarshalIndent(r.Data, "", " ")
  312. fmt.Println(string(bs))
  313. }
  314. }