RecipeComponentFactory.cs
1 using System.Globalization; 2 using Utils; 3 4 namespace KubernetesWorkflow.Recipe 5 { 6 public class RecipeComponentFactory 7 { 8 private readonly NumberSource internalNumberSource = new NumberSource(8080); 9 private static readonly NumberSource externalNumberSource = new NumberSource(30000); 10 private static int[] usedExternalPorts = Array.Empty<int>(); 11 12 public void Update(K8sController controller) 13 { 14 usedExternalPorts = controller.GetUsedExternalPorts(); 15 } 16 17 public Port CreateInternalPort(string tag, PortProtocol protocol) 18 { 19 return new Port(internalNumberSource.GetNextNumber(), tag, protocol); 20 } 21 22 public Port CreateExternalPort(int number, string tag, PortProtocol protocol) 23 { 24 if (usedExternalPorts.Contains(number)) throw new Exception($"External port number {number} is already in use by the cluster."); 25 return new Port(number, tag, protocol); 26 } 27 28 public Port CreateExternalPort(string tag, PortProtocol protocol) 29 { 30 while (true) 31 { 32 var number = externalNumberSource.GetNextNumber(); 33 if (!usedExternalPorts.Contains(number)) 34 { 35 return new Port(number, tag, protocol); 36 } 37 } 38 } 39 40 public EnvVar CreateEnvVar(string name, int value) 41 { 42 return CreateEnvVar(name, value.ToString(CultureInfo.InvariantCulture)); 43 } 44 45 public EnvVar CreateEnvVar(string name, string value) 46 { 47 return new EnvVar(name, value); 48 } 49 } 50 }