uast.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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. "gopkg.in/bblfsh/client-go.v1"
  15. "gopkg.in/bblfsh/sdk.v1/protocol"
  16. "gopkg.in/bblfsh/sdk.v1/uast"
  17. "gopkg.in/src-d/enry.v1"
  18. "gopkg.in/src-d/go-git.v4"
  19. "gopkg.in/src-d/go-git.v4/plumbing"
  20. "gopkg.in/src-d/go-git.v4/plumbing/object"
  21. "gopkg.in/src-d/go-git.v4/utils/ioutil"
  22. "gopkg.in/src-d/go-git.v4/utils/merkletrie"
  23. "gopkg.in/src-d/hercules.v3/pb"
  24. "github.com/jeffail/tunny"
  25. "github.com/gogo/protobuf/proto"
  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 = "UAST.Endpoint"
  40. ConfigUASTTimeout = "UAST.Timeout"
  41. ConfigUASTPoolSize = "UAST.PoolSize"
  42. ConfigUASTFailOnErrors = "UAST.FailOnErrors"
  43. ConfigUASTLanguages = "UAST.Languages"
  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["UAST.Timeout"].(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[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. }
  164. func (exr *UASTExtractor) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  165. cache := deps["blob_cache"].(map[plumbing.Hash]*object.Blob)
  166. treeDiffs := deps["changes"].(object.Changes)
  167. uasts := map[plumbing.Hash]*uast.Node{}
  168. lock := sync.RWMutex{}
  169. errs := make([]error, 0)
  170. status := make(chan int)
  171. pending := 0
  172. submit := func(change *object.Change) {
  173. {
  174. reader, err := cache[change.To.TreeEntry.Hash].Reader()
  175. if err != nil {
  176. errs = append(errs, err)
  177. return
  178. }
  179. defer ioutil.CheckClose(reader, &err)
  180. buf := new(bytes.Buffer)
  181. if _, err := buf.ReadFrom(reader); err != nil {
  182. errs = append(errs, err)
  183. return
  184. }
  185. lang, _ := enry.GetLanguageByContent(change.To.Name, buf.Bytes())
  186. if _, exists := exr.Languages[lang]; !exists {
  187. exr.ProcessedFiles[change.To.Name] = UAST_EXTRACTION_SKIPPED
  188. return
  189. }
  190. exr.ProcessedFiles[change.To.Name]++
  191. }
  192. pending++
  193. exr.pool.SendWorkAsync(uastTask{
  194. Lock: &lock,
  195. Dest: uasts,
  196. File: &object.File{Name: change.To.Name, Blob: *cache[change.To.TreeEntry.Hash]},
  197. Errors: &errs, Status: status}, nil)
  198. }
  199. for _, change := range treeDiffs {
  200. action, err := change.Action()
  201. if err != nil {
  202. return nil, err
  203. }
  204. switch action {
  205. case merkletrie.Insert:
  206. submit(change)
  207. case merkletrie.Delete:
  208. continue
  209. case merkletrie.Modify:
  210. submit(change)
  211. }
  212. }
  213. for i := 0; i < pending; i++ {
  214. _ = <-status
  215. }
  216. if len(errs) > 0 {
  217. msgs := make([]string, len(errs))
  218. for i, err := range errs {
  219. msgs[i] = err.Error()
  220. }
  221. joined := strings.Join(msgs, "\n")
  222. if exr.FailOnErrors {
  223. return nil, errors.New(joined)
  224. } else {
  225. fmt.Fprintln(os.Stderr, joined)
  226. }
  227. }
  228. return map[string]interface{}{"uasts": uasts}, nil
  229. }
  230. func (exr *UASTExtractor) extractUAST(
  231. client *bblfsh.BblfshClient, file *object.File) (*uast.Node, error) {
  232. request := client.NewParseRequest()
  233. contents, err := file.Contents()
  234. if err != nil {
  235. return nil, err
  236. }
  237. request.Content(contents)
  238. request.Filename(file.Name)
  239. response, err := request.DoWithContext(exr.Context())
  240. if err != nil {
  241. if strings.Contains("missing driver", err.Error()) {
  242. return nil, nil
  243. }
  244. return nil, err
  245. }
  246. if response.Status != protocol.Ok {
  247. return nil, errors.New(strings.Join(response.Errors, "\n"))
  248. }
  249. if err != nil {
  250. return nil, err
  251. }
  252. return response.UAST, nil
  253. }
  254. func (exr *UASTExtractor) extractTask(data interface{}) interface{} {
  255. task := data.(uastTask)
  256. defer func() { task.Status <- 0 }()
  257. node, err := exr.extractUAST(task.Client, task.File)
  258. task.Lock.Lock()
  259. defer task.Lock.Unlock()
  260. if err != nil {
  261. *task.Errors = append(*task.Errors, errors.New(task.File.Name+": "+err.Error()))
  262. return nil
  263. }
  264. task.Dest[task.File.Hash] = node
  265. return nil
  266. }
  267. type UASTChange struct {
  268. Before *uast.Node
  269. After *uast.Node
  270. Change *object.Change
  271. }
  272. type UASTChanges struct {
  273. cache map[plumbing.Hash]*uast.Node
  274. }
  275. func (uc *UASTChanges) Name() string {
  276. return "UASTChanges"
  277. }
  278. func (uc *UASTChanges) Provides() []string {
  279. arr := [...]string{"changed_uasts"}
  280. return arr[:]
  281. }
  282. func (uc *UASTChanges) Requires() []string {
  283. arr := [...]string{"uasts", "changes"}
  284. return arr[:]
  285. }
  286. func (uc *UASTChanges) Features() []string {
  287. arr := [...]string{"uast"}
  288. return arr[:]
  289. }
  290. func (uc *UASTChanges) ListConfigurationOptions() []ConfigurationOption {
  291. return []ConfigurationOption{}
  292. }
  293. func (uc *UASTChanges) Configure(facts map[string]interface{}) {}
  294. func (uc *UASTChanges) Initialize(repository *git.Repository) {
  295. uc.cache = map[plumbing.Hash]*uast.Node{}
  296. }
  297. func (uc *UASTChanges) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  298. uasts := deps["uasts"].(map[plumbing.Hash]*uast.Node)
  299. treeDiffs := deps["changes"].(object.Changes)
  300. commit := make([]UASTChange, 0, len(treeDiffs))
  301. for _, change := range treeDiffs {
  302. action, err := change.Action()
  303. if err != nil {
  304. return nil, err
  305. }
  306. switch action {
  307. case merkletrie.Insert:
  308. hashTo := change.To.TreeEntry.Hash
  309. uastTo := uasts[hashTo]
  310. commit = append(commit, UASTChange{Before: nil, After: uastTo, Change: change})
  311. uc.cache[hashTo] = uastTo
  312. case merkletrie.Delete:
  313. hashFrom := change.From.TreeEntry.Hash
  314. commit = append(commit, UASTChange{Before: uc.cache[hashFrom], After: nil, Change: change})
  315. delete(uc.cache, hashFrom)
  316. case merkletrie.Modify:
  317. hashFrom := change.From.TreeEntry.Hash
  318. hashTo := change.To.TreeEntry.Hash
  319. uastTo := uasts[hashTo]
  320. commit = append(commit, UASTChange{Before: uc.cache[hashFrom], After: uastTo, Change: change})
  321. delete(uc.cache, hashFrom)
  322. uc.cache[hashTo] = uastTo
  323. }
  324. }
  325. return map[string]interface{}{"changed_uasts": commit}, nil
  326. }
  327. type UASTChangesSaver struct {
  328. // OutputPath points to the target directory with UASTs
  329. OutputPath string
  330. repository *git.Repository
  331. result [][]UASTChange
  332. }
  333. const (
  334. ConfigUASTChangesSaverOutputPath = "UASTChangesSaver.OutputPath"
  335. )
  336. func (saver *UASTChangesSaver) Name() string {
  337. return "UASTChangesSaver"
  338. }
  339. func (saver *UASTChangesSaver) Provides() []string {
  340. return []string{}
  341. }
  342. func (saver *UASTChangesSaver) Requires() []string {
  343. arr := [...]string{"changed_uasts"}
  344. return arr[:]
  345. }
  346. func (saver *UASTChangesSaver) Features() []string {
  347. arr := [...]string{"uast"}
  348. return arr[:]
  349. }
  350. func (saver *UASTChangesSaver) ListConfigurationOptions() []ConfigurationOption {
  351. options := [...]ConfigurationOption{{
  352. Name: ConfigUASTChangesSaverOutputPath,
  353. Description: "The target directory where to store the changed UAST files.",
  354. Flag: "changed-uast-dir",
  355. Type: StringConfigurationOption,
  356. Default: "."},
  357. }
  358. return options[:]
  359. }
  360. func (saver *UASTChangesSaver) Flag() string {
  361. return "dump-uast-changes"
  362. }
  363. func (saver *UASTChangesSaver) Configure(facts map[string]interface{}) {}
  364. func (saver *UASTChangesSaver) Initialize(repository *git.Repository) {
  365. saver.repository = repository
  366. saver.result = [][]UASTChange{}
  367. }
  368. func (saver *UASTChangesSaver) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  369. changes := deps["changed_uasts"].([]UASTChange)
  370. saver.result = append(saver.result, changes)
  371. return nil, nil
  372. }
  373. func (saver *UASTChangesSaver) Finalize() interface{} {
  374. return saver.result
  375. }
  376. func (saver *UASTChangesSaver) Serialize(result interface{}, binary bool, writer io.Writer) error {
  377. saverResult := result.([][]UASTChange)
  378. fileNames := saver.dumpFiles(saverResult)
  379. if binary {
  380. return saver.serializeBinary(fileNames, writer)
  381. }
  382. saver.serializeText(fileNames, writer)
  383. return nil
  384. }
  385. func (saver *UASTChangesSaver) dumpFiles(result [][]UASTChange) []*pb.UASTChange {
  386. fileNames := []*pb.UASTChange{}
  387. for i, changes := range result {
  388. for j, change := range changes {
  389. if change.Before == nil || change.After == nil {
  390. continue
  391. }
  392. record := &pb.UASTChange{FileName: change.Change.To.Name}
  393. bs, _ := change.Before.Marshal()
  394. record.UastBefore = fmt.Sprintf(
  395. "%d_%d_before_%s.pb", i, j, change.Change.From.TreeEntry.Hash.String())
  396. goioutil.WriteFile(record.UastBefore, bs, 0666)
  397. blob, _ := saver.repository.BlobObject(change.Change.From.TreeEntry.Hash)
  398. s, _ := (&object.File{Blob: *blob}).Contents()
  399. record.SrcBefore = fmt.Sprintf(
  400. "%d_%d_before_%s.src", i, j, change.Change.From.TreeEntry.Hash.String())
  401. goioutil.WriteFile(record.SrcBefore, []byte(s), 0666)
  402. bs, _ = change.After.Marshal()
  403. record.UastAfter = fmt.Sprintf(
  404. "%d_%d_after_%s.pb", i, j, change.Change.To.TreeEntry.Hash.String())
  405. goioutil.WriteFile(record.UastAfter, bs, 0666)
  406. blob, _ = saver.repository.BlobObject(change.Change.To.TreeEntry.Hash)
  407. s, _ = (&object.File{Blob: *blob}).Contents()
  408. record.SrcAfter = fmt.Sprintf(
  409. "%d_%d_after_%s.src", i, j, change.Change.To.TreeEntry.Hash.String())
  410. goioutil.WriteFile(record.SrcAfter, []byte(s), 0666)
  411. fileNames = append(fileNames, record)
  412. }
  413. }
  414. return fileNames
  415. }
  416. func (saver *UASTChangesSaver) serializeText(result []*pb.UASTChange, writer io.Writer) {
  417. for _, sc := range result {
  418. kv := [...]string{
  419. "file: " + sc.FileName,
  420. "src0: " + sc.SrcBefore, "src1: " + sc.SrcAfter,
  421. "uast0: " + sc.UastBefore, "uast1: " + sc.UastAfter,
  422. }
  423. fmt.Fprintf(writer, " - {%s}\n", strings.Join(kv[:], ", "))
  424. }
  425. }
  426. func (saver *UASTChangesSaver) serializeBinary(result []*pb.UASTChange, writer io.Writer) error {
  427. message := pb.UASTChangesSaverResults{Changes: result}
  428. serialized, err := proto.Marshal(&message)
  429. if err != nil {
  430. return err
  431. }
  432. writer.Write(serialized)
  433. return nil
  434. }
  435. func init() {
  436. Registry.Register(&UASTExtractor{})
  437. Registry.Register(&UASTChanges{})
  438. Registry.Register(&UASTChangesSaver{})
  439. }