ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Jenkins Pipeline Stage Dependency Manager

Groovy

Goal -- WPM

Ready
Exercise Algorithm Area
1import java.util.ArrayDeque
2import java.util.ArrayList
3import java.util.HashMap
4import java.util.HashSet
5import java.util.List
6import java.util.Map
7import java.util.Queue
8import java.util.Set
9
10class JenkinsPipelineDependencyManager {
11
12private Map<String, List<String>> graph = new HashMap<>()
13private Map<String, Integer> inDegree = new HashMap<>()
14private Set<String> allStages = new HashSet<>()
15
16/**
17* Adds a stage and its dependencies to the pipeline graph.
18* @param stageName The name of the stage.
19* @param dependsOn A list of stage names that this stage depends on.
20*/
21void addStage(String stageName, List<String> dependsOn) {
22allStages.add(stageName)
23graph.computeIfAbsent(stageName, { new ArrayList<>() })
24inDegree.putIfAbsent(stageName, 0)
25
26if (dependsOn != null) {
27dependsOn.each {
28String dependency ->
29allStages.add(dependency)
30graph.computeIfAbsent(dependency, { new ArrayList<>() }).add(stageName)
31inDegree.put(stageName, inDegree.getOrDefault(stageName, 0) + 1)
32inDegree.putIfAbsent(dependency, 0) // Ensure dependency is in inDegree map
33}
34}
35}
36
37/**
38* Determines the execution order of stages using topological sort.
39* Handles circular dependencies and missing stages.
40* @return A list of stage names in execution order, or null if a circular dependency is detected.
41*/
42List<String> getExecutionOrder() {
43// Initialize in-degrees for all stages, including those only listed as dependencies
44allStages.each {
45stage -> inDegree.putIfAbsent(stage, 0)
46}
47
48Queue<String> queue = new ArrayDeque<>()
49List<String> executionOrder = new ArrayList<>()
50
51// Add all stages with an in-degree of 0 to the queue
52inDegree.each {
53stage, degree ->
54if (degree == 0) {
55queue.offer(stage)
56}
57}
58
59// Process the queue
60while (!queue.isEmpty()) {
61String currentStage = queue.poll()
62executionOrder.add(currentStage)
63
64// For each neighbor of the current stage
65graph.getOrDefault(currentStage, new ArrayList<>()).each {
66String neighbor ->
67inDegree.put(neighbor, inDegree.get(neighbor) - 1)
68// If in-degree becomes 0, add to queue
69if (inDegree.get(neighbor) == 0) {
70queue.offer(neighbor)
71}
72}
73}
74
75// Check for circular dependencies
76if (executionOrder.size() != allStages.size()) {
77// A circular dependency exists or some stages are unreachable/not defined
78// In a real Jenkins pipeline, this would be an error.
79// For this exercise, we return null to indicate failure.
80return null
81}
82
83return executionOrder
84}
85
86/**
87* Checks if a circular dependency exists in the graph.
88* This is an alternative/complementary check to the size comparison in getExecutionOrder.
89* @return true if a circular dependency is detected, false otherwise.
90*/
91boolean hasCircularDependency() {
92// Re-run topological sort logic to detect cycles
93Map<String, Integer> tempInDegree = new HashMap<>(inDegree)
94Queue<String> queue = new ArrayDeque<>()
95int count = 0
96
97tempInDegree.each {
98stage, degree ->
99if (degree == 0) {
100queue.offer(stage)
101}
102}
103
104while (!queue.isEmpty()) {
105String currentStage = queue.poll()
106count++
107
108graph.getOrDefault(currentStage, new ArrayList<>()).each {
109String neighbor ->
110tempInDegree.put(neighbor, tempInDegree.get(neighbor) - 1)
111if (tempInDegree.get(neighbor) == 0) {
112queue.offer(neighbor)
113}
114}
115}
116
117return count != allStages.size()
118}
119
120/**
121* Main method for demonstration.
122*/
123static void main(String[] args) {
124JenkinsPipelineDependencyManager manager = new JenkinsPipelineDependencyManager()
125
126// Example 1: Simple linear dependency
127manager.addStage("Build", null)
128manager.addStage("Test", ["Build"])
129manager.addStage("Deploy", ["Test"])
130
131List<String> order1 = manager.getExecutionOrder()
132println "Order 1: ${order1 ?: 'Circular dependency detected'}"
133
134// Example 2: More complex DAG
135manager = new JenkinsPipelineDependencyManager()
136manager.addStage("Checkout", null)
137manager.addStage("Lint", ["Checkout"])
138manager.addStage("UnitTests", ["Checkout"])
139manager.addStage("IntegrationTests", ["UnitTests"])
140manager.addStage("BuildArtifact", ["Lint", "UnitTests"])
141manager.addStage("DeployToStaging", ["BuildArtifact"])
142manager.addStage("SmokeTests", ["DeployToStaging"])
143manager.addStage("Release", ["SmokeTests"])
144
145List<String> order2 = manager.getExecutionOrder()
146println "Order 2: ${order2 ?: 'Circular dependency detected'}"
147
148// Example 3: Circular dependency
149manager = new JenkinsPipelineDependencyManager()
150manager.addStage("A", ["C"])
151manager.addStage("B", ["A"])
152manager.addStage("C", ["B"])
153
154List<String> order3 = manager.getExecutionOrder()
155println "Order 3: ${order3 ?: 'Circular dependency detected'}"
156
157// Example 4: Stage with no dependencies
158manager = new JenkinsPipelineDependencyManager()
159manager.addStage("Start", null)
160manager.addStage("Middle", ["Start"])
161manager.addStage("End", null)
162
163List<String> order4 = manager.getExecutionOrder()
164println "Order 4: ${order4 ?: 'Circular dependency detected'}"
165
166// Example 5: Missing dependency stage definition (handled by allStages)
167manager = new JenkinsPipelineDependencyManager()
168manager.addStage("Task1", null)
169manager.addStage("Task2", ["Task1", "NonExistentTask"])
170
171List<String> order5 = manager.getExecutionOrder()
172println "Order 5: ${order5 ?: 'Circular dependency detected'}"
173}
174}
Algorithm description viewbox

Jenkins Pipeline Stage Dependency Manager

Algorithm description:

This Groovy code models a Jenkins pipeline's stage dependencies and determines a valid execution order using topological sorting. It represents stages and their `dependsOn` relationships as a directed graph. The algorithm calculates the in-degree of each stage (number of incoming dependencies) and uses a queue to process stages with an in-degree of zero. This process continues until all stages are ordered or a cycle is detected, indicating an invalid pipeline configuration.

Algorithm explanation:

The `JenkinsPipelineDependencyManager` class uses a graph representation where keys are stage names and values are lists of stages that depend on them. The `inDegree` map stores the count of incoming dependencies for each stage. The `addStage` method populates this graph and `inDegree` map. The core logic is in `getExecutionOrder`, which implements Kahn's algorithm for topological sorting. It initializes a queue with all stages having an in-degree of 0. It then iteratively dequeues a stage, adds it to the `executionOrder`, and decrements the in-degree of its dependent stages. If a dependent stage's in-degree becomes 0, it's enqueued. If, after processing, the `executionOrder` size does not match the total number of unique stages (`allStages.size()`), it signifies a circular dependency or unreachable stages, and `null` is returned. The `hasCircularDependency` method provides an explicit check for cycles. Time complexity is O(V + E) where V is the number of stages and E is the number of dependencies. Space complexity is O(V + E) for storing the graph and in-degrees.

Pseudocode:

CLASS JenkinsPipelineDependencyManager:
  graph = map of stageName to list of dependent stages
  inDegree = map of stageName to integer count
  allStages = set of stage names

  FUNCTION addStage(stageName, dependsOn):
    ADD stageName to allStages
    IF stageName not in graph THEN graph[stageName] = empty list
    IF stageName not in inDegree THEN inDegree[stageName] = 0

    IF dependsOn is not null THEN
      FOR EACH dependency IN dependsOn:
        ADD dependency to allStages
        ADD stageName to graph[dependency]
        inDegree[stageName] = inDegree[stageName] + 1
        IF dependency not in inDegree THEN inDegree[dependency] = 0
      END FOR
    END IF
  END FUNCTION

  FUNCTION getExecutionOrder():
    // Ensure all stages have an in-degree entry
    FOR EACH stage IN allStages:
      IF stage not in inDegree THEN inDegree[stage] = 0
    END FOR

    queue = new queue
    executionOrder = new list

    // Initialize queue with stages having 0 in-degree
    FOR EACH stage, degree IN inDegree:
      IF degree == 0 THEN
        ADD stage to queue
      END IF
    END FOR

    // Process queue
    WHILE queue is not empty:
      currentStage = queue.dequeue()
      ADD currentStage to executionOrder

      FOR EACH neighbor IN graph[currentStage]:
        inDegree[neighbor] = inDegree[neighbor] - 1
        IF inDegree[neighbor] == 0 THEN
          ADD neighbor to queue
        END IF
      END FOR
    END WHILE

    // Check for cycles
    IF length(executionOrder) != length(allStages) THEN
      RETURN null // Circular dependency or missing stages
    ELSE
      RETURN executionOrder
    END IF
  END FUNCTION

  FUNCTION hasCircularDependency():
    // Similar logic to getExecutionOrder but just returns true/false
    // ... (implementation omitted for brevity) ...
  END FUNCTION

  FUNCTION main(args):
    // ... (demonstration code) ...
  END FUNCTION
END CLASS