pipeline.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. package hercules
  2. import (
  3. "bufio"
  4. "errors"
  5. "flag"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "os"
  10. "reflect"
  11. "strings"
  12. "unsafe"
  13. "gopkg.in/src-d/go-git.v4"
  14. "gopkg.in/src-d/go-git.v4/plumbing"
  15. "gopkg.in/src-d/go-git.v4/plumbing/object"
  16. "gopkg.in/src-d/hercules.v3/toposort"
  17. "sort"
  18. )
  19. type ConfigurationOptionType int
  20. const (
  21. // Boolean value type.
  22. BoolConfigurationOption ConfigurationOptionType = iota
  23. // Integer value type.
  24. IntConfigurationOption
  25. // String value type.
  26. StringConfigurationOption
  27. )
  28. // ConfigurationOption allows for the unified, retrospective way to setup PipelineItem-s.
  29. type ConfigurationOption struct {
  30. // Name identifies the configuration option in facts.
  31. Name string
  32. // Description represents the help text about the configuration option.
  33. Description string
  34. // Flag corresponds to the CLI token with "-" prepended.
  35. Flag string
  36. // Type specifies the kind of the configuration option's value.
  37. Type ConfigurationOptionType
  38. // Default is the initial value of the configuration option.
  39. Default interface{}
  40. }
  41. // PipelineItem is the interface for all the units of the Git commit analysis pipeline.
  42. type PipelineItem interface {
  43. // Name returns the name of the analysis.
  44. Name() string
  45. // Provides returns the list of keys of reusable calculated entities.
  46. // Other items may depend on them.
  47. Provides() []string
  48. // Requires returns the list of keys of needed entities which must be supplied in Consume().
  49. Requires() []string
  50. // ListConfigurationOptions returns the list of available options which can be consumed by Configure().
  51. ListConfigurationOptions() []ConfigurationOption
  52. // Configure performs the initial setup of the object by applying parameters from facts.
  53. // It allows to create PipelineItems in a universal way.
  54. Configure(facts map[string]interface{})
  55. // Initialize prepares and resets the item. Consume() requires Initialize()
  56. // to be called at least once beforehand.
  57. Initialize(*git.Repository)
  58. // Consume processes the next commit.
  59. // deps contains the required entities which match Depends(). Besides, it always includes
  60. // "commit" and "index".
  61. // Returns the calculated entities which match Provides().
  62. Consume(deps map[string]interface{}) (map[string]interface{}, error)
  63. }
  64. // FeaturedPipelineItem enables switching the automatic insertion of pipeline items on or off.
  65. type FeaturedPipelineItem interface {
  66. PipelineItem
  67. // Features returns the list of names which enable this item to be automatically inserted
  68. // in Pipeline.DeployItem().
  69. Features() []string
  70. }
  71. // LeafPipelineItem corresponds to the top level pipeline items which produce the end results.
  72. type LeafPipelineItem interface {
  73. PipelineItem
  74. // Flag returns the cmdline name of the item.
  75. Flag() string
  76. // Finalize returns the result of the analysis.
  77. Finalize() interface{}
  78. // Serialize encodes the object returned by Finalize() to Text or Protocol Buffers.
  79. Serialize(result interface{}, binary bool, writer io.Writer) error
  80. }
  81. // PipelineItemRegistry contains all the known PipelineItem-s.
  82. type PipelineItemRegistry struct {
  83. provided map[string][]reflect.Type
  84. registered map[string]reflect.Type
  85. flags map[string]reflect.Type
  86. }
  87. // Register adds another PipelineItem to the registry.
  88. func (registry *PipelineItemRegistry) Register(example PipelineItem) {
  89. t := reflect.TypeOf(example)
  90. registry.registered[example.Name()] = t
  91. if fpi, ok := interface{}(example).(LeafPipelineItem); ok {
  92. registry.flags[fpi.Flag()] = t
  93. }
  94. for _, dep := range example.Provides() {
  95. ts := registry.provided[dep]
  96. if ts == nil {
  97. ts = []reflect.Type{}
  98. }
  99. ts = append(ts, t)
  100. registry.provided[dep] = ts
  101. }
  102. }
  103. func (registry *PipelineItemRegistry) Summon(providesOrName string) []PipelineItem {
  104. if registry.provided == nil {
  105. return []PipelineItem{}
  106. }
  107. ts := registry.provided[providesOrName]
  108. items := []PipelineItem{}
  109. for _, t := range ts {
  110. items = append(items, reflect.New(t.Elem()).Interface().(PipelineItem))
  111. }
  112. if t, exists := registry.registered[providesOrName]; exists {
  113. items = append(items, reflect.New(t.Elem()).Interface().(PipelineItem))
  114. }
  115. return items
  116. }
  117. type arrayFeatureFlags struct {
  118. // Flags containts the features activated through the command line.
  119. Flags []string
  120. // Choices contains all registered features.
  121. Choices map[string]bool
  122. }
  123. func (acf *arrayFeatureFlags) String() string {
  124. return strings.Join([]string(acf.Flags), ", ")
  125. }
  126. func (acf *arrayFeatureFlags) Set(value string) error {
  127. if _, exists := acf.Choices[value]; !exists {
  128. return errors.New(fmt.Sprintf("Feature \"%s\" is not registered.", value))
  129. }
  130. acf.Flags = append(acf.Flags, value)
  131. return nil
  132. }
  133. var featureFlags = arrayFeatureFlags{Flags: []string{}, Choices: map[string]bool{}}
  134. // AddFlags inserts the cmdline options from PipelineItem.ListConfigurationOptions(),
  135. // FeaturedPipelineItem().Features() and LeafPipelineItem.Flag() into the global "flag" parser
  136. // built into the Go runtime.
  137. // Returns the "facts" which can be fed into PipelineItem.Configure() and the dictionary of
  138. // runnable analysis (LeafPipelineItem) choices. E.g. if "BurndownAnalysis" was activated
  139. // through "-burndown" cmdline argument, this mapping would contain ["BurndownAnalysis"] = *true.
  140. func (registry *PipelineItemRegistry) AddFlags() (map[string]interface{}, map[string]*bool) {
  141. flags := map[string]interface{}{}
  142. deployed := map[string]*bool{}
  143. for name, it := range registry.registered {
  144. formatHelp := func(desc string) string {
  145. return fmt.Sprintf("%s [%s]", desc, name)
  146. }
  147. itemIface := reflect.New(it.Elem()).Interface()
  148. for _, opt := range itemIface.(PipelineItem).ListConfigurationOptions() {
  149. var iface interface{}
  150. switch opt.Type {
  151. case BoolConfigurationOption:
  152. iface = interface{}(true)
  153. ptr := (**bool)(unsafe.Pointer(uintptr(unsafe.Pointer(&iface)) + unsafe.Sizeof(&iface)))
  154. *ptr = flag.Bool(opt.Flag, opt.Default.(bool), formatHelp(opt.Description))
  155. case IntConfigurationOption:
  156. iface = interface{}(0)
  157. ptr := (**int)(unsafe.Pointer(uintptr(unsafe.Pointer(&iface)) + unsafe.Sizeof(&iface)))
  158. *ptr = flag.Int(opt.Flag, opt.Default.(int), formatHelp(opt.Description))
  159. case StringConfigurationOption:
  160. iface = interface{}("")
  161. ptr := (**string)(unsafe.Pointer(uintptr(unsafe.Pointer(&iface)) + unsafe.Sizeof(&iface)))
  162. *ptr = flag.String(opt.Flag, opt.Default.(string), formatHelp(opt.Description))
  163. }
  164. flags[opt.Name] = iface
  165. }
  166. if fpi, ok := itemIface.(FeaturedPipelineItem); ok {
  167. for _, f := range fpi.Features() {
  168. featureFlags.Choices[f] = true
  169. }
  170. }
  171. if fpi, ok := itemIface.(LeafPipelineItem); ok {
  172. deployed[fpi.Name()] = flag.Bool(
  173. fpi.Flag(), false, fmt.Sprintf("Runs %s analysis.", fpi.Name()))
  174. }
  175. }
  176. features := []string{}
  177. for f := range featureFlags.Choices {
  178. features = append(features, f)
  179. }
  180. flag.Var(&featureFlags, "feature",
  181. fmt.Sprintf("Enables specific analysis features, can be specified "+
  182. "multiple times. Available features: [%s].", strings.Join(features, ", ")))
  183. return flags, deployed
  184. }
  185. // Registry contains all known pipeline item types.
  186. var Registry = &PipelineItemRegistry{
  187. provided: map[string][]reflect.Type{},
  188. registered: map[string]reflect.Type{},
  189. flags: map[string]reflect.Type{},
  190. }
  191. type wrappedPipelineItem struct {
  192. Item PipelineItem
  193. Children []wrappedPipelineItem
  194. }
  195. type Pipeline struct {
  196. // OnProgress is the callback which is invoked in Analyse() to output it's
  197. // progress. The first argument is the number of processed commits and the
  198. // second is the total number of commits.
  199. OnProgress func(int, int)
  200. // repository points to the analysed Git repository struct from go-git.
  201. repository *git.Repository
  202. // items are the registered building blocks in the pipeline. The order defines the
  203. // execution sequence.
  204. items []PipelineItem
  205. // the collection of parameters to create items.
  206. facts map[string]interface{}
  207. // Feature flags which enable the corresponding items.
  208. features map[string]bool
  209. }
  210. func NewPipeline(repository *git.Repository) *Pipeline {
  211. return &Pipeline{
  212. repository: repository,
  213. items: []PipelineItem{},
  214. facts: map[string]interface{}{},
  215. features: map[string]bool{},
  216. }
  217. }
  218. func (pipeline *Pipeline) GetFact(name string) interface{} {
  219. return pipeline.facts[name]
  220. }
  221. func (pipeline *Pipeline) SetFact(name string, value interface{}) {
  222. pipeline.facts[name] = value
  223. }
  224. func (pipeline *Pipeline) GetFeature(name string) (bool, bool) {
  225. val, exists := pipeline.features[name]
  226. return val, exists
  227. }
  228. func (pipeline *Pipeline) SetFeature(name string) {
  229. pipeline.features[name] = true
  230. }
  231. func (pipeline *Pipeline) SetFeaturesFromFlags() {
  232. for _, feature := range featureFlags.Flags {
  233. pipeline.SetFeature(feature)
  234. }
  235. }
  236. func (pipeline *Pipeline) DeployItem(item PipelineItem) PipelineItem {
  237. queue := []PipelineItem{}
  238. queue = append(queue, item)
  239. added := map[string]PipelineItem{}
  240. added[item.Name()] = item
  241. pipeline.AddItem(item)
  242. for len(queue) > 0 {
  243. head := queue[0]
  244. queue = queue[1:]
  245. for _, dep := range head.Requires() {
  246. for _, sibling := range Registry.Summon(dep) {
  247. if _, exists := added[sibling.Name()]; !exists {
  248. disabled := false
  249. // If this item supports features, check them against the activated in pipeline.features
  250. if fpi, matches := interface{}(sibling).(FeaturedPipelineItem); matches {
  251. for _, feature := range fpi.Features() {
  252. if !pipeline.features[feature] {
  253. disabled = true
  254. break
  255. }
  256. }
  257. }
  258. if disabled {
  259. continue
  260. }
  261. added[sibling.Name()] = sibling
  262. queue = append(queue, sibling)
  263. pipeline.AddItem(sibling)
  264. }
  265. }
  266. }
  267. }
  268. return item
  269. }
  270. func (pipeline *Pipeline) AddItem(item PipelineItem) PipelineItem {
  271. pipeline.items = append(pipeline.items, item)
  272. return item
  273. }
  274. func (pipeline *Pipeline) RemoveItem(item PipelineItem) {
  275. for i, reg := range pipeline.items {
  276. if reg == item {
  277. pipeline.items = append(pipeline.items[:i], pipeline.items[i+1:]...)
  278. return
  279. }
  280. }
  281. }
  282. func (pipeline *Pipeline) Len() int {
  283. return len(pipeline.items)
  284. }
  285. // Commits returns the critical path in the repository's history. It starts
  286. // from HEAD and traces commits backwards till the root. When it encounters
  287. // a merge (more than one parent), it always chooses the first parent.
  288. func (pipeline *Pipeline) Commits() []*object.Commit {
  289. result := []*object.Commit{}
  290. repository := pipeline.repository
  291. head, err := repository.Head()
  292. if err != nil {
  293. panic(err)
  294. }
  295. commit, err := repository.CommitObject(head.Hash())
  296. if err != nil {
  297. panic(err)
  298. }
  299. // the first parent matches the head
  300. for ; err != io.EOF; commit, err = commit.Parents().Next() {
  301. if err != nil {
  302. panic(err)
  303. }
  304. result = append(result, commit)
  305. }
  306. // reverse the order
  307. for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 {
  308. result[i], result[j] = result[j], result[i]
  309. }
  310. return result
  311. }
  312. type sortablePipelineItems []PipelineItem
  313. func (items sortablePipelineItems) Len() int {
  314. return len(items)
  315. }
  316. func (items sortablePipelineItems) Less(i, j int) bool {
  317. return items[i].Name() < items[j].Name()
  318. }
  319. func (items sortablePipelineItems) Swap(i, j int) {
  320. items[i], items[j] = items[j], items[i]
  321. }
  322. func (pipeline *Pipeline) resolve(dumpPath string) {
  323. graph := toposort.NewGraph()
  324. sort.Sort(sortablePipelineItems(pipeline.items))
  325. name2item := map[string]PipelineItem{}
  326. ambiguousMap := map[string][]string{}
  327. nameUsages := map[string]int{}
  328. for _, item := range pipeline.items {
  329. nameUsages[item.Name()]++
  330. }
  331. counters := map[string]int{}
  332. for _, item := range pipeline.items {
  333. name := item.Name()
  334. if nameUsages[name] > 1 {
  335. index := counters[item.Name()] + 1
  336. counters[item.Name()] = index
  337. name = fmt.Sprintf("%s_%d", item.Name(), index)
  338. }
  339. graph.AddNode(name)
  340. name2item[name] = item
  341. for _, key := range item.Provides() {
  342. key = "[" + key + "]"
  343. graph.AddNode(key)
  344. if graph.AddEdge(name, key) > 1 {
  345. if ambiguousMap[key] != nil {
  346. panic("Failed to resolve pipeline dependencies.")
  347. }
  348. ambiguousMap[key] = graph.FindParents(key)
  349. }
  350. }
  351. }
  352. counters = map[string]int{}
  353. for _, item := range pipeline.items {
  354. name := item.Name()
  355. if nameUsages[name] > 1 {
  356. index := counters[item.Name()] + 1
  357. counters[item.Name()] = index
  358. name = fmt.Sprintf("%s_%d", item.Name(), index)
  359. }
  360. for _, key := range item.Requires() {
  361. key = "[" + key + "]"
  362. if graph.AddEdge(key, name) == 0 {
  363. panic(fmt.Sprintf("Unsatisfied dependency: %s -> %s", key, item.Name()))
  364. }
  365. }
  366. }
  367. if len(ambiguousMap) > 0 {
  368. ambiguous := []string{}
  369. for key := range ambiguousMap {
  370. ambiguous = append(ambiguous, key)
  371. }
  372. bfsorder := graph.BreadthSort()
  373. bfsindex := map[string]int{}
  374. for i, s := range bfsorder {
  375. bfsindex[s] = i
  376. }
  377. for len(ambiguous) > 0 {
  378. key := ambiguous[0]
  379. ambiguous = ambiguous[1:]
  380. pair := ambiguousMap[key]
  381. inheritor := pair[1]
  382. if bfsindex[pair[1]] < bfsindex[pair[0]] {
  383. inheritor = pair[0]
  384. }
  385. removed := graph.RemoveEdge(key, inheritor)
  386. cycle := map[string]bool{}
  387. for _, node := range graph.FindCycle(key) {
  388. cycle[node] = true
  389. }
  390. if len(cycle) == 0 {
  391. cycle[inheritor] = true
  392. }
  393. if removed {
  394. graph.AddEdge(key, inheritor)
  395. }
  396. graph.RemoveEdge(inheritor, key)
  397. graph.ReindexNode(inheritor)
  398. // for all nodes key links to except those in cycle, put the link from inheritor
  399. for _, node := range graph.FindChildren(key) {
  400. if _, exists := cycle[node]; !exists {
  401. graph.AddEdge(inheritor, node)
  402. graph.RemoveEdge(key, node)
  403. }
  404. }
  405. graph.ReindexNode(key)
  406. }
  407. }
  408. var graphCopy *toposort.Graph
  409. if dumpPath != "" {
  410. graphCopy = graph.Copy()
  411. }
  412. strplan, ok := graph.Toposort()
  413. if !ok {
  414. panic("Failed to resolve pipeline dependencies.")
  415. }
  416. pipeline.items = make([]PipelineItem, 0, len(pipeline.items))
  417. for _, key := range strplan {
  418. if item, ok := name2item[key]; ok {
  419. pipeline.items = append(pipeline.items, item)
  420. }
  421. }
  422. if dumpPath != "" {
  423. ioutil.WriteFile(dumpPath, []byte(graphCopy.Serialize(strplan)), 0666)
  424. }
  425. }
  426. func (pipeline *Pipeline) Initialize(facts map[string]interface{}) {
  427. if facts == nil {
  428. facts = map[string]interface{}{}
  429. }
  430. dumpPath, _ := facts["Pipeline.DumpPath"].(string)
  431. pipeline.resolve(dumpPath)
  432. if dryRun, _ := facts["Pipeline.DryRun"].(bool); dryRun {
  433. return
  434. }
  435. for _, item := range pipeline.items {
  436. item.Configure(facts)
  437. }
  438. for _, item := range pipeline.items {
  439. item.Initialize(pipeline.repository)
  440. }
  441. }
  442. // Run executes the pipeline.
  443. //
  444. // commits is a slice with the sequential commit history. It shall start from
  445. // the root (ascending order).
  446. func (pipeline *Pipeline) Run(commits []*object.Commit) (map[PipelineItem]interface{}, error) {
  447. onProgress := pipeline.OnProgress
  448. if onProgress == nil {
  449. onProgress = func(int, int) {}
  450. }
  451. for index, commit := range commits {
  452. onProgress(index, len(commits))
  453. state := map[string]interface{}{"commit": commit, "index": index}
  454. for _, item := range pipeline.items {
  455. update, err := item.Consume(state)
  456. if err != nil {
  457. fmt.Fprintf(os.Stderr, "%s failed on commit #%d %s\n",
  458. item.Name(), index, commit.Hash.String())
  459. return nil, err
  460. }
  461. for _, key := range item.Provides() {
  462. val, ok := update[key]
  463. if !ok {
  464. panic(fmt.Sprintf("%s: Consume() did not return %s", item.Name(), key))
  465. }
  466. state[key] = val
  467. }
  468. }
  469. }
  470. onProgress(len(commits), len(commits))
  471. result := map[PipelineItem]interface{}{}
  472. for _, item := range pipeline.items {
  473. if fpi, ok := interface{}(item).(LeafPipelineItem); ok {
  474. result[item] = fpi.Finalize()
  475. }
  476. }
  477. return result, nil
  478. }
  479. func LoadCommitsFromFile(path string, repository *git.Repository) ([]*object.Commit, error) {
  480. var file io.ReadCloser
  481. if path != "-" {
  482. var err error
  483. file, err = os.Open(path)
  484. if err != nil {
  485. return nil, err
  486. }
  487. defer file.Close()
  488. } else {
  489. file = os.Stdin
  490. }
  491. scanner := bufio.NewScanner(file)
  492. commits := []*object.Commit{}
  493. for scanner.Scan() {
  494. hash := plumbing.NewHash(scanner.Text())
  495. if len(hash) != 20 {
  496. return nil, errors.New("invalid commit hash " + scanner.Text())
  497. }
  498. commit, err := repository.CommitObject(hash)
  499. if err != nil {
  500. return nil, err
  501. }
  502. commits = append(commits, commit)
  503. }
  504. return commits, nil
  505. }