public static void CreatePackage(ServiceDefinition definition, string rootPath, PackageType type, out string standardOutput, out string standardError) { string arguments; arguments = ConstructArgs(definition, rootPath, type); Execute(arguments, out standardOutput, out standardError); }
private static string ConstructArgs(ServiceDefinition serviceDefinition, string rootPath, PackageType type) { string arguments; string rolesArg = ""; string sitesArg = ""; if (serviceDefinition == null) throw new ArgumentNullException("serviceDefinition", string.Format(Resources.InvalidOrEmptyArgumentMessage, "Service definition")); if (string.IsNullOrEmpty(rootPath) || System.IO.File.Exists(rootPath)) throw new ArgumentException(Resources.InvalidRootNameMessage, "rootPath"); if (serviceDefinition.WebRole != null) { foreach (WebRole webRole in serviceDefinition.WebRole) { rolesArg += string.Format(Resources.RoleArgTemplate, webRole.name, rootPath); foreach (Site site in webRole.Sites.Site) { sitesArg += string.Format(Resources.SitesArgTemplate, webRole.name, site.name, rootPath); } } } if (serviceDefinition.WorkerRole != null) { foreach (WorkerRole workerRole in serviceDefinition.WorkerRole) { rolesArg += string.Format(Resources.RoleArgTemplate, workerRole.name, rootPath); } } arguments = string.Format((type == PackageType.Local) ? Resources.CsPackLocalArg : Resources.CsPackCloudArg, rootPath, rolesArg, sitesArg); return arguments; }
internal override void AddRoleToDefinition(ServiceDefinition def, object template) { WebRole webRole = template as WebRole; var toAdd = new WebRole[] { webRole }; if (def.WebRole != null) { def.WebRole = def.WebRole.Concat(toAdd).ToArray(); } else { def.WebRole = toAdd; } }
/// <summary> /// Set the runtime properties for a role /// </summary> /// <param name="definition">The service containing the role</param> /// <param name="roleName">The name of the role to change</param> /// <param name="path">The path to the service</param> /// <param name="version">The version of the runtime to be installed</param> /// <param name="overrideUrl">The value of the override url, if the user wants to opt out of the system</param> /// <returns>true if the settings were successfully changed</returns> public static bool SetRoleRuntime(ServiceDefinition definition, string roleName, CloudProjectPathInfo path, string version = null, string overrideUrl = null) { bool changed = false; Variable[] environment = GetRoleRuntimeEnvironment(definition, roleName); if (version != null) { string filePath = Path.Combine(path.RootPath, roleName, "package.json"); File.WriteAllText(filePath, string.Format(TestResources.ValidPackageJson, "testapp", version)); changed = true; } if (overrideUrl != null) { environment = SetRuntimeEnvironment(environment, Resources.RuntimeOverrideKey, overrideUrl); changed = true; } return changed && ApplyRuntimeChanges(definition, roleName, environment); }
/// <summary> /// Try to get the specified web role from the given definiiton /// </summary> /// <param name="definition">The service definiiton</param> /// <param name="roleName">The name of the role</param> /// <param name="role">output variable where the webRole is returned</param> /// <returns>true if the web role is found in the given definition</returns> private static bool TryGetWebRole(ServiceDefinition definition, string roleName, out WebRole role) { role = definition.WebRole.FirstOrDefault <WebRole>(r => string.Equals(r.name, roleName, StringComparison.OrdinalIgnoreCase)); return(role != null); }
/// <summary> /// Validates that given service definition is valid against list of web/worker roles. Validation steps: /// 1. Make sure that name element /// </summary> /// <param name="actual">Service definition to be checked</param> /// <param name="serviceName">New created service name</param> public static void IsValidServiceDefinition(ServiceDefinition actual, string serviceName) { Assert.AreEqual <string>(serviceName, actual.name); Assert.IsNull(actual.WebRole); Assert.IsNull(actual.WorkerRole); }
public void CreatePackage(ServiceDefinition definition, CloudProjectPathInfo paths, DevEnv type, out string standardOutput, out string standardError) { if (definition == null) { throw new ArgumentNullException( "definition", string.Format(Resources.InvalidOrEmptyArgumentMessage, "Service definition")); } if (string.IsNullOrEmpty(paths.RootPath)) { throw new ArgumentException(Resources.InvalidRootNameMessage, "rootPath"); } // Track the directories that are created by GetOrCreateCleanPath // to avoid publishing iisnode log files so we can delete the temp // copies when we're finished packaging Dictionary<string, string> tempDirectories = new Dictionary<string, string>(); try { string roles = // Get the names of all web and worker roles Enumerable.Concat( definition.WebRole.NonNull().Select(role => role.name), definition.WorkerRole.NonNull().Select(role => role.name)) // Get the name and safe path for each role (i.e., if the // role has files that shouldn't be packaged, it'll be // copied to a temp location without those files) .Select(name => GetOrCreateCleanPath(paths.RolesPath, name, tempDirectories, type)) // Format the role name and path as a role argument .Select(nameAndPath => string.Format(Resources.RoleArgTemplate, nameAndPath.Key, nameAndPath.Value)) // Join all the role arguments together into one .DefaultIfEmpty(string.Empty) .Aggregate(string.Concat); string sites = // Get all of the web roles definition.WebRole.NonNull() // Get all the sites in each role and format them all as // site arguments .SelectMany(role => // Format each site as a site argument role.Sites.Site.Select(site => string.Format( Resources.SitesArgTemplate, role.name, site.name, tempDirectories.GetValueOrDefault(role.name, paths.RolesPath)))) // Join all the site arguments together into one .DefaultIfEmpty(string.Empty) .Aggregate(string.Concat); string args = string.Format( type == DevEnv.Local ? Resources.CsPackLocalArg : Resources.CsPackCloudArg, paths.RootPath, roles, sites); // Run CsPack to generate the package ProcessHelper.StartAndWaitForProcess( new ProcessStartInfo( Path.Combine(AzureSdkBinDirectory, Resources.CsPackExe), args), out standardOutput, out standardError); } finally { // Cleanup any temp directories tempDirectories.Values.ForEach(dir => Directory.Delete(dir, true)); } }
public Dictionary<string, object>[] GetProductsList(ServiceDefinition definition, long startRow, long pageSize, bool isLive, string query) { throw new NotImplementedException(); }
internal void ParseProperties(ServiceDefinition.TorrentPropertiesList ListToParse) { _maximumUploadBytesPerSecond = ListToParse.MaximumUploadRate; _maximumDownloadBytesPerSecond = ListToParse.MaximumDownloadRate; _initialSeeding = ListToParse.InitialSeeding; _useDistributedHashTable = ListToParse.UseDht; _usePeerExchange = ListToParse.UsePeerExchange; _overrideQueueing = ListToParse.OverrideQueueing; _maximumSeedRatio = ListToParse.SeedRatio; _maximumSeedTime = ListToParse.SeedTime; _uploadSlots = ListToParse.UploadSlots; if (_trackers == null) { _trackers = new TrackerCollection(this); } _trackers.ParseTrackers(ListToParse.Trackers); }
public static IEnumerable <KeyValuePair <string, Schema> > GetArmResources(ServiceDefinition serviceDefinition) { return(serviceDefinition.Definitions.Where(defPair => defPair.Value.Extensions?.ContainsKey("x-ms-azure-resource") == true && (bool?)defPair.Value.Extensions["x-ms-azure-resource"] == true)); }
static int Main(string[] args) { try { bool show_help = false; bool show_version = false; bool thunksource = false; string lang = null; var sources = new List <Source>(); string outfile = null; var include_dirs = new List <string>(); string output_dir = "."; var p = new OptionSet() { { "thunksource", "generate thunk source code", v => thunksource = v != null }, { "version", "print program version", v => show_version = v != null }, { "output-dir=", "directory for output", v => output_dir = v }, { "lang=", "language to generate sources for for (only csharp currently supported)", v => lang = v }, { "import=", "input file for use in imports", v => sources.Add(new Source { filename = v, is_import = true }) }, { "I|include-path=", "include path", v => include_dirs.Add(v) }, { "outfile=", "unified output file (csharp only)", v => outfile = v }, { "h|help", "show this message and exit", v => show_help = v != null }, }; try { foreach (var s in p.Parse(args)) { sources.Add(new Source { filename = s, is_import = false }); } } catch (OptionException e) { Console.Write("RobotRaconteurWebGen: fatal error: "); Console.WriteLine(e.Message); Console.WriteLine("Try 'RobotRaconteurWebGen --help' for more information."); return(1); } if (show_help) { ShowHelp(p); return(0); } if (show_version) { ShowVersion(p); return(0); } if (!thunksource) { Console.WriteLine("RobotRaconteurWebGen: fatal error: no command specified"); Console.WriteLine("Try 'RobotRaconteurWebGen --help' for more information."); return(1); } if (sources.Count(x => x.is_import == false) == 0) { Console.WriteLine("RobotRaconteurWebGen: fatal error: no files specified for thunksource"); return(1001); } if (lang != "csharp") { Console.WriteLine("RobotRaconteurWebGen: fatal error: unknown or no language specified"); return(1012); } var robdef_path = Environment.GetEnvironmentVariable("ROBOTRACONTEUR_ROBDEF_PATH"); if (robdef_path != null) { robdef_path = robdef_path.Trim(); var env_dirs = robdef_path.Split(Path.PathSeparator); include_dirs.AddRange(env_dirs); } foreach (var s in sources) { if (!File.Exists(s.filename) && !Path.IsPathFullyQualified(s.filename)) { foreach (var inc in include_dirs) { string s3 = Path.Join(inc, s.filename); if (File.Exists(s3)) { s.filename = s3; break; } } } } foreach (var s in sources) { if (!File.Exists(s.filename)) { Console.WriteLine("RobotRaconteurWebGen: fatal error: input file not found {0}", s.filename); return(1002); } } if (!Directory.Exists(output_dir)) { Console.WriteLine("RobotRaconteurWebGen: fatal error: output director not found {0}", output_dir); return(1003); } foreach (var s in sources) { ServiceDefinition d = null; string def; try { StreamReader sr = new StreamReader(s.filename); def = sr.ReadToEnd(); sr.Close(); } catch (Exception) { Console.WriteLine("RobotRaconteurWebGen: fatal error: could not open file {0}", s.filename); return(1004); } try { d = new ServiceDefinition(); ServiceDefinitionParseInfo parse_info = default(ServiceDefinitionParseInfo); parse_info.RobDefFilePath = s.filename; d.FromString(def, parse_info); string a = d.ToString(); s.full_text = def; s.service_def = d; } catch (ServiceDefinitionParseException ee) { Console.WriteLine("{0}({1}): error: {2}", s.filename, ee.ParseInfo.LineNumber, ee.ShortMessage); return(1005); } } try { ServiceDefinitionUtil.VerifyServiceDefinitions(sources.Select(x => x.service_def).ToDictionary(x => x.Name)); } catch (ServiceDefinitionParseException ee) { Console.WriteLine("{0}({1}): error: {2}", ee.ParseInfo.RobDefFilePath, ee.ParseInfo.LineNumber, ee.ShortMessage); return(1007); } catch (ServiceDefinitionVerifyException ee) { Console.WriteLine("{0}({1}): error: {2}", ee.ParseInfo.RobDefFilePath, ee.ParseInfo.LineNumber, ee.ShortMessage); return(1008); } catch (Exception ee) { Console.WriteLine("RobotRaconteurWebGen: fatal error: could not verify service definition set {0}", ee.Message); return(1009); } if (outfile == null) { foreach (var s in sources) { if (s.is_import) { continue; } try { CSharpServiceLangGen.GenerateFiles(s.service_def, s.full_text, output_dir); } catch (Exception ee) { Console.WriteLine("{0}: error: could not generate thunksource files {1}", s.filename, ee.Message); return(1010); } } return(0); } else { StreamWriter f2; try { f2 = new StreamWriter(outfile); } catch (Exception) { Console.WriteLine("RobotRaconteurWebGen: fatal error: could not open outfile for writing {0}", outfile); return(1015); } using (f2) { CSharpServiceLangGen.GenerateOneFileHeader(f2); foreach (var s in sources) { if (s.is_import) { continue; } try { CSharpServiceLangGen.GenerateOneFilePart(s.service_def, s.full_text, f2); } catch (Exception ee) { Console.WriteLine("{0}: error: could not generate thunksource files {1}", s.filename, ee.Message); return(1010); } } } return(0); } } catch (Exception e) { Console.Write("RobotRaconteurWebGen: error: "); Console.WriteLine(e.Message); return(1); } Console.WriteLine("RobotRaconteurGen: error: unknown internal error"); return(7); }
private void UpdateRoleInstanceEndpoints(ServiceDefinition serviceDefinition, int instanceNumber) { // Sample: //"currentRoleInstance": { // "id": "GSDKAgent_IN_0", // "roleInstanceEndpoints": [ // { // "name": "gametraffic", // "internalPort": 7777, // "externalPort": 31000, // "maxPort": 30099, // "minPort": 30000, // "ipEndPoint": "10.26.114.84:7777", // "publicIpEndPoint": "255.255.255.255:31000", // "protocol": "udp" // }, // { // "name": "Microsoft.WindowsAzure.Plugins.RemoteAccess.Rdp", // "internalPort": 3389, // "externalPort": 3389, // "maxPort": 30099, // "minPort": 30000, // "ipEndPoint": "10.26.114.84:3389", // "publicIpEndPoint": "10.26.114.84:3389", // "protocol": "tcp" // }, // { // "name": "Microsoft.WindowsAzure.Plugins.RemoteForwarder.RdpInput", // "internalPort": 20000, // "externalPort": 3389, // "maxPort": 30099, // "minPort": 30000, // "ipEndPoint": "10.26.114.84:20000", // "publicIpEndPoint": "255.255.255.255:3389", // "protocol": "tcp" // }, // { // "name": "ShouldertapUdp", // "internalPort": 10101, // "externalPort": 30100, // "maxPort": 30099, // "minPort": 30000, // "ipEndPoint": "10.26.114.84:10101", // "publicIpEndPoint": "255.255.255.255:30100", // "protocol": "udp" // }, // { // "name": "TCPEcho", // "internalPort": 10100, // "externalPort": 30000, // "maxPort": 30099, // "minPort": 30000, // "ipEndPoint": "10.26.114.84:10100", // "publicIpEndPoint": "255.255.255.255:30000", // "protocol": "tcp" // } // ] //}, serviceDefinition.CurrentRoleInstance.RoleInstanceEndpoints = new List <RoleInstanceEndpoint>(); IList <PortMapping> portMappings = GetPortMappings(instanceNumber); foreach (PortMapping mapping in portMappings) { string internalServerListeningPort = GetLegacyServerListeningPort(mapping).ToString(); serviceDefinition.CurrentRoleInstance.RoleInstanceEndpoints.Add(new RoleInstanceEndpoint() { // The local ip can be a dummy value. IpEndPoint = $"100.76.124.25:{internalServerListeningPort}", Name = mapping.GamePort.Name, Protocol = mapping.GamePort.Protocol.ToLower(), PublicIpEndPoint = $"{_sessionHostsStartInfo.PublicIpV4Address}:{mapping.PublicPort}", InternalPort = internalServerListeningPort, ExternalPort = mapping.PublicPort.ToString() }); } string hostnameFilePath = Path.Combine(VmConfiguration.GetAssetExtractionFolderPathForSessionHost(instanceNumber, 0), "hostname"); _systemOperations.FileWriteAllText(hostnameFilePath, _sessionHostsStartInfo.FQDN); if (_sessionHostsStartInfo.IpSecCertificate != null) { string ipsecFileNamePath = Path.Combine(VmConfiguration.GetAssetExtractionFolderPathForSessionHost(instanceNumber, 0), "ipsec_certificate_thumbprint"); _systemOperations.FileWriteAllText(ipsecFileNamePath, _sessionHostsStartInfo.IpSecCertificate.Thumbprint); } }
private void SetUpLegacyConfigValues(ServiceDefinition serviceDefinition, string sessionHostId, int instanceNumber, string vmAgentHeartbeatIpAddress) { VmConfiguration.ParseAssignmentId(_sessionHostsStartInfo.AssignmentId, out Guid titleId, out Guid deploymentId, out string region); JsonWorkerRole workerRole = serviceDefinition.JsonWorkerRole; workerRole.NoGSMS = false; // Set the RoleInstanceId to vmId. Games like Activision's Call of Duty depend on this being unique per Vm in a cluster. // In v3, the vmId is globally unique (and should satisfy the requirement). serviceDefinition.CurrentRoleInstance = serviceDefinition.CurrentRoleInstance ?? new CurrentRoleInstance(); serviceDefinition.CurrentRoleInstance.Id = VmConfiguration.VmId; // Not completely necessary, but avoids all VMs reporting the same deploymentId to the game server (and consequently to their lobby service potentially). serviceDefinition.DeploymentId = Guid.NewGuid().ToString("N"); UpdateRoleInstanceEndpoints(serviceDefinition, instanceNumber); if (LegacyTitleHelper.LegacyTitleMappings.TryGetValue(titleId, out LegacyTitleDetails titleDetails)) { workerRole.TitleId = titleDetails.TitleId.ToString(); workerRole.GsiId = titleDetails.GsiId.ToString(); workerRole.GsiSetId = titleDetails.GsiSetId.ToString(); workerRole.ClusterId = GetHostNameFromFqdn(_sessionHostsStartInfo.FQDN); } else { workerRole.TitleId = VmConfiguration.GetPlayFabTitleId(titleId); workerRole.GsiId = deploymentId.ToString(); workerRole.GsiSetId = deploymentId.ToString(); // Some legacy games, such as SunsetOverdrive append "cloudapp.net" to the clusterId value // and try pinging that over the internet (essentially the server is pinging itself over the internet for // health monitoring). Given that the FQDN in PlayFab doesn't necessarily end with cloudapp.net, we fake // this by specifying a dummy value here and editing the etc\hosts file to point dummyValue.cloudapp.net to // the publicIPAddress of the VM (available via environment variable). workerRole.ClusterId = "dummyValue"; } workerRole.GsmsBaseUrl = $"http://{vmAgentHeartbeatIpAddress}:{VmConfiguration.ListeningPort}/v1"; workerRole.SessionHostId = "r601y87miefd5ok8rdlgn-3b5np6glmoj4r24ymsk7gh7yhl-2019999738-wus.GSDKAgent_IN_0.Tenant_0.0"; workerRole.InstanceId = sessionHostId; workerRole.ExeFolderPath = DefaultExePath; workerRole.TenantCount = _sessionHostsStartInfo.Count; workerRole.Location = LegacyAzureRegionHelper.GetRegionString(region); workerRole.Datacenter = workerRole.Location.Replace(" ", string.Empty); workerRole.XassBaseUrl = "https://service.auth.xboxlive.com/service/authenticate"; workerRole.XastBaseUrl = "https://title.auth.xboxlive.com:10443/title/authenticate"; workerRole.XstsBaseUrl = "https://xsts.auth.xboxlive.com/xsts/authorize"; // Legacy Agent wrote it in this format. workerRole.TenantName = $"{instanceNumber,4:0000}"; CertificateDetail ipSecCertificate = _sessionHostsStartInfo.IpSecCertificate ?? _sessionHostsStartInfo.XblcCertificate; if (!string.IsNullOrEmpty(_sessionHostsStartInfo.XblcCertificate?.Thumbprint)) { // Halo GSDK needs both of these to start up properly. workerRole.XblGameServerCertificateThumbprint = _sessionHostsStartInfo.XblcCertificate?.Thumbprint; workerRole.XblIpsecCertificateThumbprint = ipSecCertificate?.Thumbprint; } // Add port mappings in the legacy format. GetLegacyPortMapping(instanceNumber).ToList().ForEach(port => workerRole.SetConfigValue(port.Key, port.Value)); }
/// <summary> /// Populates list of resources, tracked resources and proxy resources /// </summary> private void PopulateResourceTypes(ServiceDefinition serviceDefinition) { this.ResourceModels = ValidationUtilities.GetResourceModels(serviceDefinition).ToList(); this.TrackedResourceModels = ValidationUtilities.GetTrackedResources(this.ResourceModels, serviceDefinition.Definitions).ToList(); this.ProxyResourceModels = this.ResourceModels.Except(this.TrackedResourceModels).ToList(); }
/// <summary> /// Initializes a top level context for rules /// </summary> /// <param name="root"></param> public RuleContext(ServiceDefinition root, Uri file) : this(null) { this.Root = root; this.Value = root; this.File = file; }
public void Write(CodeWriter b, ServiceDefinition serviceDefinition, string accessLevel = "public") { this.Write_Interface(b, serviceDefinition, accessLevel); this.Write_ClientAndServerClass(b, serviceDefinition, accessLevel); }
/// <summary> /// Resolves the service runtimes into downloadable URLs. /// </summary> /// <param name="manifest">The custom manifest file</param> /// <returns>Warning text if any</returns> public string ResolveRuntimePackageUrls(string manifest = null) { ServiceSettings settings = ServiceSettings.Load(Paths.Settings); CloudRuntimeCollection availableRuntimePackages; if (!CloudRuntimeCollection.CreateCloudRuntimeCollection(out availableRuntimePackages, manifest)) { throw new ArgumentException( string.Format(Resources.ErrorRetrievingRuntimesForLocation, settings.Location)); } ServiceDefinition definition = this.Components.Definition; StringBuilder warningText = new StringBuilder(); List <CloudRuntimeApplicator> applicators = new List <CloudRuntimeApplicator>(); if (definition.WebRole != null) { foreach (WebRole role in definition.WebRole.Where(role => role.Startup != null && CloudRuntime.GetRuntimeStartupTask(role.Startup) != null)) { CloudRuntime.ClearRuntime(role); string rolePath = Path.Combine(this.Paths.RootPath, role.name); foreach (CloudRuntime runtime in CloudRuntime.CreateRuntime(role, rolePath)) { CloudRuntimePackage package; runtime.CloudServiceProject = this; if (!availableRuntimePackages.TryFindMatch(runtime, out package)) { string warning; if (!runtime.ValidateMatch(package, out warning)) { warningText.AppendFormat("{0}\r\n", warning); } } applicators.Add(CloudRuntimeApplicator.CreateCloudRuntimeApplicator( runtime, package, role)); } } } if (definition.WorkerRole != null) { foreach (WorkerRole role in definition.WorkerRole.Where(role => role.Startup != null && CloudRuntime.GetRuntimeStartupTask(role.Startup) != null)) { string rolePath = Path.Combine(this.Paths.RootPath, role.name); CloudRuntime.ClearRuntime(role); foreach (CloudRuntime runtime in CloudRuntime.CreateRuntime(role, rolePath)) { CloudRuntimePackage package; runtime.CloudServiceProject = this; if (!availableRuntimePackages.TryFindMatch(runtime, out package)) { string warning; if (!runtime.ValidateMatch(package, out warning)) { warningText.AppendFormat(warning + Environment.NewLine); } } applicators.Add(CloudRuntimeApplicator.CreateCloudRuntimeApplicator(runtime, package, role)); } } } applicators.ForEach <CloudRuntimeApplicator>(a => a.Apply()); this.Components.Save(this.Paths); return(warningText.ToString()); }
/// <summary> /// Validates that given service definition is valid against list of web/worker roles. Validation steps: /// 1. Make sure that name element /// </summary> /// <param name="actual">Service definition to be checked</param> /// <param name="serviceName">New created service name</param> public static void IsValidServiceDefinition(ServiceDefinition actual, string serviceName) { Assert.AreEqual<string>(serviceName, actual.name); Assert.IsNull(actual.WebRole); Assert.IsNull(actual.WorkerRole); }
internal virtual void AddRoleToDefinition(ServiceDefinition serviceDefinition, object template) { Validate.ValidateNullArgument(template, string.Format(Resources.NullRoleSettingsMessage, "service definition")); Validate.ValidateNullArgument(serviceDefinition, Resources.NullServiceDefinitionMessage); }
public ServiceKey(Type serviceType, ServiceDefinition definition) { ServiceType = serviceType; ImplementType = definition.GetImplementType(); }
/// <summary> /// Gets response models returned by operations with given httpVerb /// by default looks at the '200' response /// </summary> /// <param name="httpVerb">operation verb for which to determine the response model</param> /// <param name="serviceDefinition">service definition containing the operations</param> /// <param name="respCode">The response code to look at when fetching models, by default '200'</param> /// <returns>list of model names that are returned by all operations matching the httpVerb</returns> public static IEnumerable <string> GetOperationResponseModels(string httpVerb, ServiceDefinition serviceDefinition, string respCode = "200") { var operations = GetOperationsByRequestMethod(httpVerb, serviceDefinition) .Where(op => op.Responses?.ContainsKey(respCode) == true); return(operations.Select(op => op.Responses[respCode]?.Schema?.Reference?.StripDefinitionPath()) .Where(modelName => !string.IsNullOrEmpty(modelName))); }
/// <summary> /// Returns all operations that match the httpverb (from all paths in service definitions) /// </summary> /// <param name="id">httpverb to check for</param> /// <param name="serviceDefinition">service definition in which to find the operations</param> /// <param name="includeCustomPaths">whether to include the x-ms-paths</param> /// <returns>list if operations that match the httpverb</returns> public static IEnumerable <Operation> GetOperationsByRequestMethod(string id, ServiceDefinition serviceDefinition, bool includeCustomPaths = true) { var pathOperations = SelectOperationsFromPaths(id, serviceDefinition.Paths); if (includeCustomPaths) { pathOperations.Concat(SelectOperationsFromPaths(id, serviceDefinition.CustomPaths)); } return(pathOperations); }
public async ValueTask PostAsync(ServiceDefinition serviceDefinition) { _serviceManagerProvider.ServiceManager.RegisterService(serviceDefinition); await _serviceManagerProvider.SaveChangeAsync(); }
public static bool IsXmsPageableOrArrayTypeResponseOperation(Operation op, ServiceDefinition entity) => (IsXmsPageableResponseOperation(op) || IsArrayTypeResponseOperation(op, entity));
public AuthenticationService(MessageBroker broker, ServiceDefinition serviceDefinition) : base(broker, serviceDefinition) { }
/// <summary> /// Get the list of all ChildTrackedResources along with their immediate parents. /// </summary> /// <param name="serviceDefinition">Service Definition</param> /// <returns>list of child tracked resources</returns> public static IEnumerable <KeyValuePair <string, string> > GetChildTrackedResourcesWithImmediateParent(ServiceDefinition serviceDefinition) { LinkedList <KeyValuePair <string, string> > result = new LinkedList <KeyValuePair <string, string> >(); foreach (KeyValuePair <string, Dictionary <string, Operation> > pathDefinition in serviceDefinition.Paths) { KeyValuePair <string, string> childResourceMapping = GetChildAndImmediateParentResource(pathDefinition.Key, serviceDefinition.Paths, serviceDefinition.Definitions); if (childResourceMapping.Key != null && childResourceMapping.Value != null) { result.AddLast(new LinkedListNode <KeyValuePair <string, string> >(new KeyValuePair <string, string>(childResourceMapping.Key, childResourceMapping.Value))); } } return(result); }
public Dictionary<string, object>[] GetProductsList(ServiceDefinition definition, long startRow, long pageSize, bool isLive, System.Linq.Expressions.Expression<Predicate<Quantumart.QP8.BLL.Repository.ArticleMatching.Models.IArticle>> query) { throw new NotImplementedException(); }
/// <summary> /// For the provided resource model, it gets the operation which matches with ListBySubscription and returns the resource model. /// </summary> /// <param name="resourceModel"></param> /// <param name="definitions"></param> /// <param name="serviceDefinition"></param> /// <returns>Gets the operation which matches with ListBySubscription and returns the resource model.</returns> public static Operation GetListBySubscriptionOperation(string resourceModel, Dictionary <string, Schema> definitions, ServiceDefinition serviceDefinition) { return(GetListByXOperation(resourceModel, definitions, serviceDefinition, listBySidRegEx)); }
/// <summary> /// For the provided resource model, it gets the operation which matches with specified regex and returns the resource model. /// </summary> /// <param name="resourceModel"></param> /// <param name="definitions"></param> /// <param name="serviceDefinition"></param> /// <param name="regEx"></param> /// <returns>Gets the operation which matches with specified regex and returns the resource model.</returns> private static Operation GetListByXOperation(string resourceModel, Dictionary <string, Schema> definitions, ServiceDefinition serviceDefinition, Regex regEx) { return(GetListByOperation(regEx, resourceModel, definitions, serviceDefinition)); }
public static void AreEqualServiceDefinition(ServiceDefinition expected, ServiceDefinition actual) { throw new NotImplementedException(); }
/// <summary> /// For the provided resource model, it gets the operation which matches with specified regex and returns the resource model. /// </summary> /// <param name="regEx"></param> /// <param name="resourceModel"></param> /// <param name="definitions"></param> /// <param name="serviceDefinition"></param> /// <returns>Gets the operation which matches with specified regex and returns the resource model.</returns> private static Operation GetListByOperation(Regex regEx, string resourceModel, Dictionary <string, Schema> definitions, ServiceDefinition serviceDefinition) { IEnumerable <Operation> getOperations = ValidationUtilities.GetOperationsByRequestMethod("get", serviceDefinition); IEnumerable <Operation> operations = getOperations.Where(operation => regEx.IsMatch(operation.OperationId) && IsXmsPageableResponseOperation(operation) && operation.Responses.Any( response => response.Key.Equals("200") && IsArrayOf(response.Value.Schema?.Reference, resourceModel, definitions))); if (operations != null && operations.Count() != 0) { return(operations.First()); } return(null); }
/// <summary> /// Validates that given service definition is valid for a service. Validation steps: /// 1. Validates name element matches serviceName /// 2. Validates web role element has all webRoles with same configuration. /// 3. Validates worker role element has all workerRoles with same configuration. /// </summary> /// <param name="actual">Service definition to be checked</param> /// <param name="serviceName">New created service name</param> public static void IsValidServiceDefinition(ServiceDefinition actual, string serviceName, WebRoleInfo[] webRoles = null, WorkerRoleInfo[] workerRoles = null) { Assert.AreEqual<string>(serviceName, actual.name); if (webRoles != null) { Assert.AreEqual<int>(webRoles.Length, actual.WebRole.Length); int length = webRoles.Length; for (int i = 0; i < length; i++) { Assert.IsTrue(webRoles[i].Equals(actual.WebRole[i])); } } else { Assert.IsNull(actual.WebRole); } if (workerRoles != null) { Assert.AreEqual<int>(workerRoles.Length, actual.WorkerRole.Length); int length = workerRoles.Length; for (int i = 0; i < length; i++) { Assert.IsTrue(workerRoles[i].Equals(actual.WorkerRole[i])); } } else { Assert.IsNull(actual.WorkerRole); } }
/// <summary> /// Validate that the actual role runtime values for the given role match the given expected values /// </summary> /// <param name="definition">The service definition containing the role to validate</param> /// <param name="roleName">The name of the role to validate</param> /// <param name="runtimeUrl">The resolved runtime url for the role</param> /// <param name="overrideUrl">The override url for the role runtime</param> public static void ValidateRoleRuntime(ServiceDefinition definition, string roleName, string runtimeUrl, string overrideUrl) { string actualRuntimeUrl = GetRoleRuntimeUrl(definition, roleName); string actualOverrideUrl = GetRoleRuntimeOverrideUrl(definition, roleName); Assert.IsTrue(VerifySetting(runtimeUrl, actualRuntimeUrl), string.Format( "Actual runtime URL '{0}' does not match expected runtime URL '{1}'", actualRuntimeUrl, runtimeUrl)); Assert.IsTrue(VerifySetting(overrideUrl, actualOverrideUrl), string.Format( "Actual override URL '{0}' does not match expected override URL '{1}'", actualOverrideUrl, overrideUrl)); }
/// <summary> /// Get the startup task environment settings for the given role /// </summary> /// <param name="definition">The definition containign the role</param> /// <param name="roleName">The name of the role</param> /// <returns>The environment settings for the role, or null if the role is not found</returns> private static Variable[] GetRoleRuntimeEnvironment(ServiceDefinition definition, string roleName) { WebRole webRole; if (TryGetWebRole(definition, roleName, out webRole)) { return CloudRuntime.GetRuntimeStartupTask(webRole.Startup).Environment; } WorkerRole workerRole; if (TryGetWorkerRole(definition, roleName, out workerRole)) { return CloudRuntime.GetRuntimeStartupTask(workerRole.Startup).Environment; } return null; }
/// <summary> /// Initializes a new instance of the MessageService class. /// </summary> /// <param name="messageBroker"></param> /// <param name="serviceDefinition"></param> public MessageService(MessageBroker messageBroker, ServiceDefinition serviceDefinition) : base(messageBroker, serviceDefinition) { }
public static IEnumerable <Operation> GetOperationsByRequestMethod(string id, ServiceDefinition serviceDefinition) { return(serviceDefinition.Paths.Values.Select(pathObj => pathObj.Where(pair => pair.Key.ToLower().Equals(id.ToLower()))).SelectMany(pathPair => pathPair.Select(opPair => opPair.Value))); }
/// <summary> /// Apply the specified Variable values to the specified role's startup task environment /// </summary> /// <param name="definition">The service definition containing the role</param> /// <param name="roleName">The name of the role to change</param> /// <param name="environment">The Variables containing the changes</param> /// <returns>true if the variables environment is successfully changed</returns> private static bool ApplyRuntimeChanges(ServiceDefinition definition, string roleName, Variable[] environment) { WebRole webRole; if (TryGetWebRole(definition, roleName, out webRole)) { CloudRuntime.GetRuntimeStartupTask(webRole.Startup).Environment = environment; return true; } WorkerRole workerRole; if (TryGetWorkerRole(definition, roleName, out workerRole)) { CloudRuntime.GetRuntimeStartupTask(workerRole.Startup).Environment = environment; return true; } return false; }
public void CreatePackage(ServiceDefinition definition, CloudProjectPathInfo paths, DevEnv type, string azureSdkBinDirectory, out string standardOutput, out string standardError) { if (definition == null) { throw new ArgumentNullException( "definition", string.Format(Resources.InvalidOrEmptyArgumentMessage, "Service definition")); } if (string.IsNullOrEmpty(paths.RootPath)) { throw new ArgumentException(Resources.InvalidRootNameMessage, "rootPath"); } // Track the directories that are created by GetOrCreateCleanPath // to avoid publishing iisnode log files so we can delete the temp // copies when we're finished packaging Dictionary <string, string> tempDirectories = new Dictionary <string, string>(); try { string roles = // Get the names of all web and worker roles Enumerable.Concat( definition.WebRole.NonNull().Select(role => role.name), definition.WorkerRole.NonNull().Select(role => role.name)) // Get the name and safe path for each role (i.e., if the // role has files that shouldn't be packaged, it'll be // copied to a temp location without those files) .Select(name => GetOrCreateCleanPath(paths.RolesPath, name, tempDirectories, type)) // Format the role name and path as a role argument .Select(nameAndPath => string.Format(Resources.RoleArgTemplate, nameAndPath.Key, nameAndPath.Value)) // Join all the role arguments together into one .DefaultIfEmpty(string.Empty) .Aggregate(string.Concat); string sites = // Get all of the web roles definition.WebRole.NonNull() // Get all the sites in each role and format them all as // site arguments .SelectMany(role => // Format each site as a site argument role.Sites.Site.Select(site => string.Format( Resources.SitesArgTemplate, role.name, site.name, tempDirectories.GetValueOrDefault(role.name, paths.RolesPath)))) // Join all the site arguments together into one .DefaultIfEmpty(string.Empty) .Aggregate(string.Concat); string args = string.Format( type == DevEnv.Local ? Resources.CsPackLocalArg : Resources.CsPackCloudArg, paths.RootPath, roles, sites); if (ProcessUtil == null) { ProcessUtil = new ProcessHelper(); } // Run CsPack to generate the package ProcessUtil.StartAndWaitForProcess(Path.Combine(azureSdkBinDirectory, Resources.CsPackExe), args); standardOutput = ProcessUtil.StandardOutput; standardError = ProcessUtil.StandardError; standardError = GetRightError(standardOutput, standardError, ProcessUtil.ExitCode); } finally { // Cleanup any temp directories tempDirectories.Values.ForEach(dir => Directory.Delete(dir, true)); } }
/// <summary> /// Try to get the specified worker role from the given definiiton /// </summary> /// <param name="definition">The service definiiton</param> /// <param name="roleName">The name of the role</param> /// <param name="role">output variable where the worker role is returned</param> /// <returns>true if the web role is found in the given definition</returns> private static bool TryGetWorkerRole(ServiceDefinition definition, string roleName, out WorkerRole role) { role = definition.WorkerRole.FirstOrDefault<WorkerRole>(r => string.Equals(r.name, roleName, StringComparison.OrdinalIgnoreCase)); return role != null; }
private void WhenATestServiceIsCreatedOrUpdated(ServiceDefinition serviceDefinition, bool startImmediately) { sut.CreateOrUpdateService(serviceDefinition, startImmediately); }
/// <summary> /// Get the override url for the specified role /// </summary> /// <param name="definition">The service definition containing the role</param> /// <param name="roleName">The name of the role</param> /// <returns>The user-specified url of a privately hosted runtime to be insytalled on the role (if any) </returns> public static string GetRoleRuntimeOverrideUrl(ServiceDefinition definition, string roleName) { Variable v = GetRoleRuntimeEnvironment(definition, roleName).FirstOrDefault<Variable>( variable => string.Equals(variable.name, Resources.RuntimeOverrideKey)); return (null == v ? null : v.value); }
public MetaDataObjectBuilder(ServiceDefinition serviceDefinition) { _serviceDefinition = serviceDefinition; }
/// <summary> /// This method supports the infrastructure and is not intended to be used directly from your code. /// </summary> /// <param name="configFolderPaths">Possible configuration file locations.</param> /// <param name="serviceBrowserAvailable">Indicates whether the service browser is avaliable.</param> public void Init(string[] configFolderPaths, bool serviceBrowserAvailable) { _messageBroker = new MessageBroker(this); string servicesConfigFile = null; for (int i = 0; i < configFolderPaths.Length; i++) { servicesConfigFile = Path.Combine(configFolderPaths[i], "services-config.xml"); if (log.IsDebugEnabled) { log.Debug(__Res.GetString(__Res.MessageServer_TryingServiceConfig, servicesConfigFile)); } if (File.Exists(servicesConfigFile)) { break; } } if (servicesConfigFile != null && File.Exists(servicesConfigFile)) { if (log.IsDebugEnabled) { log.Debug(__Res.GetString(__Res.MessageServer_LoadingServiceConfig, servicesConfigFile)); } _servicesConfiguration = ServicesConfiguration.Load(servicesConfigFile); } else { if (log.IsDebugEnabled) { log.Debug(__Res.GetString(__Res.MessageServer_LoadingConfigDefault)); } _servicesConfiguration = ServicesConfiguration.CreateDefault(); } foreach (ChannelDefinition channelDefinition in _servicesConfiguration.Channels) { Type type = ObjectFactory.Locate(FluorineConfiguration.Instance.ClassMappings.GetType(channelDefinition.Endpoint.Class)); if (type != null) { IEndpoint endpoint = ObjectFactory.CreateInstance(type, new object[] { _messageBroker, channelDefinition }) as IEndpoint; if (endpoint != null) { _messageBroker.AddEndpoint(endpoint); } } else { log.Error(__Res.GetString(__Res.Type_InitError, channelDefinition.Class)); } } ChannelDefinition rtmptChannelDefinition = new ChannelDefinition(); rtmptChannelDefinition.Id = RtmptEndpoint.FluorineRtmptEndpointId; IEndpoint rtmptEndpoint = new RtmptEndpoint(_messageBroker, rtmptChannelDefinition); _messageBroker.AddEndpoint(rtmptEndpoint); if (_servicesConfiguration.Factories != null) { foreach (Factory factory in _servicesConfiguration.Factories) { Type type = ObjectFactory.Locate(FluorineConfiguration.Instance.ClassMappings.GetType(factory.Class)); if (type != null) { IFlexFactory flexFactory = ObjectFactory.CreateInstance(type, new object[0]) as IFlexFactory; if (flexFactory != null) { _messageBroker.AddFactory(factory.Id, flexFactory); } } else { log.Error(__Res.GetString(__Res.Type_InitError, factory.Class)); } } } //Add the dotnet Factory _messageBroker.AddFactory(DotNetFactory.Id, new DotNetFactory()); if (serviceBrowserAvailable) { ServiceDefinition serviceConfiguration = _servicesConfiguration.GetServiceByClass("flex.messaging.services.RemotingService"); if (serviceConfiguration != null) { AdapterDefinition adapter = serviceConfiguration.GetAdapterByClass(typeof(Remoting.RemotingAdapter).FullName); if (adapter != null) { InstallServiceBrowserDestinations(serviceConfiguration, adapter); } else { adapter = serviceConfiguration.GetDefaultAdapter(); if (adapter != null) { InstallServiceBrowserDestinations(serviceConfiguration, adapter); } } } } if (_servicesConfiguration.Services.ServiceDefinitions != null) { foreach (ServiceDefinition serviceDefinition in _servicesConfiguration.Services.ServiceDefinitions) { Type type = ObjectFactory.Locate(FluorineConfiguration.Instance.ClassMappings.GetType(serviceDefinition.Class)); //current assembly only if (type != null) { IService service = ObjectFactory.CreateInstance(type, new object[] { _messageBroker, serviceDefinition }) as IService; if (service != null) { _messageBroker.AddService(service); } } else { log.Error(__Res.GetString(__Res.Type_InitError, serviceDefinition.Class)); } } } if (_servicesConfiguration.Services.Includes != null) { foreach (ServiceInclude include in _servicesConfiguration.Services.Includes) { ServiceDefinition serviceDefinition = include.ServiceDefinition; Type type = ObjectFactory.Locate(FluorineConfiguration.Instance.ClassMappings.GetType(serviceDefinition.Class)); //current assembly only if (type != null) { IService service = ObjectFactory.CreateInstance(type, new object[] { _messageBroker, serviceDefinition }) as IService; if (service != null) { _messageBroker.AddService(service); } } else { log.Error(__Res.GetString(__Res.Type_InitError, serviceDefinition.Class)); } } } if (_servicesConfiguration.Security != null) { if (_servicesConfiguration.Security.LoginCommands != null && _servicesConfiguration.Security.LoginCommands.Length > 0) { LoginCommand loginCommand = _servicesConfiguration.Security.GetLoginCommand(LoginCommand.FluorineLoginCommand); if (loginCommand != null) { Type type = ObjectFactory.Locate(FluorineConfiguration.Instance.ClassMappings.GetType(loginCommand.Class)); if (type != null) { ILoginCommand loginCommandObj = ObjectFactory.CreateInstance(type, new object[] { }) as ILoginCommand; _messageBroker.LoginManager.LoginCommand = loginCommandObj; _messageBroker.LoginManager.IsPerClientAuthentication = loginCommand.IsPerClientAuthentication; } else { log.Error(__Res.GetString(__Res.Type_InitError, loginCommand.Class)); } } else { log.Error(__Res.GetString(__Res.Type_InitError, "<<LoginCommand class>>")); } } } InitAuthenticationService(); try { if (FluorineConfiguration.Instance.FluorineSettings.Silverlight.PolicyServerSettings != null && FluorineConfiguration.Instance.FluorineSettings.Silverlight.PolicyServerSettings.Enable) { IResource resource; if (FluorineContext.Current != null) { resource = FluorineContext.Current.GetResource(FluorineConfiguration.Instance.FluorineSettings.Silverlight.PolicyServerSettings.PolicyFile); } else { resource = new FileSystemResource(FluorineConfiguration.Instance.FluorineSettings.Silverlight.PolicyServerSettings.PolicyFile); } if (resource.Exists) { log.Info(__Res.GetString(__Res.Silverlight_StartPS, resource.File.FullName)); _policyServer = new PolicyServer(resource.File.FullName); } else { throw new FileNotFoundException("Policy file not found", FluorineConfiguration.Instance.FluorineSettings.Silverlight.PolicyServerSettings.PolicyFile); } } } catch (Exception ex) { log.Error(__Res.GetString(__Res.Silverlight_PSError), ex); } }
public HttpDataSender(IEventNotifier notifier, ServiceDefinition serviceDefinition, string relativeUri) { _notifier = notifier; _serviceDefinition = serviceDefinition; _relativeUri = relativeUri; }