pipeline.go 30 KB

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