pipeline.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  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. // HibernateablePipelineItem is the interface to allow pipeline items to be frozen (compacted, unloaded)
  139. // while they are not needed in the hosting branch.
  140. type HibernateablePipelineItem interface {
  141. PipelineItem
  142. // Hibernate signals that the item is temporarily not needed and it's memory can be optimized.
  143. Hibernate() error
  144. // Boot signals that the item is needed again and must be de-hibernate-d.
  145. Boot() error
  146. }
  147. // CommonAnalysisResult holds the information which is always extracted at Pipeline.Run().
  148. type CommonAnalysisResult struct {
  149. // BeginTime is the time of the first commit in the analysed sequence.
  150. BeginTime int64
  151. // EndTime is the time of the last commit in the analysed sequence.
  152. EndTime int64
  153. // CommitsNumber is the number of commits in the analysed sequence.
  154. CommitsNumber int
  155. // RunTime is the duration of Pipeline.Run().
  156. RunTime time.Duration
  157. // RunTimePerItem is the time elapsed by each PipelineItem.
  158. RunTimePerItem map[string]float64
  159. }
  160. // BeginTimeAsTime converts the UNIX timestamp of the beginning to Go time.
  161. func (car *CommonAnalysisResult) BeginTimeAsTime() time.Time {
  162. return time.Unix(car.BeginTime, 0)
  163. }
  164. // EndTimeAsTime converts the UNIX timestamp of the ending to Go time.
  165. func (car *CommonAnalysisResult) EndTimeAsTime() time.Time {
  166. return time.Unix(car.EndTime, 0)
  167. }
  168. // Merge combines the CommonAnalysisResult with an other one.
  169. // We choose the earlier BeginTime, the later EndTime, sum the number of commits and the
  170. // elapsed run times.
  171. func (car *CommonAnalysisResult) Merge(other *CommonAnalysisResult) {
  172. if car.EndTime == 0 || other.BeginTime == 0 {
  173. panic("Merging with an uninitialized CommonAnalysisResult")
  174. }
  175. if other.BeginTime < car.BeginTime {
  176. car.BeginTime = other.BeginTime
  177. }
  178. if other.EndTime > car.EndTime {
  179. car.EndTime = other.EndTime
  180. }
  181. car.CommitsNumber += other.CommitsNumber
  182. car.RunTime += other.RunTime
  183. for key, val := range other.RunTimePerItem {
  184. car.RunTimePerItem[key] += val
  185. }
  186. }
  187. // FillMetadata copies the data to a Protobuf message.
  188. func (car *CommonAnalysisResult) FillMetadata(meta *pb.Metadata) *pb.Metadata {
  189. meta.BeginUnixTime = car.BeginTime
  190. meta.EndUnixTime = car.EndTime
  191. meta.Commits = int32(car.CommitsNumber)
  192. meta.RunTime = car.RunTime.Nanoseconds() / 1e6
  193. meta.RunTimePerItem = car.RunTimePerItem
  194. return meta
  195. }
  196. // Metadata is defined in internal/pb/pb.pb.go - header of the binary file.
  197. type Metadata = pb.Metadata
  198. // MetadataToCommonAnalysisResult copies the data from a Protobuf message.
  199. func MetadataToCommonAnalysisResult(meta *Metadata) *CommonAnalysisResult {
  200. return &CommonAnalysisResult{
  201. BeginTime: meta.BeginUnixTime,
  202. EndTime: meta.EndUnixTime,
  203. CommitsNumber: int(meta.Commits),
  204. RunTime: time.Duration(meta.RunTime * 1e6),
  205. RunTimePerItem: meta.RunTimePerItem,
  206. }
  207. }
  208. // Pipeline is the core Hercules entity which carries several PipelineItems and executes them.
  209. // See the extended example of how a Pipeline works in doc.go
  210. type Pipeline struct {
  211. // OnProgress is the callback which is invoked in Analyse() to output it's
  212. // progress. The first argument is the number of complete steps and the
  213. // second is the total number of steps.
  214. OnProgress func(int, int)
  215. // HibernationDistance is the minimum number of actions between two sequential usages of
  216. // a branch to activate the hibernation optimization (cpu-memory trade-off). 0 disables.
  217. HibernationDistance int
  218. // DryRun indicates whether the items are not executed.
  219. DryRun bool
  220. // DumpPlan indicates whether to print the execution plan to stderr.
  221. DumpPlan bool
  222. // Repository points to the analysed Git repository struct from go-git.
  223. repository *git.Repository
  224. // Items are the registered building blocks in the pipeline. The order defines the
  225. // execution sequence.
  226. items []PipelineItem
  227. // The collection of parameters to create items.
  228. facts map[string]interface{}
  229. // Feature flags which enable the corresponding items.
  230. features map[string]bool
  231. }
  232. const (
  233. // ConfigPipelineDAGPath is the name of the Pipeline configuration option (Pipeline.Initialize())
  234. // which enables saving the items DAG to the specified file.
  235. ConfigPipelineDAGPath = "Pipeline.DAGPath"
  236. // ConfigPipelineDryRun is the name of the Pipeline configuration option (Pipeline.Initialize())
  237. // which disables Configure() and Initialize() invocation on each PipelineItem during the
  238. // Pipeline initialization.
  239. // Subsequent Run() calls are going to fail. Useful with ConfigPipelineDAGPath=true.
  240. ConfigPipelineDryRun = "Pipeline.DryRun"
  241. // ConfigPipelineCommits is the name of the Pipeline configuration option (Pipeline.Initialize())
  242. // which allows to specify the custom commit sequence. By default, Pipeline.Commits() is used.
  243. ConfigPipelineCommits = "Pipeline.Commits"
  244. // ConfigPipelineDumpPlan is the name of the Pipeline configuration option (Pipeline.Initialize())
  245. // which outputs the execution plan to stderr.
  246. ConfigPipelineDumpPlan = "Pipeline.DumpPlan"
  247. // ConfigPipelineHibernationDistance is the name of the Pipeline configuration option (Pipeline.Initialize())
  248. // which is the minimum number of actions between two sequential usages of
  249. // a branch to activate the hibernation optimization (cpu-memory trade-off). 0 disables.
  250. ConfigPipelineHibernationDistance = "Pipeline.HibernationDistance"
  251. // DependencyCommit is the name of one of the three items in `deps` supplied to PipelineItem.Consume()
  252. // which always exists. It corresponds to the currently analyzed commit.
  253. DependencyCommit = "commit"
  254. // DependencyIndex is the name of one of the three items in `deps` supplied to PipelineItem.Consume()
  255. // which always exists. It corresponds to the currently analyzed commit's index.
  256. DependencyIndex = "index"
  257. // DependencyIsMerge is the name of one of the three items in `deps` supplied to PipelineItem.Consume()
  258. // which always exists. It indicates whether the analyzed commit is a merge commit.
  259. // Checking the number of parents is not correct - we remove the back edges during the DAG simplification.
  260. DependencyIsMerge = "is_merge"
  261. )
  262. // NewPipeline initializes a new instance of Pipeline struct.
  263. func NewPipeline(repository *git.Repository) *Pipeline {
  264. return &Pipeline{
  265. repository: repository,
  266. items: []PipelineItem{},
  267. facts: map[string]interface{}{},
  268. features: map[string]bool{},
  269. }
  270. }
  271. // GetFact returns the value of the fact with the specified name.
  272. func (pipeline *Pipeline) GetFact(name string) interface{} {
  273. return pipeline.facts[name]
  274. }
  275. // SetFact sets the value of the fact with the specified name.
  276. func (pipeline *Pipeline) SetFact(name string, value interface{}) {
  277. pipeline.facts[name] = value
  278. }
  279. // GetFeature returns the state of the feature with the specified name (enabled/disabled) and
  280. // whether it exists. See also: FeaturedPipelineItem.
  281. func (pipeline *Pipeline) GetFeature(name string) (bool, bool) {
  282. val, exists := pipeline.features[name]
  283. return val, exists
  284. }
  285. // SetFeature sets the value of the feature with the specified name.
  286. // See also: FeaturedPipelineItem.
  287. func (pipeline *Pipeline) SetFeature(name string) {
  288. pipeline.features[name] = true
  289. }
  290. // SetFeaturesFromFlags enables the features which were specified through the command line flags
  291. // which belong to the given PipelineItemRegistry instance.
  292. // See also: AddItem().
  293. func (pipeline *Pipeline) SetFeaturesFromFlags(registry ...*PipelineItemRegistry) {
  294. var ffr *PipelineItemRegistry
  295. if len(registry) == 0 {
  296. ffr = Registry
  297. } else if len(registry) == 1 {
  298. ffr = registry[0]
  299. } else {
  300. panic("Zero or one registry is allowed to be passed.")
  301. }
  302. for _, feature := range ffr.featureFlags.Flags {
  303. pipeline.SetFeature(feature)
  304. }
  305. }
  306. // DeployItem inserts a PipelineItem into the pipeline. It also recursively creates all of it's
  307. // dependencies (PipelineItem.Requires()). Returns the same item as specified in the arguments.
  308. func (pipeline *Pipeline) DeployItem(item PipelineItem) PipelineItem {
  309. fpi, ok := item.(FeaturedPipelineItem)
  310. if ok {
  311. for _, f := range fpi.Features() {
  312. pipeline.SetFeature(f)
  313. }
  314. }
  315. queue := []PipelineItem{}
  316. queue = append(queue, item)
  317. added := map[string]PipelineItem{}
  318. for _, item := range pipeline.items {
  319. added[item.Name()] = item
  320. }
  321. added[item.Name()] = item
  322. pipeline.AddItem(item)
  323. for len(queue) > 0 {
  324. head := queue[0]
  325. queue = queue[1:]
  326. for _, dep := range head.Requires() {
  327. for _, sibling := range Registry.Summon(dep) {
  328. if _, exists := added[sibling.Name()]; !exists {
  329. disabled := false
  330. // If this item supports features, check them against the activated in pipeline.features
  331. if fpi, matches := sibling.(FeaturedPipelineItem); matches {
  332. for _, feature := range fpi.Features() {
  333. if !pipeline.features[feature] {
  334. disabled = true
  335. break
  336. }
  337. }
  338. }
  339. if disabled {
  340. continue
  341. }
  342. added[sibling.Name()] = sibling
  343. queue = append(queue, sibling)
  344. pipeline.AddItem(sibling)
  345. }
  346. }
  347. }
  348. }
  349. return item
  350. }
  351. // AddItem inserts a PipelineItem into the pipeline. It does not check any dependencies.
  352. // See also: DeployItem().
  353. func (pipeline *Pipeline) AddItem(item PipelineItem) PipelineItem {
  354. pipeline.items = append(pipeline.items, item)
  355. return item
  356. }
  357. // RemoveItem deletes a PipelineItem from the pipeline. It leaves all the rest of the items intact.
  358. func (pipeline *Pipeline) RemoveItem(item PipelineItem) {
  359. for i, reg := range pipeline.items {
  360. if reg == item {
  361. pipeline.items = append(pipeline.items[:i], pipeline.items[i+1:]...)
  362. return
  363. }
  364. }
  365. }
  366. // Len returns the number of items in the pipeline.
  367. func (pipeline *Pipeline) Len() int {
  368. return len(pipeline.items)
  369. }
  370. // Commits returns the list of commits from the history similar to `git log` over the HEAD.
  371. // `firstParent` specifies whether to leave only the first parent after each merge
  372. // (`git log --first-parent`) - effectively decreasing the accuracy but increasing performance.
  373. func (pipeline *Pipeline) Commits(firstParent bool) ([]*object.Commit, error) {
  374. var result []*object.Commit
  375. repository := pipeline.repository
  376. head, err := repository.Head()
  377. if err != nil {
  378. if err == plumbing.ErrReferenceNotFound {
  379. refs, errr := repository.References()
  380. if errr != nil {
  381. return nil, errors.Wrap(errr, "unable to list the references")
  382. }
  383. refs.ForEach(func(ref *plumbing.Reference) error {
  384. if strings.HasPrefix(ref.Name().String(), "refs/heads/HEAD/") {
  385. head = ref
  386. return storer.ErrStop
  387. }
  388. return nil
  389. })
  390. }
  391. if head == nil && err != nil {
  392. return nil, errors.Wrap(err, "unable to collect the commit history")
  393. }
  394. }
  395. if firstParent {
  396. commit, err := repository.CommitObject(head.Hash())
  397. if err != nil {
  398. panic(err)
  399. }
  400. // the first parent matches the head
  401. for ; err != io.EOF; commit, err = commit.Parents().Next() {
  402. if err != nil {
  403. panic(err)
  404. }
  405. result = append(result, commit)
  406. }
  407. // reverse the order
  408. for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 {
  409. result[i], result[j] = result[j], result[i]
  410. }
  411. return result, nil
  412. }
  413. cit, err := repository.Log(&git.LogOptions{From: head.Hash()})
  414. if err != nil {
  415. return nil, errors.Wrap(err, "unable to collect the commit history")
  416. }
  417. defer cit.Close()
  418. cit.ForEach(func(commit *object.Commit) error {
  419. result = append(result, commit)
  420. return nil
  421. })
  422. return result, nil
  423. }
  424. type sortablePipelineItems []PipelineItem
  425. func (items sortablePipelineItems) Len() int {
  426. return len(items)
  427. }
  428. func (items sortablePipelineItems) Less(i, j int) bool {
  429. return items[i].Name() < items[j].Name()
  430. }
  431. func (items sortablePipelineItems) Swap(i, j int) {
  432. items[i], items[j] = items[j], items[i]
  433. }
  434. func (pipeline *Pipeline) resolve(dumpPath string) {
  435. graph := toposort.NewGraph()
  436. sort.Sort(sortablePipelineItems(pipeline.items))
  437. name2item := map[string]PipelineItem{}
  438. ambiguousMap := map[string][]string{}
  439. nameUsages := map[string]int{}
  440. for _, item := range pipeline.items {
  441. nameUsages[item.Name()]++
  442. }
  443. counters := map[string]int{}
  444. for _, item := range pipeline.items {
  445. name := item.Name()
  446. if nameUsages[name] > 1 {
  447. index := counters[item.Name()] + 1
  448. counters[item.Name()] = index
  449. name = fmt.Sprintf("%s_%d", item.Name(), index)
  450. }
  451. graph.AddNode(name)
  452. name2item[name] = item
  453. for _, key := range item.Provides() {
  454. key = "[" + key + "]"
  455. graph.AddNode(key)
  456. if graph.AddEdge(name, key) > 1 {
  457. if ambiguousMap[key] != nil {
  458. fmt.Fprintln(os.Stderr, "Pipeline:")
  459. for _, item2 := range pipeline.items {
  460. if item2 == item {
  461. fmt.Fprint(os.Stderr, "> ")
  462. }
  463. fmt.Fprint(os.Stderr, item2.Name(), " [")
  464. for i, key2 := range item2.Provides() {
  465. fmt.Fprint(os.Stderr, key2)
  466. if i < len(item.Provides())-1 {
  467. fmt.Fprint(os.Stderr, ", ")
  468. }
  469. }
  470. fmt.Fprintln(os.Stderr, "]")
  471. }
  472. panic("Failed to resolve pipeline dependencies: ambiguous graph.")
  473. }
  474. ambiguousMap[key] = graph.FindParents(key)
  475. }
  476. }
  477. }
  478. counters = map[string]int{}
  479. for _, item := range pipeline.items {
  480. name := item.Name()
  481. if nameUsages[name] > 1 {
  482. index := counters[item.Name()] + 1
  483. counters[item.Name()] = index
  484. name = fmt.Sprintf("%s_%d", item.Name(), index)
  485. }
  486. for _, key := range item.Requires() {
  487. key = "[" + key + "]"
  488. if graph.AddEdge(key, name) == 0 {
  489. log.Panicf("Unsatisfied dependency: %s -> %s", key, item.Name())
  490. }
  491. }
  492. }
  493. // Try to break the cycles in some known scenarios.
  494. if len(ambiguousMap) > 0 {
  495. var ambiguous []string
  496. for key := range ambiguousMap {
  497. ambiguous = append(ambiguous, key)
  498. }
  499. sort.Strings(ambiguous)
  500. bfsorder := graph.BreadthSort()
  501. bfsindex := map[string]int{}
  502. for i, s := range bfsorder {
  503. bfsindex[s] = i
  504. }
  505. for len(ambiguous) > 0 {
  506. key := ambiguous[0]
  507. ambiguous = ambiguous[1:]
  508. pair := ambiguousMap[key]
  509. inheritor := pair[1]
  510. if bfsindex[pair[1]] < bfsindex[pair[0]] {
  511. inheritor = pair[0]
  512. }
  513. removed := graph.RemoveEdge(key, inheritor)
  514. cycle := map[string]bool{}
  515. for _, node := range graph.FindCycle(key) {
  516. cycle[node] = true
  517. }
  518. if len(cycle) == 0 {
  519. cycle[inheritor] = true
  520. }
  521. if removed {
  522. graph.AddEdge(key, inheritor)
  523. }
  524. graph.RemoveEdge(inheritor, key)
  525. graph.ReindexNode(inheritor)
  526. // for all nodes key links to except those in cycle, put the link from inheritor
  527. for _, node := range graph.FindChildren(key) {
  528. if _, exists := cycle[node]; !exists {
  529. graph.AddEdge(inheritor, node)
  530. graph.RemoveEdge(key, node)
  531. }
  532. }
  533. graph.ReindexNode(key)
  534. }
  535. }
  536. var graphCopy *toposort.Graph
  537. if dumpPath != "" {
  538. graphCopy = graph.Copy()
  539. }
  540. strplan, ok := graph.Toposort()
  541. if !ok {
  542. panic("Failed to resolve pipeline dependencies: unable to topologically sort the items.")
  543. }
  544. pipeline.items = make([]PipelineItem, 0, len(pipeline.items))
  545. for _, key := range strplan {
  546. if item, ok := name2item[key]; ok {
  547. pipeline.items = append(pipeline.items, item)
  548. }
  549. }
  550. if dumpPath != "" {
  551. // If there is a floating difference, uncomment this:
  552. // fmt.Fprint(os.Stderr, graphCopy.DebugDump())
  553. ioutil.WriteFile(dumpPath, []byte(graphCopy.Serialize(strplan)), 0666)
  554. absPath, _ := filepath.Abs(dumpPath)
  555. log.Printf("Wrote the DAG to %s\n", absPath)
  556. }
  557. }
  558. // Initialize prepares the pipeline for the execution (Run()). This function
  559. // resolves the execution DAG, Configure()-s and Initialize()-s the items in it in the
  560. // topological dependency order. `facts` are passed inside Configure(). They are mutable.
  561. func (pipeline *Pipeline) Initialize(facts map[string]interface{}) error {
  562. if facts == nil {
  563. facts = map[string]interface{}{}
  564. }
  565. if _, exists := facts[ConfigPipelineCommits]; !exists {
  566. var err error
  567. facts[ConfigPipelineCommits], err = pipeline.Commits(false)
  568. if err != nil {
  569. log.Panicf("failed to list the commits: %v", err)
  570. }
  571. }
  572. if val, exists := facts[ConfigPipelineHibernationDistance].(int); exists {
  573. if val < 0 {
  574. log.Panicf("--hibernation-distance cannot be negative (got %d)", val)
  575. }
  576. pipeline.HibernationDistance = val
  577. }
  578. dumpPath, _ := facts[ConfigPipelineDAGPath].(string)
  579. pipeline.resolve(dumpPath)
  580. if dumpPlan, exists := facts[ConfigPipelineDumpPlan].(bool); exists {
  581. pipeline.DumpPlan = dumpPlan
  582. }
  583. if dryRun, exists := facts[ConfigPipelineDryRun].(bool); exists {
  584. pipeline.DryRun = dryRun
  585. if dryRun {
  586. return nil
  587. }
  588. }
  589. for _, item := range pipeline.items {
  590. err := item.Configure(facts)
  591. if err != nil {
  592. return errors.Wrapf(err, "%s failed to configure", item.Name())
  593. }
  594. }
  595. for _, item := range pipeline.items {
  596. err := item.Initialize(pipeline.repository)
  597. if err != nil {
  598. return errors.Wrapf(err, "%s failed to initialize", item.Name())
  599. }
  600. }
  601. return nil
  602. }
  603. // Run method executes the pipeline.
  604. //
  605. // `commits` is a slice with the git commits to analyse. Multiple branches are supported.
  606. //
  607. // Returns the mapping from each LeafPipelineItem to the corresponding analysis result.
  608. // There is always a "nil" record with CommonAnalysisResult.
  609. func (pipeline *Pipeline) Run(commits []*object.Commit) (map[LeafPipelineItem]interface{}, error) {
  610. startRunTime := time.Now()
  611. onProgress := pipeline.OnProgress
  612. if onProgress == nil {
  613. onProgress = func(int, int) {}
  614. }
  615. plan := prepareRunPlan(commits, pipeline.HibernationDistance, pipeline.DumpPlan)
  616. progressSteps := len(plan) + 2
  617. branches := map[int][]PipelineItem{}
  618. // we will need rootClone if there is more than one root branch
  619. var rootClone []PipelineItem
  620. if !pipeline.DryRun {
  621. rootClone = cloneItems(pipeline.items, 1)[0]
  622. }
  623. var newestTime int64
  624. runTimePerItem := map[string]float64{}
  625. commitIndex := 0
  626. for index, step := range plan {
  627. onProgress(index+1, progressSteps)
  628. if pipeline.DryRun {
  629. continue
  630. }
  631. firstItem := step.Items[0]
  632. switch step.Action {
  633. case runActionCommit:
  634. state := map[string]interface{}{
  635. DependencyCommit: step.Commit,
  636. DependencyIndex: commitIndex,
  637. DependencyIsMerge: (index > 0 &&
  638. plan[index-1].Action == runActionCommit &&
  639. plan[index-1].Commit.Hash == step.Commit.Hash) ||
  640. (index < (len(plan)-1) &&
  641. plan[index+1].Action == runActionCommit &&
  642. plan[index+1].Commit.Hash == step.Commit.Hash),
  643. }
  644. for _, item := range branches[firstItem] {
  645. startTime := time.Now()
  646. update, err := item.Consume(state)
  647. runTimePerItem[item.Name()] += time.Now().Sub(startTime).Seconds()
  648. if err != nil {
  649. log.Printf("%s failed on commit #%d (%d) %s\n",
  650. item.Name(), commitIndex+1, index+1, step.Commit.Hash.String())
  651. return nil, err
  652. }
  653. for _, key := range item.Provides() {
  654. val, ok := update[key]
  655. if !ok {
  656. log.Panicf("%s: Consume() did not return %s", item.Name(), key)
  657. }
  658. state[key] = val
  659. }
  660. }
  661. commitTime := step.Commit.Committer.When.Unix()
  662. if commitTime > newestTime {
  663. newestTime = commitTime
  664. }
  665. commitIndex++
  666. case runActionFork:
  667. startTime := time.Now()
  668. for i, clone := range cloneItems(branches[firstItem], len(step.Items)-1) {
  669. branches[step.Items[i+1]] = clone
  670. }
  671. runTimePerItem["*.Fork"] += time.Now().Sub(startTime).Seconds()
  672. case runActionMerge:
  673. startTime := time.Now()
  674. merged := make([][]PipelineItem, len(step.Items))
  675. for i, b := range step.Items {
  676. merged[i] = branches[b]
  677. }
  678. mergeItems(merged)
  679. runTimePerItem["*.Merge"] += time.Now().Sub(startTime).Seconds()
  680. case runActionEmerge:
  681. if firstItem == rootBranchIndex {
  682. branches[firstItem] = pipeline.items
  683. } else {
  684. branches[firstItem] = cloneItems(rootClone, 1)[0]
  685. }
  686. case runActionDelete:
  687. delete(branches, firstItem)
  688. case runActionHibernate:
  689. for _, item := range step.Items {
  690. for _, item := range branches[item] {
  691. if hi, ok := item.(HibernateablePipelineItem); ok {
  692. startTime := time.Now()
  693. err := hi.Hibernate()
  694. if err != nil {
  695. log.Panicf("Failed to hibernate %s: %v\n", item.Name(), err)
  696. }
  697. runTimePerItem[item.Name()+".Hibernation"] += time.Now().Sub(startTime).Seconds()
  698. }
  699. }
  700. }
  701. case runActionBoot:
  702. for _, item := range step.Items {
  703. for _, item := range branches[item] {
  704. if hi, ok := item.(HibernateablePipelineItem); ok {
  705. startTime := time.Now()
  706. err := hi.Boot()
  707. if err != nil {
  708. log.Panicf("Failed to boot %s: %v\n", item.Name(), err)
  709. }
  710. runTimePerItem[item.Name()+".Hibernation"] += time.Now().Sub(startTime).Seconds()
  711. }
  712. }
  713. }
  714. }
  715. }
  716. onProgress(len(plan)+1, progressSteps)
  717. result := map[LeafPipelineItem]interface{}{}
  718. if !pipeline.DryRun {
  719. for index, item := range getMasterBranch(branches) {
  720. if casted, ok := item.(LeafPipelineItem); ok {
  721. result[pipeline.items[index].(LeafPipelineItem)] = casted.Finalize()
  722. }
  723. }
  724. }
  725. onProgress(progressSteps, progressSteps)
  726. result[nil] = &CommonAnalysisResult{
  727. BeginTime: plan[0].Commit.Committer.When.Unix(),
  728. EndTime: newestTime,
  729. CommitsNumber: len(commits),
  730. RunTime: time.Since(startRunTime),
  731. RunTimePerItem: runTimePerItem,
  732. }
  733. return result, nil
  734. }
  735. // LoadCommitsFromFile reads the file by the specified FS path and generates the sequence of commits
  736. // by interpreting each line as a Git commit hash.
  737. func LoadCommitsFromFile(path string, repository *git.Repository) ([]*object.Commit, error) {
  738. var file io.ReadCloser
  739. if path != "-" {
  740. var err error
  741. file, err = os.Open(path)
  742. if err != nil {
  743. return nil, err
  744. }
  745. defer file.Close()
  746. } else {
  747. file = os.Stdin
  748. }
  749. scanner := bufio.NewScanner(file)
  750. var commits []*object.Commit
  751. for scanner.Scan() {
  752. hash := plumbing.NewHash(scanner.Text())
  753. if len(hash) != 20 {
  754. return nil, errors.New("invalid commit hash " + scanner.Text())
  755. }
  756. commit, err := repository.CommitObject(hash)
  757. if err != nil {
  758. return nil, err
  759. }
  760. commits = append(commits, commit)
  761. }
  762. return commits, nil
  763. }