pipeline.go 16 KB

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