File: generate-llbuild-manifest

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (275 lines) | stat: -rwxr-xr-x 11,417 bytes parent folder | download
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
#!/usr/bin/env python

#Example 1 (Small-Manifest)
#./generate-llbuild-manifest -levelWidths 1,2,4,8,1 -manifestPath generated-manifest.llbuild -expectedLLBuildOutputPath expectedOutput
#llbuild buildsystem build -f generated-manifest.llbuild > actualOutput
#diff <(sort expectedOutput) <(sort actualOutput)

#Example 2 (Large-Manifest) 
#./generate-llbuild-manifest -levelWidths 100,2000,4000,8000,4000,2000,100,1 -inputDensity 5 -maxAdditionalInputs 20 -manifestPath large-generated-manifest.llbuild -expectedLLBuildOutputPath expectedOutputFromLargeManifest
#llbuild buildsystem build -f large-generated-manifest.llbuild > actualOutputFromLargeManifest
#diff <(sort expectedOutputFromLargeManifest) <(sort actualOutputFromLargeManifest)

#Example 3 (Randomized-Manifest)
#./generate-llbuild-manifest -minWidth 3 -maxWidth 6 -minDepth 5 -maxDepth 10 -inputDensity 5 -maxAdditionalInputs 20 -manifestPath randomized-manifest.llbuild -expectedLLBuildOutputPath expectedOutputFromRandomizedManifest
#llbuild buildsystem build -f randomized-manifest.llbuild > actualOutputFromRandomizedManifest
#diff <(sort expectedOutputFromRandomizedManifest) <(sort actualOutputFromRandomizedManifest)

import sys
import argparse
import uuid
import random

class Command:
  def __init__(self, name, index, inputList):
    self.name = name
    self.outputFile = name
    self.index = index
    self.inputList = inputList
    self.args = ""
    self.hasDependantCommand = False

  def setupArgs(self):
    if not self.inputList:
      self.args = "echo " + self.name + " > " + self.outputFile
    else:
      self.args = "echo " + self.name + " > " + self.outputFile + " && " + "cat " + " ".join(input for input in self.inputList) + " >> " + self.outputFile

  def addNewInput(self, newInput):
    self.inputList.append(newInput)

class LLBuildManifest:
  def __init__(self, manifestPath, expectedLLBuildOutputPath, clientName, clientVersion, density, maxAdditionalInputs=sys.maxsize, minDepth = -1, maxDepth = -1, minWidth = -1, maxWidth = -1, levelWidths = []):
    print("Writing llbuild manifest to " + manifestPath)

    try:
      self.manifestFile = open(manifestPath, 'w+')
    except:
      print("Failed to open manifest file at " + manifestPath)
      raise Exception

    print("Writing expected llbuild results to " + expectedLLBuildOutputPath)
    try:
      self.expectedLLBuildOutputFile = open(expectedLLBuildOutputPath, 'w+')
    except:
      print("Failed to open expected llbuild file at " + expectedLLBuildOutputPath)
      raise Exception

    self.nextCommandID = 0
    
    self.levelWidths = levelWidths
    self.setupLevelWidths(minDepth, maxDepth, minWidth, maxWidth)

    self.commands = []
    self.clientName = clientName
    self.clientVersion = clientVersion
    self.density = density
    self.maxAdditionalInputs = maxAdditionalInputs
    

  def getNodeID(self):
    nextCommandID = self.nextCommandID
    self.nextCommandID+=1
    return nextCommandID

  def writeLine(self, newStr, indentLevel):
    self.manifestFile.write((" " * indentLevel * 2) + newStr + '\n')

  def writeCommandToManifest(self, command):
    self.writeLine(command.name + ":", indentLevel=1)
    self.writeLine("tool: shell", indentLevel=2)
    self.writeLine("inputs: [" + ", ".join('"' + x + '"' for x in command.inputList) + "]", indentLevel=2)
    self.writeLine("outputs: " + '["' + command.outputFile + '"]', indentLevel=2)
    self.writeLine("args: " + command.args, indentLevel=2)

  #This tool currently only uses shell commands, this method needs to be made more robust if other commands are implemented.
  def writeCommandToExpectedResults(self, command):
    self.expectedLLBuildOutputFile.write("/bin/sh -c '" + command.args + "'\n")

  #Determines how many commands there will be per level in the graph.
  def setupLevelWidths(self, minDepth, maxDepth, minWidth, maxWidth):
    if not self.levelWidths:
      depth = random.randint(minDepth, maxDepth)
      
      if minDepth < 0 or maxDepth < 0 or minWidth < 0 or maxWidth < 0:
        print("ERROR: Missing necessary arguments for building the manifest or one of parameters was unexpectedly less than zero. Please provide -minWidth <INT>, -maxWidth <INT>, -minDepth <INT>, -maxDepth <INT> OR -levelWidths <LIST>.")
        raise Exception

      for levelIndex in range(depth-1):
        width = random.randint(minWidth, maxWidth)
        self.levelWidths.append(width)

      #The last level can only have one command, as only one target is created.
      self.levelWidths.append(1)

    if self.levelWidths[len(self.levelWidths)-1] != 1:
      print("ERROR: Last LevelWidths Index must be set to 1 as there can only be one default target.")
      raise Exception

    print("Level widths: %s" % self.levelWidths)
  
  def generateBuildGraph(self):
    print("Generating Build Graph")
    
    self.writeLine("client:", indentLevel=0)
    self.writeLine("name: " + self.clientName, indentLevel=1)
    self.writeLine("version: " + self.clientVersion, indentLevel=1)

    self.writeLine("targets:", 0)
    self.writeLine('"": [root]', 1)

    self.writeLine("commands:", indentLevel=0)
    
    currentCommands = []
    for levelIndex in range(len(self.levelWidths)):
      currentCommands = self.createCommandsAtLevel(levelIndex, previousCommandLevel=currentCommands)
      self.commands.extend(currentCommands)

  def createCommandsAtLevel(self, currentLevelIndex, previousCommandLevel):
    currentLevelCommands = []

    if previousCommandLevel:
      minPreviousLevelCommandIndex = previousCommandLevel[0].index
      maxPreviousLevelCommandIndex = previousCommandLevel[len(previousCommandLevel)-1].index

    #Create New Command
    for commandIndex in range(self.levelWidths[currentLevelIndex]):
      inputList = []

      #Setup Inputs/Dependencies as long as the loop is not on the first or last level.
      if previousCommandLevel and len(self.levelWidths)-1 != currentLevelIndex:
        neighborCommand = random.choice(previousCommandLevel)
        availableCommandCount = len(self.commands) - 1
        
        inputCount = random.randint(0, int(availableCommandCount * (self.density/100)))
        inputCount = inputCount if inputCount <= self.maxAdditionalInputs else self.maxAdditionalInputs

        dependencyCommands = self.getDependencyCommands(inputCount, neighborCommand.index)
        dependencyCommands.append(neighborCommand)

        #Mark all commands the current command is dependant on, to keep track of who has a dependant command.
        for dependencyCommand in dependencyCommands:
          if dependencyCommand.index >= minPreviousLevelCommandIndex and dependencyCommand.index <= maxPreviousLevelCommandIndex: 
            previousCommandLevel[dependencyCommand.index - minPreviousLevelCommandIndex].hasDependantCommand = True
          
          inputList.append(dependencyCommand.outputFile)

      if len(self.levelWidths)-1 != currentLevelIndex:
        newCommandName = str(currentLevelIndex) + "-" + str(commandIndex)
      else:
        newCommandName = "root"

      newCommand = Command(newCommandName, self.getNodeID(), inputList)
      currentLevelCommands.append(newCommand)

    #Parse previous level to ensure all it's commands are in the current level's input lists.
    for command in previousCommandLevel:
      if not command.hasDependantCommand:
        neighborCommand = random.choice(currentLevelCommands)
        neighborCommand.addNewInput(command.outputFile)
    
    
    for command in currentLevelCommands:
      command.setupArgs()
      self.writeCommandToManifest(command)
      self.writeCommandToExpectedResults(command)
    
    return currentLevelCommands

  #Selects commands for the new command's input list.
  def getDependencyCommands(self, inputCount, skipCommandWithIndex):
    commandInputs = []
    foundDuplicateCommand = False

    for command in random.sample(self.commands, inputCount + 1):
      if command.index != skipCommandWithIndex:
        commandInputs.append(command)
      else:
        foundDuplicateCommand = True

    if foundDuplicateCommand == False:
      del commandInputs[random.randint(0, len(commandInputs)-1)]

    return commandInputs

#Collect Args
parser = argparse.ArgumentParser()

parser.add_argument("-manifestPath", dest="manifestPath",
  help="Path to write manifest to. Defaults to '/tmp/llbuildmanifest-' + random hash + '.llbuild.'", 
  default="/tmp/llbuildmanifest-" + uuid.uuid4().hex + ".llbuild")

parser.add_argument("-expectedLLBuildOutputPath", dest="expectedLLBuildOutputPath",
  help="Path to write llbuild's expected output to. Defaults to '/tmp/expectedResults-' + random hash + '.llbuild.' Please make sure to sort when diffing with actual llbuild output", 
  default="/tmp/expected-llbuild-results-" + uuid.uuid4().hex + ".llbuild")

parser.add_argument("-clientName", dest="clientName",
  help="The name of the client. Default value is 'basic.'",
  default="basic")

parser.add_argument("-clientVersion", dest="clientVersion",
  help="The version of the client. Default value is 0.",
  default="0")

parser.add_argument("-levelWidths", dest="levelWidths",
  help="Specify the exact number of levels, and width for each level. The last level must be one as there can only be one default target. Overrides minDepth, maxDepth, minWidth, and maxWidth. i.e: -levelWidths 1,2,4,8,16,1.",
  default="")

parser.add_argument("-minDepth", dest="minDepth",
  help="The minimum depth of the bipartite graph.",
  default="-1")

parser.add_argument("-maxDepth", dest="maxDepth",
  help="The maximum depth of the bipartite graph.",
  default="-1")

parser.add_argument("-minWidth", dest="minWidth",
  help="The minimum width of the graph - determines how many build tasks will occur in parallel.",
  default="-1")

parser.add_argument("-maxWidth", dest="maxWidth",
  help="The maximum width of the graph - determines how many build tasks will occur in parallel.",
  default="-1")

parser.add_argument("-inputDensity", dest="density",
  help="The percentage of additional inputs to add after constraints have been met.",
  default="10")

parser.add_argument("-maxAdditionalInputs", dest="maxAdditionalInputs",
  help="The maximum number of dependencies possible for a node after meeting constraints.",
  default=sys.maxsize)

args = parser.parse_args()

if float(args.density) > 100:
  sys.exit("Invalid density amount. Should be from 1 to 100")

try:
  if args.levelWidths != "":
    if args.minDepth != "-1" or args.maxDepth != "-1" or args.minWidth != "-1" or args.maxWidth != "-1":
      print("WARNING: Level Width will override any width/depth parameters")

    manifest = LLBuildManifest(args.manifestPath, 
      args.expectedLLBuildOutputPath,
      args.clientName,
      args.clientVersion,
      float(args.density),
      maxAdditionalInputs=int(args.maxAdditionalInputs),
      levelWidths=[int(levelWidth) for levelWidth in args.levelWidths.split(",")])

  else:
    manifest = LLBuildManifest(args.manifestPath,
      args.expectedLLBuildOutputPath,
      args.clientName,
      args.clientVersion,
      float(args.density),
      maxAdditionalInputs=int(args.maxAdditionalInputs),
      minDepth=int(args.minDepth), 
      maxDepth=int(args.maxDepth), 
      minWidth=int(args.minWidth), 
      maxWidth=int(args.maxWidth))
except:
  sys.exit("ERROR: Manifest Generation failed in setup")

manifest.generateBuildGraph()