pipeline.go 27 KB

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