pipeline.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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. func (registry *PipelineItemRegistry) AddFlags() (map[string]interface{}, map[string]*bool) {
  134. flags := map[string]interface{}{}
  135. deployed := map[string]*bool{}
  136. for name, it := range registry.registered {
  137. formatHelp := func(desc string) string {
  138. return fmt.Sprintf("%s [%s]", desc, name)
  139. }
  140. itemIface := reflect.New(it.Elem()).Interface()
  141. for _, opt := range itemIface.(PipelineItem).ListConfigurationOptions() {
  142. var iface interface{}
  143. switch opt.Type {
  144. case BoolConfigurationOption:
  145. iface = interface{}(true)
  146. ptr := (**bool)(unsafe.Pointer(uintptr(unsafe.Pointer(&iface)) + unsafe.Sizeof(&iface)))
  147. *ptr = flag.Bool(opt.Flag, opt.Default.(bool), formatHelp(opt.Description))
  148. case IntConfigurationOption:
  149. iface = interface{}(0)
  150. ptr := (**int)(unsafe.Pointer(uintptr(unsafe.Pointer(&iface)) + unsafe.Sizeof(&iface)))
  151. *ptr = flag.Int(opt.Flag, opt.Default.(int), formatHelp(opt.Description))
  152. case StringConfigurationOption:
  153. iface = interface{}("")
  154. ptr := (**string)(unsafe.Pointer(uintptr(unsafe.Pointer(&iface)) + unsafe.Sizeof(&iface)))
  155. *ptr = flag.String(opt.Flag, opt.Default.(string), formatHelp(opt.Description))
  156. }
  157. flags[opt.Name] = iface
  158. }
  159. if fpi, ok := itemIface.(FeaturedPipelineItem); ok {
  160. for _, f := range fpi.Features() {
  161. featureFlags.Choices[f] = true
  162. }
  163. }
  164. if fpi, ok := itemIface.(LeafPipelineItem); ok {
  165. deployed[fpi.Name()] = flag.Bool(
  166. fpi.Flag(), false, fmt.Sprintf("Runs %s analysis.", fpi.Name()))
  167. }
  168. }
  169. features := []string{}
  170. for f := range featureFlags.Choices {
  171. features = append(features, f)
  172. }
  173. flag.Var(&featureFlags, "feature",
  174. fmt.Sprintf("Enables specific analysis features, can be specified "+
  175. "multiple times. Available features: [%s].", strings.Join(features, ", ")))
  176. return flags, deployed
  177. }
  178. // Registry contains all known pipeline item types.
  179. var Registry = &PipelineItemRegistry{
  180. provided: map[string][]reflect.Type{},
  181. registered: map[string]reflect.Type{},
  182. flags: map[string]reflect.Type{},
  183. }
  184. type wrappedPipelineItem struct {
  185. Item PipelineItem
  186. Children []wrappedPipelineItem
  187. }
  188. type Pipeline struct {
  189. // OnProgress is the callback which is invoked in Analyse() to output it's
  190. // progress. The first argument is the number of processed commits and the
  191. // second is the total number of commits.
  192. OnProgress func(int, int)
  193. // repository points to the analysed Git repository struct from go-git.
  194. repository *git.Repository
  195. // items are the registered building blocks in the pipeline. The order defines the
  196. // execution sequence.
  197. items []PipelineItem
  198. // the collection of parameters to create items.
  199. facts map[string]interface{}
  200. // Feature flags which enable the corresponding items.
  201. features map[string]bool
  202. }
  203. func NewPipeline(repository *git.Repository) *Pipeline {
  204. return &Pipeline{
  205. repository: repository,
  206. items: []PipelineItem{},
  207. facts: map[string]interface{}{},
  208. features: map[string]bool{},
  209. }
  210. }
  211. func (pipeline *Pipeline) GetFact(name string) interface{} {
  212. return pipeline.facts[name]
  213. }
  214. func (pipeline *Pipeline) SetFact(name string, value interface{}) {
  215. pipeline.facts[name] = value
  216. }
  217. func (pipeline *Pipeline) GetFeature(name string) bool {
  218. return pipeline.features[name]
  219. }
  220. func (pipeline *Pipeline) SetFeature(name string) {
  221. pipeline.features[name] = true
  222. }
  223. func (pipeline *Pipeline) SetFeaturesFromFlags() {
  224. for _, feature := range featureFlags.Flags {
  225. pipeline.SetFeature(feature)
  226. }
  227. }
  228. func (pipeline *Pipeline) DeployItem(item PipelineItem) PipelineItem {
  229. queue := []PipelineItem{}
  230. queue = append(queue, item)
  231. added := map[string]PipelineItem{}
  232. added[item.Name()] = item
  233. pipeline.AddItem(item)
  234. for len(queue) > 0 {
  235. head := queue[0]
  236. queue = queue[1:]
  237. for _, dep := range head.Requires() {
  238. for _, sibling := range Registry.Summon(dep) {
  239. if _, exists := added[sibling.Name()]; !exists {
  240. disabled := false
  241. // If this item supports features, check them against the activated in pipeline.features
  242. if fpi, matches := interface{}(sibling).(FeaturedPipelineItem); matches {
  243. for _, feature := range fpi.Features() {
  244. if !pipeline.features[feature] {
  245. disabled = true
  246. break
  247. }
  248. }
  249. }
  250. if disabled {
  251. continue
  252. }
  253. added[sibling.Name()] = sibling
  254. queue = append(queue, sibling)
  255. pipeline.AddItem(sibling)
  256. }
  257. }
  258. }
  259. }
  260. return item
  261. }
  262. func (pipeline *Pipeline) AddItem(item PipelineItem) PipelineItem {
  263. pipeline.items = append(pipeline.items, item)
  264. return item
  265. }
  266. func (pipeline *Pipeline) RemoveItem(item PipelineItem) {
  267. for i, reg := range pipeline.items {
  268. if reg == item {
  269. pipeline.items = append(pipeline.items[:i], pipeline.items[i+1:]...)
  270. return
  271. }
  272. }
  273. }
  274. func (pipeline *Pipeline) Len() int {
  275. return len(pipeline.items)
  276. }
  277. // Commits returns the critical path in the repository's history. It starts
  278. // from HEAD and traces commits backwards till the root. When it encounters
  279. // a merge (more than one parent), it always chooses the first parent.
  280. func (pipeline *Pipeline) Commits() []*object.Commit {
  281. result := []*object.Commit{}
  282. repository := pipeline.repository
  283. head, err := repository.Head()
  284. if err != nil {
  285. panic(err)
  286. }
  287. commit, err := repository.CommitObject(head.Hash())
  288. if err != nil {
  289. panic(err)
  290. }
  291. // the first parent matches the head
  292. for ; err != io.EOF; commit, err = commit.Parents().Next() {
  293. if err != nil {
  294. panic(err)
  295. }
  296. result = append(result, commit)
  297. }
  298. // reverse the order
  299. for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 {
  300. result[i], result[j] = result[j], result[i]
  301. }
  302. return result
  303. }
  304. func (pipeline *Pipeline) resolve(dumpPath string) {
  305. graph := toposort.NewGraph()
  306. name2item := map[string]PipelineItem{}
  307. ambiguousMap := map[string][]string{}
  308. nameUsages := map[string]int{}
  309. for _, item := range pipeline.items {
  310. nameUsages[item.Name()]++
  311. }
  312. counters := map[string]int{}
  313. for _, item := range pipeline.items {
  314. name := item.Name()
  315. if nameUsages[name] > 1 {
  316. index := counters[item.Name()] + 1
  317. counters[item.Name()] = index
  318. name = fmt.Sprintf("%s_%d", item.Name(), index)
  319. }
  320. graph.AddNode(name)
  321. name2item[name] = item
  322. for _, key := range item.Provides() {
  323. key = "[" + key + "]"
  324. graph.AddNode(key)
  325. if graph.AddEdge(name, key) > 1 {
  326. if ambiguousMap[key] != nil {
  327. panic("Failed to resolve pipeline dependencies.")
  328. }
  329. ambiguousMap[key] = graph.FindParents(key)
  330. }
  331. }
  332. }
  333. counters = map[string]int{}
  334. for _, item := range pipeline.items {
  335. name := item.Name()
  336. if nameUsages[name] > 1 {
  337. index := counters[item.Name()] + 1
  338. counters[item.Name()] = index
  339. name = fmt.Sprintf("%s_%d", item.Name(), index)
  340. }
  341. for _, key := range item.Requires() {
  342. key = "[" + key + "]"
  343. if graph.AddEdge(key, name) == 0 {
  344. panic(fmt.Sprintf("Unsatisfied dependency: %s -> %s", key, item.Name()))
  345. }
  346. }
  347. }
  348. if len(ambiguousMap) > 0 {
  349. ambiguous := []string{}
  350. for key := range ambiguousMap {
  351. ambiguous = append(ambiguous, key)
  352. }
  353. bfsorder := graph.BreadthSort()
  354. bfsindex := map[string]int{}
  355. for i, s := range bfsorder {
  356. bfsindex[s] = i
  357. }
  358. for len(ambiguous) > 0 {
  359. key := ambiguous[0]
  360. ambiguous = ambiguous[1:]
  361. pair := ambiguousMap[key]
  362. inheritor := pair[1]
  363. if bfsindex[pair[1]] < bfsindex[pair[0]] {
  364. inheritor = pair[0]
  365. }
  366. removed := graph.RemoveEdge(key, inheritor)
  367. cycle := map[string]bool{}
  368. for _, node := range graph.FindCycle(key) {
  369. cycle[node] = true
  370. }
  371. if len(cycle) == 0 {
  372. cycle[inheritor] = true
  373. }
  374. if removed {
  375. graph.AddEdge(key, inheritor)
  376. }
  377. graph.RemoveEdge(inheritor, key)
  378. graph.ReindexNode(inheritor)
  379. // for all nodes key links to except those in cycle, put the link from inheritor
  380. for _, node := range graph.FindChildren(key) {
  381. if _, exists := cycle[node]; !exists {
  382. graph.AddEdge(inheritor, node)
  383. graph.RemoveEdge(key, node)
  384. }
  385. }
  386. graph.ReindexNode(key)
  387. }
  388. }
  389. var graphCopy *toposort.Graph
  390. if dumpPath != "" {
  391. graphCopy = graph.Copy()
  392. }
  393. strplan, ok := graph.Toposort()
  394. if !ok {
  395. panic("Failed to resolve pipeline dependencies.")
  396. }
  397. pipeline.items = make([]PipelineItem, 0, len(pipeline.items))
  398. for _, key := range strplan {
  399. if item, ok := name2item[key]; ok {
  400. pipeline.items = append(pipeline.items, item)
  401. }
  402. }
  403. if dumpPath != "" {
  404. ioutil.WriteFile(dumpPath, []byte(graphCopy.Serialize(strplan)), 0666)
  405. }
  406. }
  407. func (pipeline *Pipeline) Initialize(facts map[string]interface{}) {
  408. dumpPath, _ := facts["Pipeline.DumpPath"].(string)
  409. pipeline.resolve(dumpPath)
  410. if dryRun, _ := facts["Pipeline.DryRun"].(bool); dryRun {
  411. return
  412. }
  413. for _, item := range pipeline.items {
  414. item.Configure(facts)
  415. }
  416. for _, item := range pipeline.items {
  417. item.Initialize(pipeline.repository)
  418. }
  419. }
  420. // Run executes the pipeline.
  421. //
  422. // commits is a slice with the sequential commit history. It shall start from
  423. // the root (ascending order).
  424. func (pipeline *Pipeline) Run(commits []*object.Commit) (map[PipelineItem]interface{}, error) {
  425. onProgress := pipeline.OnProgress
  426. if onProgress == nil {
  427. onProgress = func(int, int) {}
  428. }
  429. for index, commit := range commits {
  430. onProgress(index, len(commits))
  431. state := map[string]interface{}{"commit": commit, "index": index}
  432. for _, item := range pipeline.items {
  433. update, err := item.Consume(state)
  434. if err != nil {
  435. fmt.Fprintf(os.Stderr, "%s failed on commit #%d %s\n",
  436. item.Name(), index, commit.Hash.String())
  437. return nil, err
  438. }
  439. for _, key := range item.Provides() {
  440. val, ok := update[key]
  441. if !ok {
  442. panic(fmt.Sprintf("%s: Consume() did not return %s", item.Name(), key))
  443. }
  444. state[key] = val
  445. }
  446. }
  447. }
  448. onProgress(len(commits), len(commits))
  449. result := map[PipelineItem]interface{}{}
  450. for _, item := range pipeline.items {
  451. if fpi, ok := interface{}(item).(LeafPipelineItem); ok {
  452. result[item] = fpi.Finalize()
  453. }
  454. }
  455. return result, nil
  456. }
  457. func LoadCommitsFromFile(path string, repository *git.Repository) ([]*object.Commit, error) {
  458. var file io.ReadCloser
  459. if path != "-" {
  460. var err error
  461. file, err = os.Open(path)
  462. if err != nil {
  463. return nil, err
  464. }
  465. defer file.Close()
  466. } else {
  467. file = os.Stdin
  468. }
  469. scanner := bufio.NewScanner(file)
  470. commits := []*object.Commit{}
  471. for scanner.Scan() {
  472. hash := plumbing.NewHash(scanner.Text())
  473. if len(hash) != 20 {
  474. return nil, errors.New("invalid commit hash " + scanner.Text())
  475. }
  476. commit, err := repository.CommitObject(hash)
  477. if err != nil {
  478. return nil, err
  479. }
  480. commits = append(commits, commit)
  481. }
  482. return commits, nil
  483. }