chr
2026-04-05 fe750b791d5b517cc4e9bc8e99a9a75139a0cfba
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
//            Copyright Keysight Technologies 2012-2019
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, you can obtain one at http://mozilla.org/MPL/2.0/.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
 
namespace OpenTap
{
    /// <summary>
    /// This class represents a resource in a dependency tree, and contains lists of the resources it depends on.
    /// </summary>
    [DebuggerDisplay("{Depender} : {Resource}")]
    internal class ResourceNode : IResourceReferences
    {
        /// <summary>
        /// The resource this node represents.
        /// </summary>
        public IResource Resource { get; set; }
 
        /// <summary> The property that references this resource. </summary>
        public IMemberData Depender { get; }
 
        /// <summary>
        /// The resources that this node depends on. These are marked with <see cref="ResourceOpenAttribute"/>.
        /// </summary>
        internal readonly List<IResource> WeakDependencies;
        /// <summary>
        /// The resources that this node depends on. These will be opened before this nodes resource.
        /// </summary>
        internal readonly List<IResource> StrongDependencies;
 
        /// <summary>
        /// TestSteps (or other IResources) that uses this resource. These are the reason this resources needs to be opened when running a TestPlan.
        /// </summary>
        public List<ResourceReference> References { get; } = new List<ResourceReference>();
 
        internal ResourceNode(IResource resource)
        {
            this.Resource = resource;
            this.WeakDependencies = new List<IResource>();
            this.StrongDependencies = new List<IResource>();
        }
 
        internal ResourceNode(IResource resource, IMemberData prop, IEnumerable<IResource> weakDeps, IEnumerable<IResource> strongDeps)
        {
            this.Resource = resource;
            this.Depender = prop;
            this.WeakDependencies = weakDeps.ToList();
            this.StrongDependencies = strongDeps.ToList();
        }
    }
 
 
    internal class ResourceDependencyAnalyzer
    {
        private static TraceSource Log = OpenTap.Log.CreateSource("Dependency Analyzer");
 
        private struct ResourceDep
        {
            public override bool Equals(object obj)
            {
                if (obj is ResourceDep other)
                    return other.Behavior == Behavior && other.Resource == Resource &&
                           other.Depender == Depender;
                return false;
            }
 
            public override int GetHashCode() => Behavior.GetHashCode() * 3120732 + 
                                                 (Resource?.GetHashCode() ?? 73289132) * 134017414 +
                                                 (Depender?.GetHashCode() ?? 321312) * 730921632;
 
            public readonly ResourceOpenBehavior Behavior;
            public readonly IResource Resource;
            public readonly IMemberData Depender; // this is important in case the resource is null
 
            public ResourceDep(ResourceOpenBehavior behavior, IResource resource, IMemberData dep)
            {
                this.Behavior = behavior;
                this.Resource = resource;
                this.Depender = dep;
            }
 
            public ResourceDep(IResource resource)
            {
                Depender = null;
                this.Resource = resource;
                Behavior = ResourceOpenBehavior.Before;
            }
        }
 
        private ResourceDep FilterProps(IResource o, IMemberData pi)
        {
            var behavior = ResourceOpenBehavior.Before;
            var attr = pi.GetAttribute<ResourceOpenAttribute>();
            if (attr != null) behavior = attr.Behavior;
 
            return new ResourceDep(behavior, o, pi);
        }
 
        ResourceDep[] getManyResources<T>(T[] steps)
        {
            if (steps.Length == 0)
                return Array.Empty<ResourceDep>();
 
            var result = new HashSet<ResourceDep>();
            TestStepExtensions.GetObjectSettings<IResource, T, ResourceDep>(steps, true, FilterProps, result);
            result.RemoveWhere(dep => dep.Behavior == ResourceOpenBehavior.Ignore);
            return result.ToArray();
            
        }
 
        private IEnumerable<ResourceDep> GetResources<T>(T Step)
        {
            if (Step == null)
                return Array.Empty<ResourceDep>();
            return getManyResources(new[] { Step });
        }
 
        private ResourceNode Analyze(ResourceDep resource)
        {
            var resources = GetResources(resource.Resource);
            return new ResourceNode(resource.Resource,resource.Depender, 
                weakDeps: resources.Where(x => x.Behavior == ResourceOpenBehavior.InParallel).Select(x => x.Resource), 
                strongDeps: resources.Where(x => x.Behavior == ResourceOpenBehavior.Before).Select(x => x.Resource)
                );
        }
 
        private List<ResourceNode> GetResourceTree(ICollection<ResourceDep> resources)
        {
            Queue<ResourceDep> allResources = new Queue<ResourceDep>(resources);
            HashSet<ResourceDep> knownNodes = new HashSet<ResourceDep>();
            List<ResourceNode> allNodes = new List<ResourceNode>();
 
            ResourceDep x;
            while (allResources.Count > 0)
            {
                x = allResources.Dequeue();
 
                if (x.Resource == null)
                {
                    if (knownNodes.Any(k => k.Resource == x.Resource && k.Depender == x.Depender))
                        continue;
                }
                else
                {
                    if (knownNodes.Any(k => k.Resource == x.Resource))
                        continue;
                }
                knownNodes.Add(x);
 
                var newNode = Analyze(x);
                allNodes.Add(newNode);
 
                if (x.Resource != null)
                {
                    List<IResource> newNodes = newNode.WeakDependencies.Concat(newNode.StrongDependencies).ToList();
                    foreach (IResource node in newNodes.Except(knownNodes.Select(k => k.Resource)))
                        allResources.Enqueue(new ResourceDep(node));
                }
            }
 
            return allNodes;
        }
 
        private void ExpandTree(List<ResourceNode> nodes)
        {
            var lut = nodes.Where(x => x.Resource != null).ToDictionary(x => x.Resource, x => x);
 
            bool changed;
            do
            {
                changed = false;
 
                foreach (var n in nodes)
                {
                    if (n == null) continue;
                    var newDeps = n.StrongDependencies.Where(x => x != null)
                        .SelectMany(x => lut[x].StrongDependencies.Concat(lut[x].WeakDependencies))
                        .Except(n.StrongDependencies)
                        .ToArray();
                    if (newDeps.Length > 0)
                    {
                        changed = true;
                        n.StrongDependencies.AddRange(newDeps);
                    }
                }
            }
            while (changed);
        }
 
        #region Strongly connected component algorithm
        // Can be used to find all strongly connected components(circular references) in the graph made up of the resources and the dependencies between them.
        // Implemented based on pseudo code from here: https://en.wikipedia.org/w/index.php?title=Tarjan%27s_strongly_connected_components_algorithm&oldid=774903237
        private class Vertex
        {
            internal int index, lowlink;
            internal bool onStack;
            internal ResourceNode node;
        }
 
        private void StrongConnect(Vertex v, Dictionary<IResource, Vertex> V, Stack<Vertex> S, List<List<IResource>> sccs, ref int index)
        {
            v.index = index;
            v.lowlink = index;
            index++;
            S.Push(v);
            v.onStack = true;
 
            // For all edges (v->w)
            foreach (var w in v.node.StrongDependencies.Select(n => V[n]))
            {
                if (w.index == -1)
                {
                    StrongConnect(w, V, S, sccs, ref index);
                    v.lowlink = Math.Min(v.lowlink, w.lowlink);
                }
                else if (w.onStack)
                {
                    v.lowlink = Math.Min(v.lowlink, w.index);
                }
            }
 
            if (v.lowlink == v.index)
            {
                List<IResource> scc = new List<IResource>();
                Vertex w;
                do
                {
                    w = S.Pop();
                    w.onStack = false;
                    scc.Add(w.node.Resource);
                }
                while (v != w);
 
                if (scc.Count > 1)
                    sccs.Add(scc);
            }
        }
 
        private List<List<IResource>> FindStronglyConnectedComponents(List<ResourceNode> tree)
        {
            List<List<IResource>> sccs = new List<List<IResource>>();
 
            var V = tree.Where(n => n.Resource != null).ToDictionary(n => n.Resource, n => new Vertex { index = -1, lowlink = -1, node = n });
            var S = new Stack<Vertex>();
 
            int index = 0;
 
            foreach (var v in V.Values)
                if (v.index == -1)
                    StrongConnect(v, V, S, sccs, ref index);
 
            return sccs;
        }
        #endregion
 
        /// <summary>
        /// Finds all IResource properties on a list of references. The references can be any class derived from ITapPlugin, such as ITestStep or IResource.
        /// If a reference supplied in the <paramref name="references"/> list is a IResource itself it will be added to the resulting list.
        /// </summary>
        internal List<ResourceNode> GetAllResources(object[] references, out bool errorDetected)
        {
            errorDetected = false;
 
            ResourceDep[] stepResources = getManyResources(references);
            var resourceDeps = new List<ResourceDep>(stepResources);
            foreach (var reference in references)
            {
                if(reference is IResource res)
                    resourceDeps.Add(new ResourceDep(res));
            }
            List<ResourceNode> tree = GetResourceTree(resourceDeps);
 
            ExpandTree(tree);
 
            // Check that no resources have direct references to itself.
            foreach (var scc in tree.Where(x => x.StrongDependencies.Any(dep => dep == x.Resource)))
            {
                foreach (var dep in scc.StrongDependencies)
                {
                    if (dep == scc.Resource)
                    {
                        errorDetected = true;
                        Log.Error("Resource is referencing itself: {0}", scc.Resource);
                        break;
                    }
                }
                
            }
 
            // Figure out if all resources has their resource properties set
            foreach(var leaf in tree)
            {
                if(leaf.StrongDependencies.Any(s => s is null))
                {
                    errorDetected = true;
                    Log.Error($"Resource setting not set on resource {leaf.Resource}. Please configure or disable the resource.");
                }
            }
 
            if (errorDetected) // If any resources has resource properties which is not set, let's return early, because FindStronglyConntectedComponents method below will throw a confusing error in this case.
                return tree;
 
            // Figure out if there are circular references, and list the circular references in an exception each.
            var sccs = FindStronglyConnectedComponents(tree);
            if (sccs.Count > 0)
            {
                errorDetected = true;
 
                foreach (var scc in sccs)
                    Log.Error(string.Format("Circular references between resources: {0}", string.Join(",", scc.Select(res => res.Name))));
            }
 
            //Add users of resources
            foreach (var r in references)
            {
                TestStepExtensions.GetObjectSettings<IResource, object, ResourceNode>(r, true, (res, prop) =>
                {
                    var nodes = tree.Where(n => n.Resource == res);
                    if (nodes.Count() > 1)
                    {
                        // Normally we would expect that the tree only contains one node representing each resource. 
                        // In case of null resources however, we want one node per property, such that ILockManager.BeforeOpen()
                        // has a chance to set each property to a different resource instance.
                        if (res != null)
                            throw new Exception($"Duplicate entry for Resource '{res.Name}' in tree.");
                        nodes = nodes.Where(n => n.Depender == prop);
                    }
 
                    var nodeRepresentingResource = nodes.FirstOrDefault();
                    if (nodeRepresentingResource != null)
                        nodeRepresentingResource.References.Add(new ResourceReference(r, prop));
                    return nodeRepresentingResource;
                }, new HashSet<ResourceNode>());
            }
 
            return tree;
        }
    }
}