Exemplo n.º 1
0
        private dynamic ResolveByRegistry(ContainerRegistry registry, HashSet <Type> previousGrahpNodes)
        {
            if (previousGrahpNodes.Count == 0) //Root graph
            {
                perGraphCache.Clear();
            }

            if (registry == null)
            {
                return(null);
            }

            switch (registry.Method)
            {
            case ActivationMethod.PerContainer:
                return(ResolvePerContainer(registry, previousGrahpNodes));

            case ActivationMethod.PerCall:
                return(ResolvePerCall(registry, previousGrahpNodes));

            case ActivationMethod.PerResolutionGraph:
                return(ResolvePerGraph(registry, previousGrahpNodes));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Exemplo n.º 2
0
        private dynamic ResolvePerCall(ContainerRegistry registry, HashSet <Type> previousGrahpNodes)
        {
            ConstructorInfo constructor = GetValidConstructor(registry.Type);



            previousGrahpNodes.Add(registry.Type);



            var parameters = constructor.GetParameters();

            List <object> args = new List <object>();

            foreach (var p in parameters)
            {
                if (previousGrahpNodes.Contains(p.ParameterType))
                {
                    throw new Exception($"Error resolving type {registry.Type}, it has a cyclic dependency to his constructor's parameter {p.Name}:{p.ParameterType}");
                }
                var containedType = p.ParameterType.GenericTypeArguments.FirstOrDefault();
                var arg           = p.ParameterType.GetInterface("System.Collections.IEnumerable") == null
                    ? ResolveByType(p.ParameterType, previousGrahpNodes)
                    : ConvertList(ResolveAllByType(containedType, previousGrahpNodes), p.ParameterType);

                args.Add(arg);
            }


            previousGrahpNodes.Remove(registry.Type);
            return(Activator.CreateInstance(registry.Type, args.ToArray()));
        }
        public void Context_Inherits_Parent_Injector()
        {
            AddRootToStage();

            parentContext
            .Install(typeof(SupportParentFinderExtension))
            .Install(typeof(TestSupportViewStateWatcherExtension))
            .Install(typeof(ModularityExtension))
            .Configure(new ContextView(parentView));

            childContext
            .Install(typeof(TestSupportViewStateWatcherExtension))
            .Install(typeof(ModularityExtension))
            .Install(typeof(SupportParentFinderExtension))
            .Configure(new ContextView(childView));

            ContainerRegistry cr = new ContainerRegistry();

            cr.SetParentFinder(new SupportParentFinder());

            parentContext.injector.Map(typeof(ContainerRegistry)).ToValue(cr);
            childContext.injector.Map(typeof(ContainerRegistry)).ToValue(cr);

            cr.AddContainer(parentView);
            cr.AddContainer(childView);

            root.AddChild(parentView);
            parentView.AddChild(childView);

            Assert.That(childContext.injector.parent, Is.EqualTo(parentContext.injector));
        }
Exemplo n.º 4
0
        /// <summary>
        /// OnMountBaseGame is called when Rime is requesting to mount a Frostbite Engine game
        /// This function must check the version number, and ignore if they don't match or handle the mounting
        /// </summary>
        /// <param name="p_RimeMessage">MountBaseGameMessage</param>
        private void OnMountBaseGame(RimeMessage p_RimeMessage)
        {
            var s_Message = (MountBaseGameMessage)p_RimeMessage;

            // Version check
            if (s_Message.Engine != EngineType.Frostbite2013_2)
            {
                return;
            }

            // Load the necessary bindings.
            ContainerRegistry.ClearRegistry();

            // TODO: Mounting bindings per-game (should this be done in another plugin?)

            // Create our new managers to handle Frostbite 2013.2 content
            Mount2014_3Branch();

            // Figure out the layout of the game
            LayoutManager.DiscoverLayout();

            // Mount the Content Addressable Storage
            ContentManager.MountBaseContent();

            // Mount the superbundles
            SuperbundleManager.MountSuperbundles();
        }
Exemplo n.º 5
0
 private dynamic ResolvePerGraph(ContainerRegistry registry, HashSet <Type> previousGrahpNodes)
 {
     if (!perGraphCache.ContainsKey(registry.Type))
     {
         perGraphCache.Add(registry.Type, ResolvePerCall(registry, previousGrahpNodes));
     }
     return(perGraphCache[registry.Type]);
 }
Exemplo n.º 6
0
        public void SetUpTestEnvironment()
        {
            ConfigureBddfy();
            _server = new InMemoryApiServer();
            var container = BuildContainer();

            ContainerRegistry.Register(container);
            _server.Start();
        }
Exemplo n.º 7
0
    static Task <int> Main() => Deployment.RunAsync(async() => {
        // Create a private DigitalOcean Container Registry.
        var registry = new ContainerRegistry("my-reg", new ContainerRegistryArgs
        {
            SubscriptionTierSlug = "starter"
        });

        // Get registry info (creds and endpoint).
        var imageName     = Output.Format($"{registry.Endpoint}/myapp");
        var registryCreds = new ContainerRegistryDockerCredentials("my-reg-creds",
                                                                   new ContainerRegistryDockerCredentialsArgs
        {
            RegistryName = registry.Name,
            Write        = true,
        });
        var registryInfo = Output.All(
            registryCreds.DockerCredentials, registry.ServerUrl).
                           Apply(args =>
        {
            var authJson  = args[0];
            var serverUrl = args[1];
            dynamic auths = JsonConvert.DeserializeObject(authJson);
            var authToken = auths["auths"][serverUrl]["auth"];
            var decoded   = ASCIIEncoding.ASCII.GetString(authToken);

            var parts = decoded.Split(':');
            if (parts.Length != 2)
            {
                throw new Exception("Invalid credentials");
            }

            return(new ImageRegistry
            {
                Server = serverUrl,
                Username = parts[0],
                Password = parts[1],
            });
        });

        // Build and publish the app image.
        var image = new Image("my-image", new ImageArgs
        {
            Build = new DockerBuild {
                Context = "app"
            },
            ImageName = imageName,
            Registry  = registryInfo,
        });

        // Export the resulting base name in addition to the specific version pushed.
        return(new Dictionary <string, object>
        {
            { "baseImageName", image.BaseImageName },
            { "fullImageName", image.ImageName },
        });
    });
 private void BeforeInitializing()
 {
     if (_injector.HasDirectMapping(typeof(ContainerRegistry)))
     {
         ContainerRegistry registry = _injector.GetInstance(typeof(ContainerRegistry)) as ContainerRegistry;
         registry.SetParentFinder(_parentFinder);
         _injector.Unmap(typeof(IParentFinder));
         _injector.Map(typeof(IParentFinder)).ToValue(registry);
     }
 }
Exemplo n.º 9
0
            public void Should_Call_The_Modules_Register_Method()
            {
                // Given
                var module   = Substitute.For <ICakeModule>();
                var registry = new ContainerRegistry();

                // When
                registry.RegisterModule(module);

                // Then
                module.Received(1).Register(
                    Arg.Is <ICakeContainerRegistry>(registry));
            }
Exemplo n.º 10
0
            public void Should_Create_Type_Registration_As_Singleton_By_Default()
            {
                // Given
                var registry = new ContainerRegistry();

                // When
                registry.RegisterType <CakeConsole>();

                // Then
                Assert.Equal(1, registry.Registrations.Count);
                Assert.Equal(typeof(CakeConsole), registry.Registrations[0].ImplementationType);
                Assert.Null(registry.Registrations[0].Instance);
                Assert.True(registry.Registrations[0].IsSingleton);
            }
Exemplo n.º 11
0
        /// <summary>
        /// Constructs an Azure Batch PoolInformation instance
        /// </summary>
        /// <param name="image">The image name for the current <see cref="TesTask"/></param>
        /// <param name="vmSize">The Azure VM sku</param>
        /// <param name="preemptible">True if preemptible machine should be used</param>
        /// <returns></returns>
        private async Task <PoolInformation> CreatePoolInformation(string image, string vmSize, bool preemptible)
        {
            var vmConfig = new VirtualMachineConfiguration(
                imageReference: new ImageReference("ubuntu-server-container", "microsoft-azure-batch", "16-04-lts", "latest"),
                nodeAgentSkuId: "batch.node.ubuntu 16.04");

            var containerRegistryInfo = await azureProxy.GetContainerRegistryInfoAsync(image);

            if (containerRegistryInfo != null)
            {
                var containerRegistry = new ContainerRegistry(
                    userName: containerRegistryInfo.Username,
                    registryServer: containerRegistryInfo.RegistryServer,
                    password: containerRegistryInfo.Password);

                // Download private images at node startup, since those cannot be downloaded in the main task that runs multiple containers.
                // Doing this also requires that the main task runs inside a container, hence downloading the "docker" image (contains docker client) as well.
                vmConfig.ContainerConfiguration = new ContainerConfiguration
                {
                    ContainerImageNames = new List <string> {
                        image, DockerInDockerImageName
                    },
                    ContainerRegistries = new List <ContainerRegistry> {
                        containerRegistry
                    }
                };
            }

            var poolSpecification = new PoolSpecification
            {
                VirtualMachineConfiguration = vmConfig,
                VirtualMachineSize          = vmSize,
                ResizeTimeout = TimeSpan.FromMinutes(30),
                TargetLowPriorityComputeNodes = preemptible ? 1 : 0,
                TargetDedicatedComputeNodes   = preemptible ? 0 : 1
            };

            var poolInformation = new PoolInformation
            {
                AutoPoolSpecification = new AutoPoolSpecification
                {
                    AutoPoolIdPrefix   = "TES",
                    PoolLifetimeOption = PoolLifetimeOption.Job,
                    PoolSpecification  = poolSpecification,
                    KeepAlive          = false
                }
            };

            return(poolInformation);
        }
        /// <summary>
        /// This method can create a pool, it is not used in our example.
        /// The code remains for documentation purposes.
        /// </summary>
        public static void PreparePool()
        {
            BatchClient batchClient = PrepareConnection();

            if (Environment.GetEnvironmentVariable("REGISTRYNAME") != null)
            {
                ContainerRegistry containerRegistry = new ContainerRegistry(
                    registryServer: Environment.GetEnvironmentVariable("REGISTRYNAME"),
                    userName: Environment.GetEnvironmentVariable("REGISTRYUSERNAME"),
                    password: Environment.GetEnvironmentVariable("REGISTRYPASSWORD")
                    );

                // Create container configuration, prefetching Docker images from the container registry
                ContainerConfiguration containerConfig = new ContainerConfiguration()
                {
                    ContainerImageNames = new List <string>()
                    {
                        Environment.GetEnvironmentVariable("WORKERIMAGENAME")
                    },
                    ContainerRegistries = new List <ContainerRegistry>
                    {
                        containerRegistry
                    }
                };

                ImageReference imageReference = new ImageReference(
                    publisher: "microsoft-azure-batch",
                    offer: "ubuntu-server-container",
                    sku: "16-04-lts",
                    version: "latest");

                // VM configuration
                VirtualMachineConfiguration virtualMachineConfiguration = new VirtualMachineConfiguration(
                    imageReference: imageReference,
                    nodeAgentSkuId: "batch.node.ubuntu 16.04")
                {
                    ContainerConfiguration = containerConfig,
                };

                //Create pool
                CloudPool pool = batchClient.PoolOperations.CreatePool(
                    poolId: "docker",
                    targetDedicatedComputeNodes: 1,
                    virtualMachineSize: "Standard_A2_v2",
                    virtualMachineConfiguration: virtualMachineConfiguration);

                pool.Commit();
            }
        }
Exemplo n.º 13
0
        /*============================================================================*/
        /* Private Functions                                                          */
        /*============================================================================*/

        private void AfterInitializing()
        {
            _containerRegistry = _injector.GetInstance(typeof(ContainerRegistry)) as ContainerRegistry;
            if (!_injector.HasDirectMapping(typeof(IStageCrawler)))
            {
                _logger.Warn("No CrawlerConfig configured. Make sure to configure a platform specific stage crawler config, or don't install the StageCrawler extension");
                return;
            }
            if (_injector.HasDirectMapping(typeof(IViewManager)))
            {
                ScanViewManagedContainers();
            }
            else
            {
                ScanContextView();
            }
        }
        public void Multiple_Depths_Of_Children_Only_Inherit_The_First_Parents_Injector()
        {
            AddRootToStage();

            parentContext
            .Install(typeof(TestSupportViewStateWatcherExtension))
            .Install(typeof(SupportParentFinderExtension))
            .Install(typeof(ModularityExtension))
            .Configure(new ContextView(parentView));

            childContext
            .Install(typeof(TestSupportViewStateWatcherExtension))
            .Install(typeof(ModularityExtension))
            .Install(typeof(SupportParentFinderExtension))
            .Configure(new ContextView(childView));


            SupportView anotherChildView    = new SupportView();
            IContext    anotherChildContext = new Context()
                                              .Install(typeof(TestSupportViewStateWatcherExtension))
                                              .Install(typeof(StageSyncExtension))
                                              .Install(typeof(ContextViewExtension))
                                              .Install(typeof(ModularityExtension))
                                              .Install(typeof(SupportParentFinderExtension))
                                              .Configure(new ContextView(anotherChildView));


            ContainerRegistry cr = new ContainerRegistry();

            parentContext.injector.Map(typeof(ContainerRegistry)).ToValue(cr);
            childContext.injector.Map(typeof(ContainerRegistry)).ToValue(cr);
            anotherChildContext.injector.Map(typeof(ContainerRegistry)).ToValue(cr);

            cr.AddContainer(parentView);
            cr.AddContainer(childView);
            cr.AddContainer(anotherChildView);

            root.AddChild(parentView);
            parentView.AddChild(childView);
            childView.AddChild(anotherChildView);

            Assert.That(childContext.injector.parent, Is.EqualTo(parentContext.injector));
            Assert.That(anotherChildContext.injector.parent, Is.EqualTo(childContext.injector));
            Assert.That(anotherChildContext.injector.parent, Is.Not.EqualTo(parentContext.injector));
        }
Exemplo n.º 15
0
            public void Should_Use_The_Script_Directory_As_Root_For_Configuration_File()
            {
                // Given
                var fileSystem  = Substitute.For <IFileSystem>();
                var environment = FakeEnvironment.CreateUnixEnvironment();
                var provider    = new CakeConfigurationProvider(fileSystem, environment);
                var registry    = new ContainerRegistry();
                var options     = new CakeOptions {
                    Script = "./foo/bar/build.cake"
                };
                var module = new ConfigurationModule(provider, options);

                // When
                module.Register(registry);

                // Then
                fileSystem.Received(1).Exist(Arg.Is <FilePath>(f => f.FullPath == "/Working/foo/bar/cake.config"));
            }
Exemplo n.º 16
0
        private string FormatContainerImageName(string image)
        {
            if (string.IsNullOrWhiteSpace(image))
            {
                return(image);
            }

            var imageParts = image.Split('/');

            string registry = ContainerRegistry;

            if (!ContainerRegistry.ToLower().EndsWith(".azurecr.io"))
            {
                registry = ContainerRegistry + ".azurecr.io";
            }

            return($"{registry}/{imageParts[1]}");
        }
Exemplo n.º 17
0
        private static async Task CreatePoolIfNotExist(BatchClient batchClient, string poolId, ResourceFile[] resourceFiles)
        {
            var pools = await batchClient.PoolOperations.ListPools().ToListAsync();

            var alreadyExists = pools.Any(x => x.Id == poolId);

            if (alreadyExists)
            {
                Console.WriteLine($"Pool {poolId} already exists, no need to create");
                return;
            }

            Console.WriteLine($"Creating pool {poolId}");

            var containerRegistry = new ContainerRegistry("globomantics", "globomantics.azurecr.io",
                                                          "jWyBhM8qiNG3zX/S8GGDbJe5r5aMvpW7");

            var containerConfig = new ContainerConfiguration()
            {
                ContainerImageNames = new List <string>
                {
                    @"globomantics.azurecr.io/optionpricer:latest"
                },
                ContainerRegistries = new List <ContainerRegistry>
                {
                    containerRegistry
                }
            };

            var pool = batchClient.PoolOperations.CreatePool(
                poolId: poolId,
                targetLowPriorityComputeNodes: 1,
                virtualMachineSize: "Standard_NC6",
                virtualMachineConfiguration: new VirtualMachineConfiguration(
                    new ImageReference("ubuntu-server-container", "microsoft-azure-batch", "16-04-lts"),
                    "batch.node.ubuntu 16.04")
            {
                ContainerConfiguration = containerConfig
            });

            await pool.CommitAsync();
        }
        /*============================================================================*/
        /* Public Functions                                                           */
        /*============================================================================*/

        public void Extend(IContext context)
        {
            context.WhenInitializing(WhenInitializing);
            context.WhenDestroying(WhenDestroying);

            _injector = context.injector;

            // Just one Container Registry
            if (_containerRegistry == null)
            {
                _containerRegistry = new ContainerRegistry();
                ViewNotifier.SetRegistry(_containerRegistry);
            }
            _injector.Map(typeof(ContainerRegistry)).ToValue(_containerRegistry);
            if (_injector.HasDirectMapping(typeof(IParentFinder)))
            {
                _injector.Unmap(typeof(IParentFinder));
            }
            _injector.Map(typeof(IParentFinder)).ToValue(_containerRegistry);

            // But you get your own View Manager
            _injector.Map(typeof(IViewManager)).ToSingleton(typeof(Impl.ViewManager));
        }
Exemplo n.º 19
0
        private Container InnerRegister(Type key, Type target, string name, ActivationMethod activationMethod)
        {
            if (key != target && target.IsAssignableFrom(key))
            {
                throw new Exception($"Unnable to register type {target} with key {key}, target must be assignable to key.");
            }

            var containerRegistry = new ContainerRegistry(activationMethod, target);

            registries.Add(key.FullName, containerRegistry);

            if (key != target)
            {
                registries.Add(target.FullName, containerRegistry);
            }

            if (!string.IsNullOrEmpty(name))
            {
                registries.Add(name, containerRegistry);
            }


            return(this);
        }
        private VirtualMachineConfiguration CreateVirtualMachineConfiguration(
            BatchClient batchClient,
            ImageReference imageReference)
        {
            List <ImageInformation> nodeAgentSkus = null;

            IPagedEnumerable <ImageInformation> agentSkus =
                batchClient.PoolOperations.ListSupportedImages();
            Task <List <ImageInformation> > nodeAgentTask =
                PagedEnumerableExtensions.ToListAsync <ImageInformation>(agentSkus);

            nodeAgentTask.Wait();
            if (nodeAgentTask.Status == TaskStatus.Faulted)
            {
                throw new BatchOperationException(
                          "Couldn't retrieve list of Batch supported VM images, aborting ...");
            }
            else
            {
                nodeAgentSkus = nodeAgentTask.Result;
            }

            /** nodeAgentSkus.ForEach(delegate(ImageInformation img)
             * {
             * Console.WriteLine("-------------------------");
             * Console.WriteLine("Node SKU: {0}", img.NodeAgentSkuId);
             * Console.WriteLine("Publisher {0}", img.ImageReference.Publisher);
             * Console.WriteLine("Offer {0}", img.ImageReference.Offer);
             * Console.WriteLine("Sku {0}", img.ImageReference.Sku);
             * Console.WriteLine("-------------------------");
             * }); **/

            ImageInformation ubuntuAgentSku = nodeAgentSkus.Find(
                imageRef =>
                imageRef.ImageReference.Publisher == BatchVmConfig.VM_IMAGE_PUBLISHER &&
                imageRef.ImageReference.Offer == BatchVmConfig.VM_IMAGE_OFFER &&
                imageRef.ImageReference.Sku.Contains(BatchVmConfig.VM_IMAGE_SKU));

            Console.WriteLine("Batch node agent: {0}", ubuntuAgentSku.NodeAgentSkuId);
            VirtualMachineConfiguration vmConfig = new VirtualMachineConfiguration(
                imageReference: imageReference,
                nodeAgentSkuId: ubuntuAgentSku.NodeAgentSkuId);
            // nodeAgentSkuId: "batch.node.ubuntu 18.04");

            Dictionary <string, string> imageList = GetContainerImageList();

            if ((imageList != null) && (imageList.Count > 0))
            {
                string contRegistry        = EnvVars[AzureEnvConstants.AZURE_ACR_NAME];
                string contRegistryUser    = EnvVars[AzureEnvConstants.AZURE_ACR_USER];
                string contRegistryUserPwd = EnvVars[AzureEnvConstants.AZURE_ACR_USER_PWD];

                // Specify a container registry
                ContainerRegistry containerRegistry = new ContainerRegistry(
                    registryServer: contRegistry,
                    userName: contRegistryUser,
                    password: contRegistryUserPwd);

                // Create container configuration, prefetching Docker images from the container registry
                ContainerConfiguration containerConfig = new ContainerConfiguration();
                containerConfig.ContainerImageNames = new List <string>(imageList.Values);
                containerConfig.ContainerRegistries = new List <ContainerRegistry> {
                    containerRegistry
                };

                vmConfig.ContainerConfiguration = containerConfig;
            }
            ;

            return(vmConfig);
        }
Exemplo n.º 21
0
        static void Main(string[] args)
        {
            string storageConnectionString =
                $"DefaultEndpointsProtocol=https;AccountName={StorageAccountName};AccountKey={StorageAccountKey}";

            // Retrieve the storage account
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);

            // Create the blob client
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Upload the input files to blob storage
            const string  inputContainerName = "batchinput";
            List <string> inputFilePaths     = new List <string>
            {
                "taskdata0.txt",
                "taskdata1.txt",
                "taskdata2.txt"
            };
            List <ResourceFile> inputFiles = new List <ResourceFile>();

            foreach (string filePath in inputFilePaths)
            {
                inputFiles.Add(UploadFileToContainer(blobClient, inputContainerName, filePath));
            }

            // Get a SAS Url for the output container
            const string outputContainerName   = "batchoutput";
            string       outputContainerSasUrl = GetOutputContainerSasUrl(blobClient, outputContainerName);

            // Specify a container registry
            ContainerRegistry containerRegistry = new ContainerRegistry(
                registryServer: RegistryServer,
                userName: RegistryUserName,
                password: RegistryPassword);

            // Create container configuration, prefetching Docker images from the container registry
            ContainerConfiguration containerConfig = new ContainerConfiguration()
            {
                ContainerImageNames = ContainerImageNames,
                ContainerRegistries = new List <ContainerRegistry> {
                    containerRegistry
                }
            };

            // Create the virtual machine image reference - make sure to choose an image that supports containers
            ImageReference imageReference = new ImageReference(
                publisher: "MicrosoftWindowsServer",
                offer: "WindowsServer",
                sku: "2016-datacenter-with-containers",
                version: "latest");

            // Create the virtual machine configuration for the pool and set the container configuration
            VirtualMachineConfiguration virtualMachineConfiguration = new VirtualMachineConfiguration(
                imageReference: imageReference,
                nodeAgentSkuId: "batch.node.windows amd64");

            virtualMachineConfiguration.ContainerConfiguration = containerConfig;

            BatchSharedKeyCredentials cred = new BatchSharedKeyCredentials(BatchAccountUrl, BatchAccountName, BatchAccountKey);

            using (BatchClient batchClient = BatchClient.Open(cred))
            {
                Console.WriteLine("Creating pool [{0}]...", PoolId);

                try
                {
                    CloudPool pool = batchClient.PoolOperations.CreatePool(
                        poolId: PoolId,
                        targetDedicatedComputeNodes: PoolNodeCount,
                        virtualMachineSize: PoolVMSize,
                        virtualMachineConfiguration: virtualMachineConfiguration);

                    pool.Commit();
                }
                catch (BatchException be)
                {
                    // Accept the specific error code PoolExists as that is expected if the pool already exists
                    if (be.RequestInformation?.BatchError?.Code == BatchErrorCodeStrings.PoolExists)
                    {
                        Console.WriteLine("The pool {0} already existed when we tried to create it", PoolId);
                    }
                    else
                    {
                        throw; // Any other exception is unexpected
                    }
                }

                Console.WriteLine("Creating job [{0}]...", JobId);
                CloudJob job = null;
                try
                {
                    job    = batchClient.JobOperations.CreateJob();
                    job.Id = JobId;
                    job.PoolInformation = new PoolInformation {
                        PoolId = PoolId
                    };

                    // Add job preparation task to remove existing Docker image
                    Console.WriteLine("Adding job preparation task to job [{0}]...", JobId);
                    string             jobPreparationCmdLine = $"cmd /c docker rmi -f {ContainerImageNames[0]}:latest";
                    JobPreparationTask jobPreparationTask    = new JobPreparationTask(jobPreparationCmdLine)
                    {
                        UserIdentity = new UserIdentity(new AutoUserSpecification(elevationLevel: ElevationLevel.Admin, scope: AutoUserScope.Task))
                    };
                    job.JobPreparationTask = jobPreparationTask;

                    job.Commit();
                }
                catch (BatchException be)
                {
                    // Accept the specific error code JobExists as that is expected if the job already exists
                    if (be.RequestInformation?.BatchError?.Code == BatchErrorCodeStrings.JobExists)
                    {
                        Console.WriteLine("The job {0} already existed when we tried to create it", JobId);
                    }
                    else
                    {
                        throw; // Any other exception is unexpected
                    }
                }

                if (job != null)
                {
                    // Create a collection to hold the tasks that we'll be adding to the job
                    Console.WriteLine("Adding {0} tasks to job [{1}]...", inputFiles.Count, JobId);

                    List <CloudTask> tasks = new List <CloudTask>();

                    // Create each of the tasks to process one of the input files.
                    for (int i = 0; i < inputFiles.Count; i++)
                    {
                        string taskId         = String.Format("Task{0}", i);
                        string inputFilename  = inputFiles[i].FilePath;
                        string outputFileName = string.Format("out{0}", inputFilename);

                        // Override the default entrypoint of the container
                        string taskCommandLine = string.Format("C:\\ReadWriteFile\\ReadWriteFile.exe {0} {1}", inputFilename, outputFileName);

                        // Specify the container the task will run
                        TaskContainerSettings cmdContainerSettings = new TaskContainerSettings(
                            imageName: "nimccollftacr.azurecr.io/batch/readwritefile"
                            );

                        CloudTask task = new CloudTask(taskId, taskCommandLine);
                        task.ContainerSettings = cmdContainerSettings;

                        // Set the resource files and output files for the task
                        task.ResourceFiles = new List <ResourceFile> {
                            inputFiles[i]
                        };
                        task.OutputFiles = new List <OutputFile>
                        {
                            new OutputFile(
                                filePattern: outputFileName,
                                destination: new OutputFileDestination(new OutputFileBlobContainerDestination(containerUrl: outputContainerSasUrl, path: outputFileName)),
                                uploadOptions: new OutputFileUploadOptions(OutputFileUploadCondition.TaskCompletion))
                        };

                        // You must elevate the identity of the task in order to run a container
                        task.UserIdentity = new UserIdentity(new AutoUserSpecification(elevationLevel: ElevationLevel.Admin, scope: AutoUserScope.Task));
                        tasks.Add(task);
                    }

                    // Add all tasks to the job.
                    batchClient.JobOperations.AddTask(JobId, tasks);

                    // Monitor task success/failure, specifying a maximum amount of time to wait for the tasks to complete.
                    TimeSpan timeout = TimeSpan.FromMinutes(30);
                    Console.WriteLine("Monitoring all tasks for 'Completed' state, timeout in {0}...", timeout);

                    IEnumerable <CloudTask> addedTasks = batchClient.JobOperations.ListTasks(JobId);

                    batchClient.Utilities.CreateTaskStateMonitor().WaitAll(addedTasks, TaskState.Completed, timeout);

                    Console.WriteLine("All tasks reached state Completed.");

                    // Print task output
                    Console.WriteLine();
                    Console.WriteLine("Printing task output...");

                    IEnumerable <CloudTask> completedtasks = batchClient.JobOperations.ListTasks(JobId);

                    foreach (CloudTask task in completedtasks)
                    {
                        string nodeId = String.Format(task.ComputeNodeInformation.ComputeNodeId);
                        Console.WriteLine("Task: {0}", task.Id);
                        Console.WriteLine("Node: {0}", nodeId);
                        Console.WriteLine("Standard out:");
                        Console.WriteLine(task.GetNodeFile(Constants.StandardOutFileName).ReadAsString());
                    }
                }

                // Clean up Batch resources (if the user so chooses)
                Console.WriteLine();
                Console.Write("Delete job? [yes] no: ");
                string response = Console.ReadLine().ToLower();
                if (response != "n" && response != "no")
                {
                    batchClient.JobOperations.DeleteJob(JobId);
                }

                Console.Write("Delete pool? [yes] no: ");
                response = Console.ReadLine().ToLower();
                if (response != "n" && response != "no")
                {
                    batchClient.PoolOperations.DeletePool(PoolId);
                }
            }
        }
Exemplo n.º 22
0
 public void TearDown()
 {
     _server.Stop();
     ContainerRegistry.Get().Dispose();
 }
Exemplo n.º 23
0
        // ReSharper disable once UnusedMember.Local
        static void Main(string[] args)
        {
            var version = Read("dotnet", "minver", noEcho: true, echoPrefix: Prefix).Replace("\r", string.Empty).Replace("\n", string.Empty);

            Console.WriteLine("Version used in Build: {0}", version);
            Console.WriteLine($"##vso[build.updatebuildnumber]{version}");

            Target(Targets.CleanBuildOutput,
                   () => { Run("dotnet", "clean -c Release -v m --nologo", echoPrefix: Prefix); });

            Target(Targets.Build,
                   DependsOn(Targets.CleanBuildOutput),
                   () => { Run("dotnet", "build -c Release --nologo", echoPrefix: Prefix); });

            Target(Targets.Test,
                   DependsOn(Targets.Build),
                   () => { Run("dotnet", $"test -c Release --no-build", echoPrefix: Prefix); });

            Target(Targets.CleanPublishOutput,
                   () =>
            {
                if (Directory.Exists(PublishOutput))
                {
                    Directory.Delete(PublishOutput, true);
                }
            });

            Target(Targets.Publish,
                   DependsOn(Targets.CleanPublishOutput),
                   () =>
            {
                Directory.CreateDirectory(PublishOutput);

                foreach (var fileName in Directory.GetFiles("./src", "*.csproj", SearchOption.AllDirectories))
                {
                    // Console.WriteLine($"file: {fileName}");

                    var projectFile = new FileInfo(fileName);
                    // Console.WriteLine($"fileInfo.DirectoryName: {projectFile.DirectoryName}");
                    // Console.WriteLine($"fileInfo.Directory.Name: {projectFile.Directory?.Name}");
                    // Console.WriteLine($"fileInfo.FullName: {projectFile.FullName}");

                    var publishDirName = Path.Combine(PublishOutput, projectFile.Directory?.Name !);
                    var publishDir     = new DirectoryInfo(publishDirName);

                    // Console.WriteLine($"publishOutput: {publishOutput}");
                    // Console.WriteLine($"publishDir.FullName: {publishDir.FullName}");

                    Console.WriteLine($"Publishing Project: {projectFile.FullName} to dir {publishDir.FullName}");

                    Run("dotnet", $"publish {projectFile.FullName} -c Release --no-build --no-restore --output {publishDir.FullName}", echoPrefix: Prefix);
                    //File.Copy(file, Path.Combine(packOutputCopy, Path.GetFileName(file)), true);
                }
            });

            Target(Targets.CleanPackOutput,
                   () =>
            {
                if (Directory.Exists(PackOutput))
                {
                    Directory.Delete(PackOutput, true);
                }
            });

            Target(Targets.Pack,
                   DependsOn(Targets.Build, Targets.CleanPackOutput),
                   () =>
            {
                Directory.CreateDirectory(PackOutput);

                //var project = Directory.GetFiles("./src", "*.csproj", SearchOption.TopDirectoryOnly).OrderBy(_ => _).First();
                //Run("dotnet", $"pack {project} -c Release -o {Directory.CreateDirectory(packOutput).FullName} --no-build --nologo", echoPrefix: Prefix);
            });

            Target(Targets.CopyPackOutput,
                   DependsOn(Targets.Pack),
                   () =>
            {
                Directory.CreateDirectory(PackOutputCopy);

                foreach (var file in Directory.GetFiles(PackOutput))
                {
                    File.Copy(file, Path.Combine(PackOutputCopy, Path.GetFileName(file)), true);
                }
            });

            Target(Targets.CopyOnly,
                   () =>
            {
                foreach (var fileName in Directory.GetFiles("./src", "copy-only.txt", SearchOption.AllDirectories))
                {
                    // Console.WriteLine($"file: {fileName}");

                    var projectFile = new FileInfo(fileName);
                    Console.WriteLine($"fileInfo.DirectoryName: {projectFile.DirectoryName}");
                    // Console.WriteLine($"fileInfo.Directory.Name: {projectFile.Directory?.Name}");
                    // Console.WriteLine($"fileInfo.FullName: {projectFile.FullName}");

                    if (projectFile.Directory != null)
                    {
                        var sourceFolder       = projectFile.Directory.FullName;
                        var destionationFolder = Path.Combine(PublishOutput, projectFile.Directory?.Name !);
                        Console.WriteLine($"Copy Folder: {sourceFolder} to {destionationFolder}");
                        CopyFolder(sourceFolder, destionationFolder);
                    }
                }
            });

            Target(Targets.CreateDockerImages,
                   DependsOn(Targets.Publish),
                   () =>
            {
                foreach (var fileName in Directory.GetFiles(PublishOutput, "Dockerfile", SearchOption.AllDirectories))
                {
                    var dockerfile = new FileInfo(fileName);
                    Console.WriteLine($"Building Dockerfile Project: {dockerfile.FullName}");

                    var tag  = $"{ContainerRegistry.ToLower()}/{Prefix.ToLower()}-{dockerfile.Directory?.Name}:latest";
                    var tag2 = $"{ContainerRegistry.ToLower()}/{Prefix.ToLower()}-{dockerfile.Directory?.Name}:{version}";

                    Run("docker", $"build -t {tag} -t {tag2} .", workingDirectory: dockerfile.Directory?.FullName);
                }
            });

            Target(Targets.PushDockerImages,
                   () =>
            {
                foreach (var fileName in Directory.GetFiles(PublishOutput, "Dockerfile", SearchOption.AllDirectories))
                {
                    var dockerfile = new FileInfo(fileName);
                    Console.WriteLine($"Building Dockerfile Project: {dockerfile.FullName}");

                    var tag  = $"{ContainerRegistry.ToLower()}/{Prefix.ToLower()}-{dockerfile.Directory?.Name}:latest";
                    var tag2 = $"{ContainerRegistry.ToLower()}/{Prefix.ToLower()}-{dockerfile.Directory?.Name}:{version}";

                    Run("docker", $"push {tag}");
                    Run("docker", $"push {tag2}");
                }
            });

            Target("default", DependsOn(Targets.Test, Targets.CopyPackOutput, Targets.Publish, Targets.CopyOnly, Targets.CreateDockerImages));


            RunTargetsAndExit(args,
                              ex => ex is SimpleExec.NonZeroExitCodeException || ex.Message.EndsWith(EnvVarMissing),
                              Prefix);
        }
Exemplo n.º 24
0
 public CakeContainerBuilder()
 {
     _registry = new ContainerRegistry();
 }
Exemplo n.º 25
0
        /*============================================================================*/
        /* Public Static Functions                                                    */
        /*============================================================================*/

        public static void SetRegistry(ContainerRegistry containerRegistry)
        {
            _registry = containerRegistry;
        }
        private void BeforeInitializing()
        {
            ContainerRegistry registry = _injector.GetInstance(typeof(ContainerRegistry)) as ContainerRegistry;

            registry.SetParentFinder(_parentFinder);
        }