pipeline.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. package core
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "log"
  8. "os"
  9. "path/filepath"
  10. "sort"
  11. "strings"
  12. "time"
  13. "github.com/pkg/errors"
  14. "gopkg.in/src-d/go-git.v4"
  15. "gopkg.in/src-d/go-git.v4/plumbing"
  16. "gopkg.in/src-d/go-git.v4/plumbing/object"
  17. "gopkg.in/src-d/go-git.v4/plumbing/storer"
  18. "gopkg.in/src-d/hercules.v6/internal/pb"
  19. "gopkg.in/src-d/hercules.v6/internal/toposort"
  20. )
  21. // ConfigurationOptionType represents the possible types of a ConfigurationOption's value.
  22. type ConfigurationOptionType int
  23. const (
  24. // BoolConfigurationOption reflects the boolean value type.
  25. BoolConfigurationOption ConfigurationOptionType = iota
  26. // IntConfigurationOption reflects the integer value type.
  27. IntConfigurationOption
  28. // StringConfigurationOption reflects the string value type.
  29. StringConfigurationOption
  30. // FloatConfigurationOption reflects a floating point value type.
  31. FloatConfigurationOption
  32. // StringsConfigurationOption reflects the array of strings value type.
  33. StringsConfigurationOption
  34. )
  35. // String() returns an empty string for the boolean type, "int" for integers and "string" for
  36. // strings. It is used in the command line interface to show the argument's type.
  37. func (opt ConfigurationOptionType) String() string {
  38. switch opt {
  39. case BoolConfigurationOption:
  40. return ""
  41. case IntConfigurationOption:
  42. return "int"
  43. case StringConfigurationOption:
  44. return "string"
  45. case FloatConfigurationOption:
  46. return "float"
  47. case StringsConfigurationOption:
  48. return "string"
  49. }
  50. log.Panicf("Invalid ConfigurationOptionType value %d", opt)
  51. return ""
  52. }
  53. // ConfigurationOption allows for the unified, retrospective way to setup PipelineItem-s.
  54. type ConfigurationOption struct {
  55. // Name identifies the configuration option in facts.
  56. Name string
  57. // Description represents the help text about the configuration option.
  58. Description string
  59. // Flag corresponds to the CLI token with "--" prepended.
  60. Flag string
  61. // Type specifies the kind of the configuration option's value.
  62. Type ConfigurationOptionType
  63. // Default is the initial value of the configuration option.
  64. Default interface{}
  65. }
  66. // FormatDefault converts the default value of ConfigurationOption to string.
  67. // Used in the command line interface to show the argument's default value.
  68. func (opt ConfigurationOption) FormatDefault() string {
  69. if opt.Type == StringsConfigurationOption {
  70. return fmt.Sprintf("\"%s\"", strings.Join(opt.Default.([]string), ","))
  71. }
  72. if opt.Type != StringConfigurationOption {
  73. return fmt.Sprint(opt.Default)
  74. }
  75. return fmt.Sprintf("\"%s\"", opt.Default)
  76. }
  77. // PipelineItem is the interface for all the units in the Git commits analysis pipeline.
  78. type PipelineItem interface {
  79. // Name returns the name of the analysis.
  80. Name() string
  81. // Provides returns the list of keys of reusable calculated entities.
  82. // Other items may depend on them.
  83. Provides() []string
  84. // Requires returns the list of keys of needed entities which must be supplied in Consume().
  85. Requires() []string
  86. // ListConfigurationOptions returns the list of available options which can be consumed by Configure().
  87. ListConfigurationOptions() []ConfigurationOption
  88. // Configure performs the initial setup of the object by applying parameters from facts.
  89. // It allows to create PipelineItems in a universal way.
  90. Configure(facts map[string]interface{}) error
  91. // Initialize prepares and resets the item. Consume() requires Initialize()
  92. // to be called at least once beforehand.
  93. Initialize(*git.Repository) error
  94. // Consume processes the next commit.
  95. // deps contains the required entities which match Depends(). Besides, it always includes
  96. // DependencyCommit and DependencyIndex.
  97. // Returns the calculated entities which match Provides().
  98. Consume(deps map[string]interface{}) (map[string]interface{}, error)
  99. // Fork clones the item the requested number of times. The data links between the clones
  100. // are up to the implementation. Needed to handle Git branches. See also Merge().
  101. // Returns a slice with `n` fresh clones. In other words, it does not include the original item.
  102. Fork(n int) []PipelineItem
  103. // Merge combines several branches together. Each is supposed to have been created with Fork().
  104. // The result is stored in the called item, thus this function returns nothing.
  105. // Merge() must update all the branches, not only self. When several branches merge, some of
  106. // them may continue to live, hence this requirement.
  107. Merge(branches []PipelineItem)
  108. }
  109. // FeaturedPipelineItem enables switching the automatic insertion of pipeline items on or off.
  110. type FeaturedPipelineItem interface {
  111. PipelineItem
  112. // Features returns the list of names which enable this item to be automatically inserted
  113. // in Pipeline.DeployItem().
  114. Features() []string
  115. }
  116. // LeafPipelineItem corresponds to the top level pipeline items which produce the end results.
  117. type LeafPipelineItem interface {
  118. PipelineItem
  119. // Flag returns the cmdline switch to run the analysis. Should be dash-lower-case
  120. // without the leading dashes.
  121. Flag() string
  122. // Description returns the text which explains what the analysis is doing.
  123. // Should start with a capital letter and end with a dot.
  124. Description() string
  125. // Finalize returns the result of the analysis.
  126. Finalize() interface{}
  127. // Serialize encodes the object returned by Finalize() to YAML or Protocol Buffers.
  128. Serialize(result interface{}, binary bool, writer io.Writer) error
  129. }
  130. // ResultMergeablePipelineItem specifies the methods to combine several analysis results together.
  131. type ResultMergeablePipelineItem interface {
  132. LeafPipelineItem
  133. // Deserialize loads the result from Protocol Buffers blob.
  134. Deserialize(pbmessage []byte) (interface{}, error)
  135. // MergeResults joins two results together. Common-s are specified as the global state.
  136. MergeResults(r1, r2 interface{}, c1, c2 *CommonAnalysisResult) interface{}
  137. }
  138. // CommonAnalysisResult holds the information which is always extracted at Pipeline.Run().
  139. type CommonAnalysisResult struct {
  140. // BeginTime is the time of the first commit in the analysed sequence.
  141. BeginTime int64
  142. // EndTime is the time of the last commit in the analysed sequence.
  143. EndTime int64
  144. // CommitsNumber is the number of commits in the analysed sequence.
  145. CommitsNumber int
  146. // RunTime is the duration of Pipeline.Run().
  147. RunTime time.Duration
  148. // RunTimePerItem is the time elapsed by each PipelineItem.
  149. RunTimePerItem map[string]float64
  150. }
  151. // BeginTimeAsTime converts the UNIX timestamp of the beginning to Go time.
  152. func (car *CommonAnalysisResult) BeginTimeAsTime() time.Time {
  153. return time.Unix(car.BeginTime, 0)
  154. }
  155. // EndTimeAsTime converts the UNIX timestamp of the ending to Go time.
  156. func (car *CommonAnalysisResult) EndTimeAsTime() time.Time {
  157. return time.Unix(car.EndTime, 0)
  158. }
  159. // Merge combines the CommonAnalysisResult with an other one.
  160. // We choose the earlier BeginTime, the later EndTime, sum the number of commits and the
  161. // elapsed run times.
  162. func (car *CommonAnalysisResult) Merge(other *CommonAnalysisResult) {
  163. if car.EndTime == 0 || other.BeginTime == 0 {
  164. panic("Merging with an uninitialized CommonAnalysisResult")
  165. }
  166. if other.BeginTime < car.BeginTime {
  167. car.BeginTime = other.BeginTime
  168. }
  169. if other.EndTime > car.EndTime {
  170. car.EndTime = other.EndTime
  171. }
  172. car.CommitsNumber += other.CommitsNumber
  173. car.RunTime += other.RunTime
  174. for key, val := range other.RunTimePerItem {
  175. car.RunTimePerItem[key] += val
  176. }
  177. }
  178. // FillMetadata copies the data to a Protobuf message.
  179. func (car *CommonAnalysisResult) FillMetadata(meta *pb.Metadata) *pb.Metadata {
  180. meta.BeginUnixTime = car.BeginTime
  181. meta.EndUnixTime = car.EndTime
  182. meta.Commits = int32(car.CommitsNumber)
  183. meta.RunTime = car.RunTime.Nanoseconds() / 1e6
  184. meta.RunTimePerItem = car.RunTimePerItem
  185. return meta
  186. }
  187. // Metadata is defined in internal/pb/pb.pb.go - header of the binary file.
  188. type Metadata = pb.Metadata
  189. // MetadataToCommonAnalysisResult copies the data from a Protobuf message.
  190. func MetadataToCommonAnalysisResult(meta *Metadata) *CommonAnalysisResult {
  191. return &CommonAnalysisResult{
  192. BeginTime: meta.BeginUnixTime,
  193. EndTime: meta.EndUnixTime,
  194. CommitsNumber: int(meta.Commits),
  195. RunTime: time.Duration(meta.RunTime * 1e6),
  196. RunTimePerItem: meta.RunTimePerItem,
  197. }
  198. }
  199. // Pipeline is the core Hercules entity which carries several PipelineItems and executes them.
  200. // See the extended example of how a Pipeline works in doc.go
  201. type Pipeline struct {
  202. // OnProgress is the callback which is invoked in Analyse() to output it's
  203. // progress. The first argument is the number of complete steps and the
  204. // second is the total number of steps.
  205. OnProgress func(int, int)
  206. // DryRun indicates whether the items are not executed.
  207. DryRun bool
  208. // DumpPlan indicates whether to print the execution plan to stderr.
  209. DumpPlan bool
  210. // Repository points to the analysed Git repository struct from go-git.
  211. repository *git.Repository
  212. // Items are the registered building blocks in the pipeline. The order defines the
  213. // execution sequence.
  214. items []PipelineItem
  215. // The collection of parameters to create items.
  216. facts map[string]interface{}
  217. // Feature flags which enable the corresponding items.
  218. features map[string]bool
  219. }
  220. const (
  221. // ConfigPipelineDAGPath is the name of the Pipeline configuration option (Pipeline.Initialize())
  222. // which enables saving the items DAG to the specified file.
  223. ConfigPipelineDAGPath = "Pipeline.DAGPath"
  224. // ConfigPipelineDryRun is the name of the Pipeline configuration option (Pipeline.Initialize())
  225. // which disables Configure() and Initialize() invocation on each PipelineItem during the
  226. // Pipeline initialization.
  227. // Subsequent Run() calls are going to fail. Useful with ConfigPipelineDAGPath=true.
  228. ConfigPipelineDryRun = "Pipeline.DryRun"
  229. // ConfigPipelineCommits is the name of the Pipeline configuration option (Pipeline.Initialize())
  230. // which allows to specify the custom commit sequence. By default, Pipeline.Commits() is used.
  231. ConfigPipelineCommits = "Pipeline.Commits"
  232. // ConfigPipelineDumpPlan is the name of the Pipeline configuration option (Pipeline.Initialize())
  233. // which outputs the execution plan to stderr.
  234. ConfigPipelineDumpPlan = "Pipeline.DumpPlan"
  235. // DependencyCommit is the name of one of the three items in `deps` supplied to PipelineItem.Consume()
  236. // which always exists. It corresponds to the currently analyzed commit.
  237. DependencyCommit = "commit"
  238. // DependencyIndex is the name of one of the three items in `deps` supplied to PipelineItem.Consume()
  239. // which always exists. It corresponds to the currently analyzed commit's index.
  240. DependencyIndex = "index"
  241. // DependencyIsMerge is the name of one of the three items in `deps` supplied to PipelineItem.Consume()
  242. // which always exists. It indicates whether the analyzed commit is a merge commit.
  243. // Checking the number of parents is not correct - we remove the back edges during the DAG simplification.
  244. DependencyIsMerge = "is_merge"
  245. )
  246. // NewPipeline initializes a new instance of Pipeline struct.
  247. func NewPipeline(repository *git.Repository) *Pipeline {
  248. return &Pipeline{
  249. repository: repository,
  250. items: []PipelineItem{},
  251. facts: map[string]interface{}{},
  252. features: map[string]bool{},
  253. }
  254. }
  255. // GetFact returns the value of the fact with the specified name.
  256. func (pipeline *Pipeline) GetFact(name string) interface{} {
  257. return pipeline.facts[name]
  258. }
  259. // SetFact sets the value of the fact with the specified name.
  260. func (pipeline *Pipeline) SetFact(name string, value interface{}) {
  261. pipeline.facts[name] = value
  262. }
  263. // GetFeature returns the state of the feature with the specified name (enabled/disabled) and
  264. // whether it exists. See also: FeaturedPipelineItem.
  265. func (pipeline *Pipeline) GetFeature(name string) (bool, bool) {
  266. val, exists := pipeline.features[name]
  267. return val, exists
  268. }
  269. // SetFeature sets the value of the feature with the specified name.
  270. // See also: FeaturedPipelineItem.
  271. func (pipeline *Pipeline) SetFeature(name string) {
  272. pipeline.features[name] = true
  273. }
  274. // SetFeaturesFromFlags enables the features which were specified through the command line flags
  275. // which belong to the given PipelineItemRegistry instance.
  276. // See also: AddItem().
  277. func (pipeline *Pipeline) SetFeaturesFromFlags(registry ...*PipelineItemRegistry) {
  278. var ffr *PipelineItemRegistry
  279. if len(registry) == 0 {
  280. ffr = Registry
  281. } else if len(registry) == 1 {
  282. ffr = registry[0]
  283. } else {
  284. panic("Zero or one registry is allowed to be passed.")
  285. }
  286. for _, feature := range ffr.featureFlags.Flags {
  287. pipeline.SetFeature(feature)
  288. }
  289. }
  290. // DeployItem inserts a PipelineItem into the pipeline. It also recursively creates all of it's
  291. // dependencies (PipelineItem.Requires()). Returns the same item as specified in the arguments.
  292. func (pipeline *Pipeline) DeployItem(item PipelineItem) PipelineItem {
  293. fpi, ok := item.(FeaturedPipelineItem)
  294. if ok {
  295. for _, f := range fpi.Features() {
  296. pipeline.SetFeature(f)
  297. }
  298. }
  299. queue := []PipelineItem{}
  300. queue = append(queue, item)
  301. added := map[string]PipelineItem{}
  302. for _, item := range pipeline.items {
  303. added[item.Name()] = item
  304. }
  305. added[item.Name()] = item
  306. pipeline.AddItem(item)
  307. for len(queue) > 0 {
  308. head := queue[0]
  309. queue = queue[1:]
  310. for _, dep := range head.Requires() {
  311. for _, sibling := range Registry.Summon(dep) {
  312. if _, exists := added[sibling.Name()]; !exists {
  313. disabled := false
  314. // If this item supports features, check them against the activated in pipeline.features
  315. if fpi, matches := sibling.(FeaturedPipelineItem); matches {
  316. for _, feature := range fpi.Features() {
  317. if !pipeline.features[feature] {
  318. disabled = true
  319. break
  320. }
  321. }
  322. }
  323. if disabled {
  324. continue
  325. }
  326. added[sibling.Name()] = sibling
  327. queue = append(queue, sibling)
  328. pipeline.AddItem(sibling)
  329. }
  330. }
  331. }
  332. }
  333. return item
  334. }
  335. // AddItem inserts a PipelineItem into the pipeline. It does not check any dependencies.
  336. // See also: DeployItem().
  337. func (pipeline *Pipeline) AddItem(item PipelineItem) PipelineItem {
  338. pipeline.items = append(pipeline.items, item)
  339. return item
  340. }
  341. // RemoveItem deletes a PipelineItem from the pipeline. It leaves all the rest of the items intact.
  342. func (pipeline *Pipeline) RemoveItem(item PipelineItem) {
  343. for i, reg := range pipeline.items {
  344. if reg == item {
  345. pipeline.items = append(pipeline.items[:i], pipeline.items[i+1:]...)
  346. return
  347. }
  348. }
  349. }
  350. // Len returns the number of items in the pipeline.
  351. func (pipeline *Pipeline) Len() int {
  352. return len(pipeline.items)
  353. }
  354. // Commits returns the list of commits from the history similar to `git log` over the HEAD.
  355. // `firstParent` specifies whether to leave only the first parent after each merge
  356. // (`git log --first-parent`) - effectively decreasing the accuracy but increasing performance.
  357. func (pipeline *Pipeline) Commits(firstParent bool) ([]*object.Commit, error) {
  358. var result []*object.Commit
  359. repository := pipeline.repository
  360. head, err := repository.Head()
  361. if err != nil {
  362. if err == plumbing.ErrReferenceNotFound {
  363. refs, errr := repository.References()
  364. if errr != nil {
  365. return nil, errors.Wrap(errr, "unable to list the references")
  366. }
  367. refs.ForEach(func(ref *plumbing.Reference) error {
  368. if strings.HasPrefix(ref.Name().String(), "refs/heads/HEAD/") {
  369. head = ref
  370. return storer.ErrStop
  371. }
  372. return nil
  373. })
  374. }
  375. if head == nil && err != nil {
  376. return nil, errors.Wrap(err, "unable to collect the commit history")
  377. }
  378. }
  379. if firstParent {
  380. commit, err := repository.CommitObject(head.Hash())
  381. if err != nil {
  382. panic(err)
  383. }
  384. // the first parent matches the head
  385. for ; err != io.EOF; commit, err = commit.Parents().Next() {
  386. if err != nil {
  387. panic(err)
  388. }
  389. result = append(result, commit)
  390. }
  391. // reverse the order
  392. for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 {
  393. result[i], result[j] = result[j], result[i]
  394. }
  395. return result, nil
  396. }
  397. cit, err := repository.Log(&git.LogOptions{From: head.Hash()})
  398. if err != nil {
  399. return nil, errors.Wrap(err, "unable to collect the commit history")
  400. }
  401. defer cit.Close()
  402. cit.ForEach(func(commit *object.Commit) error {
  403. result = append(result, commit)
  404. return nil
  405. })
  406. return result, nil
  407. }
  408. type sortablePipelineItems []PipelineItem
  409. func (items sortablePipelineItems) Len() int {
  410. return len(items)
  411. }
  412. func (items sortablePipelineItems) Less(i, j int) bool {
  413. return items[i].Name() < items[j].Name()
  414. }
  415. func (items sortablePipelineItems) Swap(i, j int) {
  416. items[i], items[j] = items[j], items[i]
  417. }
  418. func (pipeline *Pipeline) resolve(dumpPath string) {
  419. graph := toposort.NewGraph()
  420. sort.Sort(sortablePipelineItems(pipeline.items))
  421. name2item := map[string]PipelineItem{}
  422. ambiguousMap := map[string][]string{}
  423. nameUsages := map[string]int{}
  424. for _, item := range pipeline.items {
  425. nameUsages[item.Name()]++
  426. }
  427. counters := map[string]int{}
  428. for _, item := range pipeline.items {
  429. name := item.Name()
  430. if nameUsages[name] > 1 {
  431. index := counters[item.Name()] + 1
  432. counters[item.Name()] = index
  433. name = fmt.Sprintf("%s_%d", item.Name(), index)
  434. }
  435. graph.AddNode(name)
  436. name2item[name] = item
  437. for _, key := range item.Provides() {
  438. key = "[" + key + "]"
  439. graph.AddNode(key)
  440. if graph.AddEdge(name, key) > 1 {
  441. if ambiguousMap[key] != nil {
  442. fmt.Fprintln(os.Stderr, "Pipeline:")
  443. for _, item2 := range pipeline.items {
  444. if item2 == item {
  445. fmt.Fprint(os.Stderr, "> ")
  446. }
  447. fmt.Fprint(os.Stderr, item2.Name(), " [")
  448. for i, key2 := range item2.Provides() {
  449. fmt.Fprint(os.Stderr, key2)
  450. if i < len(item.Provides())-1 {
  451. fmt.Fprint(os.Stderr, ", ")
  452. }
  453. }
  454. fmt.Fprintln(os.Stderr, "]")
  455. }
  456. panic("Failed to resolve pipeline dependencies: ambiguous graph.")
  457. }
  458. ambiguousMap[key] = graph.FindParents(key)
  459. }
  460. }
  461. }
  462. counters = map[string]int{}
  463. for _, item := range pipeline.items {
  464. name := item.Name()
  465. if nameUsages[name] > 1 {
  466. index := counters[item.Name()] + 1
  467. counters[item.Name()] = index
  468. name = fmt.Sprintf("%s_%d", item.Name(), index)
  469. }
  470. for _, key := range item.Requires() {
  471. key = "[" + key + "]"
  472. if graph.AddEdge(key, name) == 0 {
  473. log.Panicf("Unsatisfied dependency: %s -> %s", key, item.Name())
  474. }
  475. }
  476. }
  477. // Try to break the cycles in some known scenarios.
  478. if len(ambiguousMap) > 0 {
  479. var ambiguous []string
  480. for key := range ambiguousMap {
  481. ambiguous = append(ambiguous, key)
  482. }
  483. sort.Strings(ambiguous)
  484. bfsorder := graph.BreadthSort()
  485. bfsindex := map[string]int{}
  486. for i, s := range bfsorder {
  487. bfsindex[s] = i
  488. }
  489. for len(ambiguous) > 0 {
  490. key := ambiguous[0]
  491. ambiguous = ambiguous[1:]
  492. pair := ambiguousMap[key]
  493. inheritor := pair[1]
  494. if bfsindex[pair[1]] < bfsindex[pair[0]] {
  495. inheritor = pair[0]
  496. }
  497. removed := graph.RemoveEdge(key, inheritor)
  498. cycle := map[string]bool{}
  499. for _, node := range graph.FindCycle(key) {
  500. cycle[node] = true
  501. }
  502. if len(cycle) == 0 {
  503. cycle[inheritor] = true
  504. }
  505. if removed {
  506. graph.AddEdge(key, inheritor)
  507. }
  508. graph.RemoveEdge(inheritor, key)
  509. graph.ReindexNode(inheritor)
  510. // for all nodes key links to except those in cycle, put the link from inheritor
  511. for _, node := range graph.FindChildren(key) {
  512. if _, exists := cycle[node]; !exists {
  513. graph.AddEdge(inheritor, node)
  514. graph.RemoveEdge(key, node)
  515. }
  516. }
  517. graph.ReindexNode(key)
  518. }
  519. }
  520. var graphCopy *toposort.Graph
  521. if dumpPath != "" {
  522. graphCopy = graph.Copy()
  523. }
  524. strplan, ok := graph.Toposort()
  525. if !ok {
  526. panic("Failed to resolve pipeline dependencies: unable to topologically sort the items.")
  527. }
  528. pipeline.items = make([]PipelineItem, 0, len(pipeline.items))
  529. for _, key := range strplan {
  530. if item, ok := name2item[key]; ok {
  531. pipeline.items = append(pipeline.items, item)
  532. }
  533. }
  534. if dumpPath != "" {
  535. // If there is a floating difference, uncomment this:
  536. // fmt.Fprint(os.Stderr, graphCopy.DebugDump())
  537. ioutil.WriteFile(dumpPath, []byte(graphCopy.Serialize(strplan)), 0666)
  538. absPath, _ := filepath.Abs(dumpPath)
  539. log.Printf("Wrote the DAG to %s\n", absPath)
  540. }
  541. }
  542. // Initialize prepares the pipeline for the execution (Run()). This function
  543. // resolves the execution DAG, Configure()-s and Initialize()-s the items in it in the
  544. // topological dependency order. `facts` are passed inside Configure(). They are mutable.
  545. func (pipeline *Pipeline) Initialize(facts map[string]interface{}) error {
  546. if facts == nil {
  547. facts = map[string]interface{}{}
  548. }
  549. if _, exists := facts[ConfigPipelineCommits]; !exists {
  550. var err error
  551. facts[ConfigPipelineCommits], err = pipeline.Commits(false)
  552. if err != nil {
  553. log.Panicf("failed to list the commits: %v", err)
  554. }
  555. }
  556. dumpPath, _ := facts[ConfigPipelineDAGPath].(string)
  557. pipeline.resolve(dumpPath)
  558. if dumpPlan, exists := facts[ConfigPipelineDumpPlan].(bool); exists {
  559. pipeline.DumpPlan = dumpPlan
  560. }
  561. if dryRun, exists := facts[ConfigPipelineDryRun].(bool); exists {
  562. pipeline.DryRun = dryRun
  563. if dryRun {
  564. return nil
  565. }
  566. }
  567. for _, item := range pipeline.items {
  568. err := item.Configure(facts)
  569. if err != nil {
  570. return errors.Wrapf(err, "%s failed to configure", item.Name())
  571. }
  572. }
  573. for _, item := range pipeline.items {
  574. err := item.Initialize(pipeline.repository)
  575. if err != nil {
  576. return errors.Wrapf(err, "%s failed to initialize", item.Name())
  577. }
  578. }
  579. return nil
  580. }
  581. // Run method executes the pipeline.
  582. //
  583. // `commits` is a slice with the git commits to analyse. Multiple branches are supported.
  584. //
  585. // Returns the mapping from each LeafPipelineItem to the corresponding analysis result.
  586. // There is always a "nil" record with CommonAnalysisResult.
  587. func (pipeline *Pipeline) Run(commits []*object.Commit) (map[LeafPipelineItem]interface{}, error) {
  588. startRunTime := time.Now()
  589. onProgress := pipeline.OnProgress
  590. if onProgress == nil {
  591. onProgress = func(int, int) {}
  592. }
  593. plan := prepareRunPlan(commits, pipeline.DumpPlan)
  594. progressSteps := len(plan) + 2
  595. branches := map[int][]PipelineItem{}
  596. // we will need rootClone if there is more than one root branch
  597. var rootClone []PipelineItem
  598. if !pipeline.DryRun {
  599. rootClone = cloneItems(pipeline.items, 1)[0]
  600. }
  601. var newestTime int64
  602. runTimePerItem := map[string]float64{}
  603. commitIndex := 0
  604. for index, step := range plan {
  605. onProgress(index+1, progressSteps)
  606. if pipeline.DryRun {
  607. continue
  608. }
  609. firstItem := step.Items[0]
  610. switch step.Action {
  611. case runActionCommit:
  612. state := map[string]interface{}{
  613. DependencyCommit: step.Commit,
  614. DependencyIndex: commitIndex,
  615. DependencyIsMerge: (index > 0 &&
  616. plan[index-1].Action == runActionCommit &&
  617. plan[index-1].Commit.Hash == step.Commit.Hash) ||
  618. (index < (len(plan)-1) &&
  619. plan[index+1].Action == runActionCommit &&
  620. plan[index+1].Commit.Hash == step.Commit.Hash),
  621. }
  622. for _, item := range branches[firstItem] {
  623. startTime := time.Now()
  624. update, err := item.Consume(state)
  625. runTimePerItem[item.Name()] += time.Now().Sub(startTime).Seconds()
  626. if err != nil {
  627. log.Printf("%s failed on commit #%d (%d) %s\n",
  628. item.Name(), commitIndex+1, index+1, step.Commit.Hash.String())
  629. return nil, err
  630. }
  631. for _, key := range item.Provides() {
  632. val, ok := update[key]
  633. if !ok {
  634. log.Panicf("%s: Consume() did not return %s", item.Name(), key)
  635. }
  636. state[key] = val
  637. }
  638. }
  639. commitTime := step.Commit.Committer.When.Unix()
  640. if commitTime > newestTime {
  641. newestTime = commitTime
  642. }
  643. commitIndex++
  644. case runActionFork:
  645. for i, clone := range cloneItems(branches[firstItem], len(step.Items)-1) {
  646. branches[step.Items[i+1]] = clone
  647. }
  648. case runActionMerge:
  649. merged := make([][]PipelineItem, len(step.Items))
  650. for i, b := range step.Items {
  651. merged[i] = branches[b]
  652. }
  653. mergeItems(merged)
  654. case runActionEmerge:
  655. if firstItem == rootBranchIndex {
  656. branches[firstItem] = pipeline.items
  657. } else {
  658. branches[firstItem] = cloneItems(rootClone, 1)[0]
  659. }
  660. case runActionDelete:
  661. delete(branches, firstItem)
  662. }
  663. }
  664. onProgress(len(plan)+1, progressSteps)
  665. result := map[LeafPipelineItem]interface{}{}
  666. if !pipeline.DryRun {
  667. for index, item := range getMasterBranch(branches) {
  668. if casted, ok := item.(LeafPipelineItem); ok {
  669. result[pipeline.items[index].(LeafPipelineItem)] = casted.Finalize()
  670. }
  671. }
  672. }
  673. onProgress(progressSteps, progressSteps)
  674. result[nil] = &CommonAnalysisResult{
  675. BeginTime: plan[0].Commit.Committer.When.Unix(),
  676. EndTime: newestTime,
  677. CommitsNumber: len(commits),
  678. RunTime: time.Since(startRunTime),
  679. RunTimePerItem: runTimePerItem,
  680. }
  681. return result, nil
  682. }
  683. // LoadCommitsFromFile reads the file by the specified FS path and generates the sequence of commits
  684. // by interpreting each line as a Git commit hash.
  685. func LoadCommitsFromFile(path string, repository *git.Repository) ([]*object.Commit, error) {
  686. var file io.ReadCloser
  687. if path != "-" {
  688. var err error
  689. file, err = os.Open(path)
  690. if err != nil {
  691. return nil, err
  692. }
  693. defer file.Close()
  694. } else {
  695. file = os.Stdin
  696. }
  697. scanner := bufio.NewScanner(file)
  698. var commits []*object.Commit
  699. for scanner.Scan() {
  700. hash := plumbing.NewHash(scanner.Text())
  701. if len(hash) != 20 {
  702. return nil, errors.New("invalid commit hash " + scanner.Text())
  703. }
  704. commit, err := repository.CommitObject(hash)
  705. if err != nil {
  706. return nil, err
  707. }
  708. commits = append(commits, commit)
  709. }
  710. return commits, nil
  711. }