uast.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. package hercules
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "io"
  8. goioutil "io/ioutil"
  9. "os"
  10. "runtime"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/gogo/protobuf/proto"
  15. "github.com/jeffail/tunny"
  16. "gopkg.in/bblfsh/client-go.v1"
  17. "gopkg.in/bblfsh/sdk.v1/protocol"
  18. "gopkg.in/bblfsh/sdk.v1/uast"
  19. "gopkg.in/src-d/enry.v1"
  20. "gopkg.in/src-d/go-git.v4"
  21. "gopkg.in/src-d/go-git.v4/plumbing"
  22. "gopkg.in/src-d/go-git.v4/plumbing/object"
  23. "gopkg.in/src-d/go-git.v4/utils/ioutil"
  24. "gopkg.in/src-d/go-git.v4/utils/merkletrie"
  25. "gopkg.in/src-d/hercules.v3/pb"
  26. )
  27. type UASTExtractor struct {
  28. Endpoint string
  29. Context func() context.Context
  30. PoolSize int
  31. Languages map[string]bool
  32. FailOnErrors bool
  33. ProcessedFiles map[string]int
  34. clients []*bblfsh.BblfshClient
  35. pool *tunny.WorkPool
  36. }
  37. const (
  38. UAST_EXTRACTION_SKIPPED = -(1 << 31)
  39. ConfigUASTEndpoint = "ConfigUASTEndpoint"
  40. ConfigUASTTimeout = "ConfigUASTTimeout"
  41. ConfigUASTPoolSize = "ConfigUASTPoolSize"
  42. ConfigUASTFailOnErrors = "ConfigUASTFailOnErrors"
  43. ConfigUASTLanguages = "ConfigUASTLanguages"
  44. )
  45. type uastTask struct {
  46. Client *bblfsh.BblfshClient
  47. Lock *sync.RWMutex
  48. Dest map[plumbing.Hash]*uast.Node
  49. File *object.File
  50. Errors *[]error
  51. Status chan int
  52. }
  53. type worker struct {
  54. Client *bblfsh.BblfshClient
  55. Job func(interface{}) interface{}
  56. }
  57. func (w worker) TunnyReady() bool {
  58. return true
  59. }
  60. func (w worker) TunnyJob(data interface{}) interface{} {
  61. task := data.(uastTask)
  62. task.Client = w.Client
  63. return w.Job(task)
  64. }
  65. func (exr *UASTExtractor) Name() string {
  66. return "UAST"
  67. }
  68. func (exr *UASTExtractor) Provides() []string {
  69. arr := [...]string{"uasts"}
  70. return arr[:]
  71. }
  72. func (exr *UASTExtractor) Requires() []string {
  73. arr := [...]string{"changes", "blob_cache"}
  74. return arr[:]
  75. }
  76. func (exr *UASTExtractor) Features() []string {
  77. arr := [...]string{"uast"}
  78. return arr[:]
  79. }
  80. func (exr *UASTExtractor) ListConfigurationOptions() []ConfigurationOption {
  81. options := [...]ConfigurationOption{{
  82. Name: ConfigUASTEndpoint,
  83. Description: "How many days there are in a single band.",
  84. Flag: "bblfsh",
  85. Type: StringConfigurationOption,
  86. Default: "0.0.0.0:9432"}, {
  87. Name: ConfigUASTTimeout,
  88. Description: "Babelfish's server timeout in seconds.",
  89. Flag: "bblfsh-timeout",
  90. Type: IntConfigurationOption,
  91. Default: 20}, {
  92. Name: ConfigUASTPoolSize,
  93. Description: "Number of goroutines to extract UASTs.",
  94. Flag: "bblfsh-pool-size",
  95. Type: IntConfigurationOption,
  96. Default: runtime.NumCPU()}, {
  97. Name: ConfigUASTFailOnErrors,
  98. Description: "Panic if there is a UAST extraction error.",
  99. Flag: "bblfsh-fail-on-error",
  100. Type: BoolConfigurationOption,
  101. Default: false}, {
  102. Name: ConfigUASTLanguages,
  103. Description: "Programming languages from which to extract UASTs. Separated by comma \",\".",
  104. Flag: "languages",
  105. Type: StringConfigurationOption,
  106. Default: "Python,Java"},
  107. }
  108. return options[:]
  109. }
  110. func (exr *UASTExtractor) Configure(facts map[string]interface{}) {
  111. if val, exists := facts[ConfigUASTEndpoint].(string); exists {
  112. exr.Endpoint = val
  113. }
  114. if val, exists := facts[ConfigUASTTimeout].(int); exists {
  115. exr.Context = func() context.Context {
  116. ctx, _ := context.WithTimeout(context.Background(),
  117. time.Duration(val)*time.Second)
  118. return ctx
  119. }
  120. }
  121. if val, exists := facts[ConfigUASTPoolSize].(int); exists {
  122. exr.PoolSize = val
  123. }
  124. if val, exists := facts[ConfigUASTLanguages].(string); exists {
  125. exr.Languages = map[string]bool{}
  126. for _, lang := range strings.Split(val, ",") {
  127. exr.Languages[strings.TrimSpace(lang)] = true
  128. }
  129. }
  130. if val, exists := facts[ConfigUASTFailOnErrors].(bool); exists {
  131. exr.FailOnErrors = val
  132. }
  133. }
  134. func (exr *UASTExtractor) Initialize(repository *git.Repository) {
  135. if exr.Context == nil {
  136. exr.Context = func() context.Context { return context.Background() }
  137. }
  138. poolSize := exr.PoolSize
  139. if poolSize == 0 {
  140. poolSize = runtime.NumCPU()
  141. }
  142. var err error
  143. exr.clients = make([]*bblfsh.BblfshClient, poolSize)
  144. for i := 0; i < poolSize; i++ {
  145. client, err := bblfsh.NewBblfshClient(exr.Endpoint)
  146. if err != nil {
  147. panic(err)
  148. }
  149. exr.clients[i] = client
  150. }
  151. if exr.pool != nil {
  152. exr.pool.Close()
  153. }
  154. workers := make([]tunny.TunnyWorker, poolSize)
  155. for i := 0; i < poolSize; i++ {
  156. workers[i] = worker{Client: exr.clients[i], Job: exr.extractTask}
  157. }
  158. exr.pool, err = tunny.CreateCustomPool(workers).Open()
  159. if err != nil {
  160. panic(err)
  161. }
  162. exr.ProcessedFiles = map[string]int{}
  163. if exr.Languages == nil {
  164. exr.Languages = map[string]bool{}
  165. }
  166. }
  167. func (exr *UASTExtractor) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  168. cache := deps["blob_cache"].(map[plumbing.Hash]*object.Blob)
  169. treeDiffs := deps["changes"].(object.Changes)
  170. uasts := map[plumbing.Hash]*uast.Node{}
  171. lock := sync.RWMutex{}
  172. errs := make([]error, 0)
  173. status := make(chan int)
  174. pending := 0
  175. submit := func(change *object.Change) {
  176. {
  177. reader, err := cache[change.To.TreeEntry.Hash].Reader()
  178. if err != nil {
  179. errs = append(errs, err)
  180. return
  181. }
  182. defer ioutil.CheckClose(reader, &err)
  183. buf := new(bytes.Buffer)
  184. if _, err := buf.ReadFrom(reader); err != nil {
  185. errs = append(errs, err)
  186. return
  187. }
  188. lang, _ := enry.GetLanguageByContent(change.To.Name, buf.Bytes())
  189. if _, exists := exr.Languages[lang]; !exists {
  190. exr.ProcessedFiles[change.To.Name] = UAST_EXTRACTION_SKIPPED
  191. return
  192. }
  193. exr.ProcessedFiles[change.To.Name]++
  194. }
  195. pending++
  196. exr.pool.SendWorkAsync(uastTask{
  197. Lock: &lock,
  198. Dest: uasts,
  199. File: &object.File{Name: change.To.Name, Blob: *cache[change.To.TreeEntry.Hash]},
  200. Errors: &errs, Status: status}, nil)
  201. }
  202. for _, change := range treeDiffs {
  203. action, err := change.Action()
  204. if err != nil {
  205. return nil, err
  206. }
  207. switch action {
  208. case merkletrie.Insert:
  209. submit(change)
  210. case merkletrie.Delete:
  211. continue
  212. case merkletrie.Modify:
  213. submit(change)
  214. }
  215. }
  216. for i := 0; i < pending; i++ {
  217. _ = <-status
  218. }
  219. if len(errs) > 0 {
  220. msgs := make([]string, len(errs))
  221. for i, err := range errs {
  222. msgs[i] = err.Error()
  223. }
  224. joined := strings.Join(msgs, "\n")
  225. if exr.FailOnErrors {
  226. return nil, errors.New(joined)
  227. } else {
  228. fmt.Fprintln(os.Stderr, joined)
  229. }
  230. }
  231. return map[string]interface{}{"uasts": uasts}, nil
  232. }
  233. func (exr *UASTExtractor) extractUAST(
  234. client *bblfsh.BblfshClient, file *object.File) (*uast.Node, error) {
  235. request := client.NewParseRequest()
  236. contents, err := file.Contents()
  237. if err != nil {
  238. return nil, err
  239. }
  240. request.Content(contents)
  241. request.Filename(file.Name)
  242. response, err := request.DoWithContext(exr.Context())
  243. if err != nil {
  244. if strings.Contains("missing driver", err.Error()) {
  245. return nil, nil
  246. }
  247. return nil, err
  248. }
  249. if response.Status != protocol.Ok {
  250. return nil, errors.New(strings.Join(response.Errors, "\n"))
  251. }
  252. if err != nil {
  253. return nil, err
  254. }
  255. return response.UAST, nil
  256. }
  257. func (exr *UASTExtractor) extractTask(data interface{}) interface{} {
  258. task := data.(uastTask)
  259. defer func() { task.Status <- 0 }()
  260. node, err := exr.extractUAST(task.Client, task.File)
  261. task.Lock.Lock()
  262. defer task.Lock.Unlock()
  263. if err != nil {
  264. *task.Errors = append(*task.Errors, errors.New(task.File.Name+": "+err.Error()))
  265. return nil
  266. }
  267. task.Dest[task.File.Hash] = node
  268. return nil
  269. }
  270. type UASTChange struct {
  271. Before *uast.Node
  272. After *uast.Node
  273. Change *object.Change
  274. }
  275. type UASTChanges struct {
  276. cache map[plumbing.Hash]*uast.Node
  277. }
  278. func (uc *UASTChanges) Name() string {
  279. return "UASTChanges"
  280. }
  281. func (uc *UASTChanges) Provides() []string {
  282. arr := [...]string{"changed_uasts"}
  283. return arr[:]
  284. }
  285. func (uc *UASTChanges) Requires() []string {
  286. arr := [...]string{"uasts", "changes"}
  287. return arr[:]
  288. }
  289. func (uc *UASTChanges) Features() []string {
  290. arr := [...]string{"uast"}
  291. return arr[:]
  292. }
  293. func (uc *UASTChanges) ListConfigurationOptions() []ConfigurationOption {
  294. return []ConfigurationOption{}
  295. }
  296. func (uc *UASTChanges) Configure(facts map[string]interface{}) {}
  297. func (uc *UASTChanges) Initialize(repository *git.Repository) {
  298. uc.cache = map[plumbing.Hash]*uast.Node{}
  299. }
  300. func (uc *UASTChanges) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  301. uasts := deps["uasts"].(map[plumbing.Hash]*uast.Node)
  302. treeDiffs := deps["changes"].(object.Changes)
  303. commit := make([]UASTChange, 0, len(treeDiffs))
  304. for _, change := range treeDiffs {
  305. action, err := change.Action()
  306. if err != nil {
  307. return nil, err
  308. }
  309. switch action {
  310. case merkletrie.Insert:
  311. hashTo := change.To.TreeEntry.Hash
  312. uastTo := uasts[hashTo]
  313. commit = append(commit, UASTChange{Before: nil, After: uastTo, Change: change})
  314. uc.cache[hashTo] = uastTo
  315. case merkletrie.Delete:
  316. hashFrom := change.From.TreeEntry.Hash
  317. commit = append(commit, UASTChange{Before: uc.cache[hashFrom], After: nil, Change: change})
  318. delete(uc.cache, hashFrom)
  319. case merkletrie.Modify:
  320. hashFrom := change.From.TreeEntry.Hash
  321. hashTo := change.To.TreeEntry.Hash
  322. uastTo := uasts[hashTo]
  323. commit = append(commit, UASTChange{Before: uc.cache[hashFrom], After: uastTo, Change: change})
  324. delete(uc.cache, hashFrom)
  325. uc.cache[hashTo] = uastTo
  326. }
  327. }
  328. return map[string]interface{}{"changed_uasts": commit}, nil
  329. }
  330. type UASTChangesSaver struct {
  331. // OutputPath points to the target directory with UASTs
  332. OutputPath string
  333. repository *git.Repository
  334. result [][]UASTChange
  335. }
  336. const (
  337. ConfigUASTChangesSaverOutputPath = "UASTChangesSaver.OutputPath"
  338. )
  339. func (saver *UASTChangesSaver) Name() string {
  340. return "UASTChangesSaver"
  341. }
  342. func (saver *UASTChangesSaver) Provides() []string {
  343. return []string{}
  344. }
  345. func (saver *UASTChangesSaver) Requires() []string {
  346. arr := [...]string{"changed_uasts"}
  347. return arr[:]
  348. }
  349. func (saver *UASTChangesSaver) Features() []string {
  350. arr := [...]string{"uast"}
  351. return arr[:]
  352. }
  353. func (saver *UASTChangesSaver) ListConfigurationOptions() []ConfigurationOption {
  354. options := [...]ConfigurationOption{{
  355. Name: ConfigUASTChangesSaverOutputPath,
  356. Description: "The target directory where to store the changed UAST files.",
  357. Flag: "changed-uast-dir",
  358. Type: StringConfigurationOption,
  359. Default: "."},
  360. }
  361. return options[:]
  362. }
  363. func (saver *UASTChangesSaver) Flag() string {
  364. return "dump-uast-changes"
  365. }
  366. func (saver *UASTChangesSaver) Configure(facts map[string]interface{}) {}
  367. func (saver *UASTChangesSaver) Initialize(repository *git.Repository) {
  368. saver.repository = repository
  369. saver.result = [][]UASTChange{}
  370. }
  371. func (saver *UASTChangesSaver) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  372. changes := deps["changed_uasts"].([]UASTChange)
  373. saver.result = append(saver.result, changes)
  374. return nil, nil
  375. }
  376. func (saver *UASTChangesSaver) Finalize() interface{} {
  377. return saver.result
  378. }
  379. func (saver *UASTChangesSaver) Serialize(result interface{}, binary bool, writer io.Writer) error {
  380. saverResult := result.([][]UASTChange)
  381. fileNames := saver.dumpFiles(saverResult)
  382. if binary {
  383. return saver.serializeBinary(fileNames, writer)
  384. }
  385. saver.serializeText(fileNames, writer)
  386. return nil
  387. }
  388. func (saver *UASTChangesSaver) dumpFiles(result [][]UASTChange) []*pb.UASTChange {
  389. fileNames := []*pb.UASTChange{}
  390. for i, changes := range result {
  391. for j, change := range changes {
  392. if change.Before == nil || change.After == nil {
  393. continue
  394. }
  395. record := &pb.UASTChange{FileName: change.Change.To.Name}
  396. bs, _ := change.Before.Marshal()
  397. record.UastBefore = fmt.Sprintf(
  398. "%d_%d_before_%s.pb", i, j, change.Change.From.TreeEntry.Hash.String())
  399. goioutil.WriteFile(record.UastBefore, bs, 0666)
  400. blob, _ := saver.repository.BlobObject(change.Change.From.TreeEntry.Hash)
  401. s, _ := (&object.File{Blob: *blob}).Contents()
  402. record.SrcBefore = fmt.Sprintf(
  403. "%d_%d_before_%s.src", i, j, change.Change.From.TreeEntry.Hash.String())
  404. goioutil.WriteFile(record.SrcBefore, []byte(s), 0666)
  405. bs, _ = change.After.Marshal()
  406. record.UastAfter = fmt.Sprintf(
  407. "%d_%d_after_%s.pb", i, j, change.Change.To.TreeEntry.Hash.String())
  408. goioutil.WriteFile(record.UastAfter, bs, 0666)
  409. blob, _ = saver.repository.BlobObject(change.Change.To.TreeEntry.Hash)
  410. s, _ = (&object.File{Blob: *blob}).Contents()
  411. record.SrcAfter = fmt.Sprintf(
  412. "%d_%d_after_%s.src", i, j, change.Change.To.TreeEntry.Hash.String())
  413. goioutil.WriteFile(record.SrcAfter, []byte(s), 0666)
  414. fileNames = append(fileNames, record)
  415. }
  416. }
  417. return fileNames
  418. }
  419. func (saver *UASTChangesSaver) serializeText(result []*pb.UASTChange, writer io.Writer) {
  420. for _, sc := range result {
  421. kv := [...]string{
  422. "file: " + sc.FileName,
  423. "src0: " + sc.SrcBefore, "src1: " + sc.SrcAfter,
  424. "uast0: " + sc.UastBefore, "uast1: " + sc.UastAfter,
  425. }
  426. fmt.Fprintf(writer, " - {%s}\n", strings.Join(kv[:], ", "))
  427. }
  428. }
  429. func (saver *UASTChangesSaver) serializeBinary(result []*pb.UASTChange, writer io.Writer) error {
  430. message := pb.UASTChangesSaverResults{Changes: result}
  431. serialized, err := proto.Marshal(&message)
  432. if err != nil {
  433. return err
  434. }
  435. writer.Write(serialized)
  436. return nil
  437. }
  438. func init() {
  439. Registry.Register(&UASTExtractor{})
  440. Registry.Register(&UASTChanges{})
  441. Registry.Register(&UASTChangesSaver{})
  442. }