Exemplo n.º 1
0
        private void DisplayHttpFunctionsInfo(IScriptJobHost scriptHost, HttpOptions httpOptions, Uri baseUri)
        {
            if (scriptHost != null)
            {
                var httpFunctions = scriptHost.Functions.Where(f => f.Metadata.IsHttpFunction());
                if (httpFunctions.Any())
                {
                    ColoredConsole
                    .WriteLine()
                    .WriteLine(Yellow("Http Functions:"))
                    .WriteLine();
                }

                foreach (var function in httpFunctions)
                {
                    var binding   = function.Metadata.Bindings.FirstOrDefault(b => b.Type != null && b.Type.Equals("httpTrigger", StringComparison.OrdinalIgnoreCase));
                    var httpRoute = binding?.Raw?.GetValue("route", StringComparison.OrdinalIgnoreCase)?.ToString();
                    httpRoute = httpRoute ?? function.Name;

                    string[] methods    = null;
                    var      methodsRaw = binding?.Raw?.GetValue("methods", StringComparison.OrdinalIgnoreCase)?.ToString();
                    if (string.IsNullOrEmpty(methodsRaw) == false)
                    {
                        methods = methodsRaw.Split(',');
                    }

                    string hostRoutePrefix = "";
                    if (!function.Metadata.IsProxy)
                    {
                        hostRoutePrefix = httpOptions.RoutePrefix ?? "api/";
                        hostRoutePrefix = string.IsNullOrEmpty(hostRoutePrefix) || hostRoutePrefix.EndsWith("/")
                            ? hostRoutePrefix
                            : $"{hostRoutePrefix}/";
                    }

                    var functionMethods = methods != null ? $"{CleanAndFormatHttpMethods(string.Join(",", methods))}" : null;
                    var url             = $"{baseUri.ToString().Replace("0.0.0.0", "localhost")}{hostRoutePrefix}{httpRoute}";
                    ColoredConsole
                    .WriteLine($"\t{Yellow($"{function.Name}:")} {Green(functionMethods)} {Green(url)}")
                    .WriteLine();
                }
            }
        }
Exemplo n.º 2
0
        private async Task Deploy(string name, string image, string nameSpace, int min, int max)
        {
            var isHTTP = IsHTTPTrigger(name);

            await CreateNamespace(nameSpace);

            client.DefaultNamespace = nameSpace;

            ColoredConsole.WriteLine();
            ColoredConsole.WriteLine("Deploying function to Knative...");

            var knativeService = GetKnativeService(name, image, nameSpace, min, max, isHTTP);
            var json           = Newtonsoft.Json.JsonConvert.SerializeObject(knativeService,
                                                                             Newtonsoft.Json.Formatting.None,
                                                                             new Newtonsoft.Json.JsonSerializerSettings
            {
                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
            });

            File.WriteAllText("deployment.json", json);
            await KubernetesHelper.RunKubectl($"apply -f deployment.json");

            File.Delete("deployment.json");

            var externalIP = await GetIstioClusterIngressIP();

            if (string.IsNullOrEmpty(externalIP))
            {
                ColoredConsole.WriteLine("Couldn't find Istio Cluster Ingress External IP");
                return;
            }

            var host = GetFunctionHost(name, nameSpace);

            ColoredConsole.WriteLine();
            ColoredConsole.WriteLine("Function deployed successfully!");
            ColoredConsole.WriteLine();
            ColoredConsole.WriteLine($"Function URL: http://{externalIP}");
            ColoredConsole.WriteLine($"Function Host: {host}");
            ColoredConsole.WriteLine();
            ColoredConsole.WriteLine("Plese note: it may take a few minutes for the knative service to be reachable");
        }
Exemplo n.º 3
0
        public async override Task RunAsync()
        {
            if (Console.IsOutputRedirected || Console.IsInputRedirected)
            {
                if (string.IsNullOrEmpty(Language) ||
                    string.IsNullOrEmpty(TemplateName) ||
                    string.IsNullOrEmpty(FunctionName))
                {
                    ColoredConsole
                    .Error
                    .WriteLine(ErrorColor("Running with stdin\\stdout redirected. Command must specify --language, --template, and --name explicitly."))
                    .WriteLine(ErrorColor("See 'func help function' for more details"));
                    return;
                }
            }

            var templates = await _templatesManager.Templates;

            ColoredConsole.Write("Select a language: ");
            var language = Language ?? DisplaySelectionWizard(templates.Select(t => t.Metadata.Language).Distinct());

            ColoredConsole.WriteLine(TitleColor(language));

            ColoredConsole.Write("Select a template: ");
            var name = TemplateName ?? DisplaySelectionWizard(templates.Where(t => t.Metadata.Language.Equals(language, StringComparison.OrdinalIgnoreCase)).Select(t => t.Metadata.Name).Distinct());

            ColoredConsole.WriteLine(TitleColor(name));

            var template = templates.FirstOrDefault(t => t.Metadata.Name.Equals(name, StringComparison.OrdinalIgnoreCase) && t.Metadata.Language.Equals(language, StringComparison.OrdinalIgnoreCase));

            if (template == null)
            {
                ColoredConsole.Error.WriteLine(ErrorColor($"Can't find template \"{name}\" in \"{language}\""));
            }
            else
            {
                ColoredConsole.Write($"Function name: [{template.Metadata.DefaultFunctionName}] ");
                var functionName = FunctionName ?? Console.ReadLine();
                functionName = string.IsNullOrEmpty(functionName) ? template.Metadata.DefaultFunctionName : functionName;
                await _templatesManager.Deploy(functionName, template);
            }
        }
        private async Task PreRunConditions()
        {
            if (GlobalCoreToolsSettings.CurrentWorkerRuntime == WorkerRuntime.python)
            {
                await PythonHelpers.ValidatePythonVersion(setWorkerExecutable : true, errorIfNoExactMatch : true, errorOutIfOld : true);

                // We need to update the PYTHONPATH to add worker's dependencies
                var pythonPath       = Environment.GetEnvironmentVariable("PYTHONPATH") ?? string.Empty;
                var pythonWorkerDeps = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "workers", "python", "deps");
                if (!pythonPath.Contains(pythonWorkerDeps))
                {
                    Environment.SetEnvironmentVariable("PYTHONPATH", $"{pythonPath}{Path.PathSeparator}{pythonWorkerDeps}", EnvironmentVariableTarget.Process);
                }
                if (StaticSettings.IsDebug)
                {
                    ColoredConsole.WriteLine($"PYTHONPATH for the process is: {Environment.GetEnvironmentVariable("PYTHONPATH")}");
                }
            }
            else if (GlobalCoreToolsSettings.CurrentWorkerRuntime == WorkerRuntime.dotnet && !NoBuild)
            {
                if (DotnetHelpers.CanDotnetBuild())
                {
                    var outputPath = Path.Combine("bin", "output");
                    await DotnetHelpers.BuildDotnetProject(outputPath, string.Empty);

                    Environment.CurrentDirectory = Path.Combine(Environment.CurrentDirectory, outputPath);
                }
                else if (StaticSettings.IsDebug)
                {
                    ColoredConsole.WriteLine("Could not find a valid .csproj file. Skipping the build.");
                }
            }
            else if (GlobalCoreToolsSettings.CurrentWorkerRuntime == WorkerRuntime.powershell && !CommandChecker.CommandExists("dotnet"))
            {
                throw new CliException("Dotnet is required for PowerShell Functions. Please install dotnet (.NET Core SDK) for your system from https://www.microsoft.com/net/download");
            }

            if (!NetworkHelpers.IsPortAvailable(Port))
            {
                throw new CliException($"Port {Port} is unavailable. Close the process using that port, or specify another port using --port [-p].");
            }
        }
Exemplo n.º 5
0
 public static void SetEnvironmentVariable(string key, string value)
 {
     if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
     {
         if (!Win32SetEnvironmentVariable(key, value))
         {
             throw new OutOfMemoryException();
         }
     }
     else
     {
         // There is no safe native way to call into libc setenv on unix from .NET
         // .NET takes a snapshot of environ on process start and updates that snapshot.
         // Any changes through setenv() are ignored.
         if (StaticSettings.IsDebug)
         {
             ColoredConsole.WriteLine("Setting unsupported .NET environemt variables (empty string) is not implemented for this platform.");
         }
     }
 }
Exemplo n.º 6
0
        public override async Task RunAsync()
        {
            var user = await _armManager.GetUserAsync();

            if (string.IsNullOrEmpty(user.PublishingUserName))
            {
                ColoredConsole.WriteLine($"Publishing user is not configured. Run {ExampleColor("func azure set-publish-username <userName>")} to configure your publishing user");
            }
            else
            {
                ColoredConsole
                .Write(TitleColor("Publishing Username: "******"run ")
                .Write(ExampleColor($"\"func azure set-publish-password {user.PublishingUserName}\" "))
                .WriteLine("to update the password");
            }
        }
        public override async Task RunAsync()
        {
            var storageAccounts = await _armManager.GetStorageAccountsAsync(await _armManager.GetCurrentSubscriptionAsync());

            if (storageAccounts.Any())
            {
                ColoredConsole.WriteLine(TitleColor("Storage Accounts:"));

                foreach (var storageAccount in storageAccounts)
                {
                    ColoredConsole
                    .WriteLine($"   -> {TitleColor("Name")}: {storageAccount.StorageAccountName} ({AdditionalInfoColor(storageAccount.Location)})")
                    .WriteLine();
                }
            }
            else
            {
                ColoredConsole.Error.WriteLine(ErrorColor("   -> No storage accounts found"));
            }
        }
        private void DisplayHttpFunctionsInfo(HttpSelfHostConfiguration config)
        {
            WebScriptHostManager hostManager = config.DependencyResolver.GetService <WebScriptHostManager>();

            if (hostManager != null)
            {
                foreach (var function in hostManager.Instance.Functions.Where(f => f.Metadata.IsHttpFunction()))
                {
                    var httpRoute = function.Metadata.Bindings.FirstOrDefault(b => b.Type == "httpTrigger").Raw["route"]?.ToString();
                    httpRoute = httpRoute ?? function.Name;
                    var extensions      = hostManager.Instance.ScriptConfig.HostConfig.GetService <IExtensionRegistry>();
                    var httpConfig      = extensions.GetExtensions <IExtensionConfigProvider>().OfType <HttpExtensionConfiguration>().Single();
                    var hostRoutePrefix = httpConfig.RoutePrefix ?? "api/";
                    hostRoutePrefix = string.IsNullOrEmpty(hostRoutePrefix) || hostRoutePrefix.EndsWith("/")
                        ? hostRoutePrefix
                        : $"{hostRoutePrefix}/";
                    ColoredConsole.WriteLine($"{TitleColor($"Http Function {function.Name}:")} {config.BaseAddress.ToString()}{hostRoutePrefix}{httpRoute}");
                }
            }
        }
        public override async Task RunAsync()
        {
            ColoredConsole.WriteLine($"Enter password for {AdditionalInfoColor($"\"{UserName}\":")}");
            var password = SecurityHelpers.ReadPassword();

            ColoredConsole.Write($"Confirm your password:"******"passwords do not match"));
            }
            else
            {
                await _armManager.UpdateUserAsync(UserName, password);

                ColoredConsole
                .WriteLine($"Password for {AdditionalInfoColor($"\"{UserName}\"")} has been updated!");
            }
        }
        private static async Task <(bool succeeded, string token)> ExecuteCommand(string commandParameters)
        {
            var az = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                ? new Executable("cmd", "/c az " + commandParameters)
                : new Executable("az", commandParameters);

            var stdout    = new StringBuilder();
            var stderr    = new StringBuilder();
            var completed = az.RunAsync(o => stdout.AppendLine(o), e => stderr.AppendLine(e));

            if (await completed == 0)
            {
                return(true, stdout.ToString().Trim(' ', '\n', '\r', '"'));
            }
            else
            {
                ColoredConsole.WriteLine(($"Unable to fetch access token from az cli. Error: {stderr.ToString().Trim(' ', '\n', '\r')}"));
                return(false, stdout.ToString().Trim(' ', '\n', '\r', '"'));
            }
        }
        private async Task InternalPublishFunctionApp(GitIgnoreParser ignoreParser)
        {
            ColoredConsole.WriteLine("Getting site publishing info...");
            var functionApp = await _armManager.GetFunctionAppAsync(FunctionAppName);

            var functionAppRoot = ScriptHostHelpers.GetFunctionAppRootDirectory(Environment.CurrentDirectory);

            if (functionApp.IsLinux && !functionApp.IsDynamic && RunFromZipDeploy)
            {
                ColoredConsole
                .WriteLine(ErrorColor("--zip is not supported with dedicated linux apps."));
                return;
            }

            var workerRuntime     = _secretsManager.GetSecrets().FirstOrDefault(s => s.Key.Equals(Constants.FunctionsWorkerRuntime, StringComparison.OrdinalIgnoreCase)).Value;
            var workerRuntimeEnum = string.IsNullOrEmpty(workerRuntime) ? WorkerRuntime.None : WorkerRuntimeLanguageHelper.NormalizeWorkerRuntime(workerRuntime);

            if (workerRuntimeEnum == WorkerRuntime.python && !functionApp.IsLinux)
            {
                throw new CliException("Publishing Python functions is only supported for Linux FunctionApps");
            }

            var zipStream = await ZipHelper.GetAppZipFile(workerRuntimeEnum, functionAppRoot, BuildNativeDeps, ignoreParser);

            // if consumption Linux, or --zip, run from zip
            if ((functionApp.IsLinux && functionApp.IsDynamic) || RunFromZipDeploy)
            {
                await PublishRunFromZip(functionApp, zipStream);
            }
            else
            {
                await PublishZipDeploy(functionApp, zipStream);
            }

            await SyncTriggers(functionApp);

            if (PublishLocalSettings)
            {
                await PublishAppSettings(functionApp);
            }
        }
        public async Task Login()
        {
            var authContext = new AuthenticationContext(Constants.ArmConstants.CommonAADAuthority, _tokenCache);

            _tokenCache.Clear();
            var code = await authContext.AcquireDeviceCodeAsync(Constants.ArmConstants.ArmAudience, Constants.ArmConstants.AADClientId);

            ColoredConsole
            .WriteLine($"To sign in, use a web browser to open the page {code.VerificationUrl} and enter the code {code.UserCode} to authenticate.");

            var token = await authContext.AcquireTokenByDeviceCodeAsync(code);

            ColoredConsole.WriteLine(Gray($"Logging into {token.TenantId}"));
            if (string.IsNullOrEmpty(_settings.CurrentTenant))
            {
                _settings.CurrentTenant = token.TenantId;
            }

            var tenants = await AcquireTenants(token.AccessToken);

            var tokens = await tenants.Select(tenant =>
            {
                ColoredConsole.WriteLine(Gray($"Logging into {tenant}"));
                authContext = new AuthenticationContext($"{Constants.ArmConstants.AADAuthorityBase}/{tenant}", _tokenCache);
                try
                {
                    return(authContext.AcquireTokenSilentAsync(Constants.ArmConstants.ArmAudience, Constants.ArmConstants.AADClientId));
                }
                catch
                {
                    ColoredConsole.WriteLine($"Error logging into tenant {tenant}. Try to logout and login again.");
                    return(Task.FromResult <AuthenticationResult>(null));
                }
            }).WhenAll();

            if (!_settings.CurrentTenant.Equals(token.TenantId, StringComparison.OrdinalIgnoreCase) &&
                !tokens.Any(t => t.TenantId.Equals(_settings.CurrentTenant)))
            {
                _settings.CurrentTenant = token.TenantId;
            }
        }
        public async Task PrintAccountsAsync()
        {
            var tenants = await _armManager.GetTenants();

            var currentSub    = Settings.CurrentSubscription;
            var subscriptions = tenants
                                .Select(t => t.Subscriptions)
                                .SelectMany(s => s)
                                .Select(s => new
            {
                displayName    = s.DisplayName,
                subscriptionId = s.SubscriptionId,
                isCurrent      = s.SubscriptionId.Equals(currentSub, StringComparison.OrdinalIgnoreCase)
            })
                                .Distinct();

            if (subscriptions.Any())
            {
                if (!subscriptions.Any(s => s.isCurrent))
                {
                    Settings.CurrentSubscription = subscriptions.First().subscriptionId;
                    currentSub = Settings.CurrentSubscription;
                }

                var currentTenant = tenants.FirstOrDefault(t => t.Subscriptions.Any(s => s.SubscriptionId.Equals(currentSub, StringComparison.OrdinalIgnoreCase)));
                Settings.CurrentTenant = currentTenant?.TenantId;

                var longestName = subscriptions.Max(s => s.displayName.Length) + subscriptions.First().subscriptionId.Length + "( ) ".Length;

                ColoredConsole.WriteLine(string.Format($"{{0, {-longestName}}}   {{1}}", TitleColor("Subscription"), TitleColor("Current")));
                ColoredConsole.WriteLine(string.Format($"{{0, {-longestName}}} {{1}}", "------------", "-------"));

                foreach (var subscription in subscriptions)
                {
                    var current = subscription.subscriptionId.Equals(currentSub, StringComparison.OrdinalIgnoreCase)
                        ? TitleColor(true.ToString()).ToString()
                        : false.ToString();
                    ColoredConsole.WriteLine(string.Format($"{{0, {-longestName}}} {{1}}", $"{subscription.displayName} ({subscription.subscriptionId}) ", current));
                }
            }
        }
        public override async Task RunAsync()
        {
            if (!string.IsNullOrEmpty(FolderName))
            {
                var folderPath = Path.Combine(Environment.CurrentDirectory, FolderName);
                FileSystemHelpers.EnsureDirectory(folderPath);
                Environment.CurrentDirectory = folderPath;
            }

            if (!Platforms.Contains(Platform))
            {
                ColoredConsole.Error.WriteLine(ErrorColor($"platform {Platform} is not supported. Valid options are: {String.Join(",", Platforms)}"));
                return;
            }

            var dockerFilePath = Path.Combine(Environment.CurrentDirectory, "Dockerfile");

            if (!FileSystemHelpers.FileExists(dockerFilePath))
            {
                ColoredConsole.Error.WriteLine(ErrorColor($"Dockerfile not found in directory {Environment.CurrentDirectory}"));
                return;
            }

            var image = $"{Registry}/{Name}-azurefunc";

            ColoredConsole.WriteLine("Building Docker image...");
            await DockerHelpers.DockerBuild(image, Environment.CurrentDirectory);

            ColoredConsole.WriteLine("Pushing function image to registry...");
            await DockerHelpers.DockerPush(image);

            var platform = PlatformFactory.CreatePlatform(Platform, ConfigPath);

            if (platform == null)
            {
                ColoredConsole.Error.WriteLine(ErrorColor($"Platform {Platform} is not supported"));
                return;
            }

            await platform.DeployContainerizedFunction(Name, image, MinInstances, MaxInstances);
        }
Exemplo n.º 15
0
        public override async Task RunAsync()
        {
            var functionAppRoot = ScriptHostHelpers.GetFunctionAppRootDirectory(Environment.CurrentDirectory);

            ColoredConsole.WriteLine(WarningColor($"Publish {functionAppRoot} contents to an Azure Function App. Locally deleted files are not removed from destination."));
            ColoredConsole.WriteLine("Getting site publishing info...");
            var functionApp = await _armManager.GetFunctionAppAsync(FunctionAppName);

            await RetryHelper.Retry(async() =>
            {
                using (var client = await GetRemoteZipClient(new Uri($"https://{functionApp.ScmUri}")))
                    using (var request = new HttpRequestMessage(HttpMethod.Put, new Uri("api/zip/site/wwwroot", UriKind.Relative)))
                    {
                        request.Headers.IfMatch.Add(EntityTagHeaderValue.Any);

                        ColoredConsole.WriteLine("Creating archive for current directory...");

                        request.Content = CreateZip(functionAppRoot);

                        ColoredConsole.WriteLine("Uploading archive...");
                        var response = await client.SendAsync(request);
                        if (!response.IsSuccessStatusCode)
                        {
                            throw new CliException($"Error uploading archive ({response.StatusCode}).");
                        }

                        response = await client.PostAsync("api/functions/synctriggers", content: null);
                        if (!response.IsSuccessStatusCode)
                        {
                            throw new CliException($"Error calling sync triggers ({response.StatusCode}).");
                        }

                        if (PublishLocalSettings)
                        {
                            await PublishAppSettings(functionApp);
                        }

                        ColoredConsole.WriteLine("Upload completed successfully.");
                    }
            }, 2);
        }
Exemplo n.º 16
0
        public override int Read(ref int referencecounter)
        {
            iPos += 4;
            var int32_1 = BigEndianBitConverter.ToInt32(fileData, iPos);

            iPos += 4;
            ColoredConsole.WriteLine("{0:x8}   Number of Unknown: 0x{1:x2}", (object)iPos, (object)int32_1);
            iPos += 4 * int32_1;
            iPos += 4;
            var int32_2 = BigEndianBitConverter.ToInt32(fileData, iPos);

            iPos += 4;
            ColoredConsole.WriteLine("{0:x8}   Number of Textures: 0x{1:x2}", (object)iPos, (object)int32_2);
            for (var index = 0; index < int32_2; ++index)
            {
                ReadTextureMeta();
                ++referencecounter;
            }
            iPos += 4;
            var int32_3 = BigEndianBitConverter.ToInt32(fileData, iPos);

            iPos += 4;
            ColoredConsole.WriteLine("{0:x8}   Number of Unknown: 0x{1:x2}", (object)iPos, (object)int32_3);
            iPos += 4 * int32_3;
            iPos += 4;
            var int32_4 = BigEndianBitConverter.ToInt32(fileData, iPos);

            iPos += 4;
            ColoredConsole.WriteLine("{0:x8}   Number of Cameras: 0x{1:x2}", (object)iPos, (object)int32_4);
            for (var index = 0; index < int32_4; ++index)
            {
                ReadCam();
            }
            iPos += 4;
            var int32_5 = BigEndianBitConverter.ToInt32(fileData, iPos);

            iPos += 4;
            ColoredConsole.WriteLine("{0:x8}   Number of Unknown: 0x{1:x2}", (object)iPos, (object)int32_5);
            iPos += 2 * int32_5;
            return(iPos);
        }
Exemplo n.º 17
0
        public static void AssertPythonVersion(WorkerLanguageVersionInfo pythonVersion, bool errorIfNotSupported = false, bool errorIfNoVersion = true)
        {
            if (pythonVersion?.Version == null)
            {
                var message = "Could not find a Python version. Python 3.6.x or 3.7.x is recommended, and used in Azure Functions.";
                if (errorIfNoVersion)
                {
                    throw new CliException(message);
                }
                ColoredConsole.WriteLine(WarningColor(message));
                return;
            }

            ColoredConsole.WriteLine(AdditionalInfoColor($"Found Python version {pythonVersion.Version} ({pythonVersion.ExecutablePath})."));

            // Python 3.6 or 3.7 (supported)
            if (pythonVersion.Major == 3 && (pythonVersion.Minor == 6 || pythonVersion.Minor == 7))
            {
                return;
            }

            // Python 3.x (but not 3.6 or 3.7), not recommended, may fail
            if (pythonVersion.Major == 3)
            {
                if (errorIfNotSupported)
                {
                    throw new CliException($"Python 3.6.x or 3.7.x is required for this operation. "
                                           + "Please install Python 3.6 or 3.7, and use a virtual environment to switch to Python 3.6 or 3.7.");
                }
                ColoredConsole.WriteLine(WarningColor("Python 3.6.x or 3.7.x is recommended, and used in Azure Functions."));
            }

            // No Python 3
            var error = "Python 3.x (recommended version 3.6 or 3.7) is required.";

            if (errorIfNoVersion)
            {
                throw new CliException(error);
            }
            ColoredConsole.WriteLine(WarningColor(error));
        }
        private static async Task <string> RestorePythonRequirements(string functionAppRoot)
        {
            var packagesLocation = Path.Combine(functionAppRoot, Constants.ExternalPythonPackages);

            FileSystemHelpers.EnsureDirectory(packagesLocation);

            var requirementsTxt = Path.Combine(functionAppRoot, Constants.RequirementsTxt);

            var packApp = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "tools", "python", "packapp");

            var exe      = new Executable("python", $"{packApp} --platform linux --python-version 36 --packages-dir-name {Constants.ExternalPythonPackages} {functionAppRoot}");
            var sbErrors = new StringBuilder();
            var exitCode = await exe.RunAsync(o => ColoredConsole.WriteLine(o), e => sbErrors.AppendLine(e));

            if (exitCode != 0)
            {
                throw new CliException("There was an error restoring dependencies." + sbErrors.ToString());
            }

            return(packagesLocation);
        }
Exemplo n.º 19
0
        public IEnumerable <SftpFileInfo> ListDirectory(string path, Action <int> progress)
        {
            ColoredConsole.WriteLine(ConsoleColor.Cyan, "LocalFile: Listing directory {0}...", path);
            var dirs = Directory.EnumerateDirectories(GetLocalPath(path))
                       .Select(x => new SftpFileInfo()
            {
                Name        = Path.GetFileName(x),
                Length      = 0L,
                IsDirectory = true
            });
            var files = Directory.EnumerateFiles(GetLocalPath(path))
                        .Select(x => new SftpFileInfo()
            {
                Name        = Path.GetFileName(x),
                Length      = new FileInfo(x).Length,
                IsDirectory = false
            });

            ColoredConsole.WriteLine(ConsoleColor.Green, "LocalFile: Directory {0} is listed.", path);
            return(dirs.Concat(files));
        }
Exemplo n.º 20
0
        public async Task PublishZipDeploy(Site functionApp, Func <Task <Stream> > zipFileFactory)
        {
            await RetryHelper.Retry(async() =>
            {
                using (var handler = new ProgressMessageHandler(new HttpClientHandler()))
                    using (var client = GetRemoteZipClient(new Uri($"https://{functionApp.ScmUri}"), handler))
                        using (var request = new HttpRequestMessage(HttpMethod.Post, new Uri("api/zipdeploy", UriKind.Relative)))
                        {
                            request.Headers.IfMatch.Add(EntityTagHeaderValue.Any);

                            ColoredConsole.WriteLine("Creating archive for current directory...");

                            (var content, var length) = CreateStreamContentZip(await zipFileFactory());
                            request.Content           = content;

                            HttpResponseMessage response = await PublishHelper.InvokeLongRunningRequest(client, handler, request, length, "Uploading");
                            await PublishHelper.CheckResponseStatusAsync(response, "uploading archive");
                            ColoredConsole.WriteLine("Upload completed successfully.");
                        }
            }, 2);
        }
        public async override Task RunAsync()
        {
            var extensionsProj = await ExtensionsHelper.EnsureExtensionsProjectExistsAsync();

            var args = $"add {extensionsProj} package {Package} --version {Version}";

            if (!string.IsNullOrEmpty(Source))
            {
                args += $" --source {Source}";
            }

            var addPackage = new Executable("dotnet", args);
            await addPackage.RunAsync(output => ColoredConsole.WriteLine(output), error => ColoredConsole.WriteLine(ErrorColor(error)));

            var syncAction = new SyncExtensionsAction()
            {
                OutputPath = OutputPath
            };

            await syncAction.RunAsync();
        }
        private async Task WriteLaunchJson()
        {
            var setupNodeDebugResult = await DebuggerHelper.TrySetupDebuggerAsync();

            if (setupNodeDebugResult == DebuggerStatus.Created)
            {
                ColoredConsole.WriteLine("Created launch.json");
            }
            else if (setupNodeDebugResult == DebuggerStatus.Updated)
            {
                ColoredConsole.WriteLine("Added Azure Functions attach target to existing launch.json");
            }
            else if (setupNodeDebugResult == DebuggerStatus.AlreadyCreated)
            {
                ColoredConsole.WriteLine("launch.json already configured. Skipped!");
            }
            else if (setupNodeDebugResult == DebuggerStatus.Error)
            {
                ColoredConsole.Error.WriteLine(ErrorColor("Unable to configure launch.json. Check the file for more info"));
            }
        }
        private static async Task RestorePythonRequirementsPackapp(string functionAppRoot, string packagesLocation)
        {
            var packApp = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "tools", "python", "packapp");

            var exe      = new Executable("python", $"\"{packApp}\" --platform linux --python-version 36 --packages-dir-name {Constants.ExternalPythonPackages} \"{functionAppRoot}\"");
            var sbErrors = new StringBuilder();
            var exitCode = await exe.RunAsync(o => ColoredConsole.WriteLine(o), e => sbErrors.AppendLine(e));

            if (exitCode != 0)
            {
                var errorMessage = "There was an error restoring dependencies." + sbErrors.ToString();
                // If --build-native-deps if required, we exit with this specific code to notify other toolings
                // If this exit code changes, partner tools must be updated
                if (exitCode == ExitCodes.BuildNativeDepsRequired)
                {
                    ColoredConsole.WriteLine(ErrorColor(errorMessage));
                    Environment.Exit(ExitCodes.BuildNativeDepsRequired);
                }
                throw new CliException(errorMessage);
            }
        }
        private void ValidateAppSettings(Dictionary <string, string> appSettings, Site functionApp)
        {
            if (!appSettings.ContainsKey("AzureWebJobsStorage") && functionApp.IsDynamic)
            {
                throw new CliException($"'{FunctionAppName}' app is missing AzureWebJobsStorage app setting. That setting is required for publishing.");
            }

            if (appSettings.ContainsKey("WEBSITE_CONTENTAZUREFILECONNECTIONSTRING"))
            {
                if (Force)
                {
                    ColoredConsole.WriteLine(WarningColor($"Removing Azure Files from '{FunctionAppName}' because --force was passed"));
                    appSettings.Remove("WEBSITE_CONTENTSHARE");
                    appSettings.Remove("WEBSITE_CONTENTAZUREFILECONNECTIONSTRING");
                }
                else
                {
                    throw new CliException("Your app is configured with Azure Files for editing from Azure Portal.\nTo force publish use --force. This will remove Azure Files from your app.");
                }
            }
        }
Exemplo n.º 25
0
        public static async Task <Stream> GetAppZipFile(string functionAppRoot, bool buildNativeDeps, BuildOption buildOption, bool noBuild, GitIgnoreParser ignoreParser = null, string additionalPackages = null, bool ignoreDotNetCheck = false)
        {
            var gitIgnorePath = Path.Combine(functionAppRoot, Constants.FuncIgnoreFile);

            if (ignoreParser == null && FileSystemHelpers.FileExists(gitIgnorePath))
            {
                ignoreParser = new GitIgnoreParser(await FileSystemHelpers.ReadAllTextFromFileAsync(gitIgnorePath));
            }

            if (noBuild)
            {
                ColoredConsole.WriteLine(Yellow("Skipping build event for functions project (--no-build)."));
            }
            else if (buildOption == BuildOption.Remote)
            {
                ColoredConsole.WriteLine(Yellow("Performing remote build for functions project."));
            }
            else if (buildOption == BuildOption.Local)
            {
                ColoredConsole.WriteLine(Yellow("Performing local build for functions project."));
            }

            if (GlobalCoreToolsSettings.CurrentWorkerRuntime == WorkerRuntime.python && !noBuild)
            {
                return(await PythonHelpers.GetPythonDeploymentPackage(FileSystemHelpers.GetLocalFiles(functionAppRoot, ignoreParser), functionAppRoot, buildNativeDeps, buildOption, additionalPackages));
            }
            else if (GlobalCoreToolsSettings.CurrentWorkerRuntime == WorkerRuntime.dotnet && !ignoreDotNetCheck && !noBuild && buildOption != BuildOption.Remote)
            {
                throw new CliException("Pack command doesn't work for dotnet functions");
            }
            else if (GlobalCoreToolsSettings.CurrentWorkerRuntime == WorkerRuntime.dotnet && buildOption == BuildOption.Remote)
            {
                // Remote build for dotnet does not require bin and obj folders. They will be generated during the oryx build
                return(await CreateZip(FileSystemHelpers.GetLocalFiles(functionAppRoot, ignoreParser, false, new string[] { "bin", "obj" }), functionAppRoot));
            }
            else
            {
                return(await CreateZip(FileSystemHelpers.GetLocalFiles(functionAppRoot, ignoreParser, false), functionAppRoot));
            }
        }
        public override async Task RunAsync()
        {
            var subscriptions = await AzureHelper.GetSubscriptions(AccessToken, ManagementURL);

            ColoredConsole.WriteLine("Retrieving Function App...");
            var functionApp = await AzureHelper.GetFunctionApp(FunctionAppName, AccessToken, ManagementURL, allSubs : subscriptions);

            if (UseBrowser)
            {
                await OpenLiveStreamInBrowser(functionApp, subscriptions);

                return;
            }

            if (functionApp.IsLinux && functionApp.IsDynamic)
            {
                throw new CliException("Log stream is not currently supported in Linux Consumption Apps. " +
                                       "Please use --browser to open Azure Application Insights Live Stream in the Azure portal.");
            }
            var basicHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{functionApp.PublishingUserName}:{functionApp.PublishingPassword}"));

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", basicHeaderValue);
                client.DefaultRequestHeaders.Add("User-Agent", Constants.CliUserAgent);
                var response = await client.GetStreamAsync(new Uri($"https://{functionApp.ScmUri}/api/logstream/application"));

                using (var reader = new StreamReader(response))
                {
                    var buffer = new char[4096];
                    var count  = 0;
                    do
                    {
                        count = await reader.ReadAsync(buffer, 0, buffer.Length);

                        ColoredConsole.Write(new string(buffer.Take(count).ToArray()));
                    } while (count != 0);
                }
            }
        }
Exemplo n.º 27
0
        public override async Task RunAsync()
        {
            var workerRuntime = WorkerRuntimeLanguageHelper.GetCurrentWorkerRuntimeLanguage(_secretsManager);

            if (workerRuntime == WorkerRuntime.None)
            {
                ColoredConsole.WriteLine(WarningColor("your worker runtime is not set. As of 2.0.1-beta.26 a worker runtime setting is required."))
                .WriteLine(WarningColor($"Please run `{AdditionalInfoColor($"func settings add {Constants.FunctionsWorkerRuntime} <option>")}` or add {Constants.FunctionsWorkerRuntime} to your local.settings.json"))
                .WriteLine(WarningColor($"Available options: {WorkerRuntimeLanguageHelper.AvailableWorkersRuntimeString}"));
            }

            await PreRunConditions(workerRuntime);

            Utilities.PrintLogo();
            Utilities.PrintVersion();

            var settings = SelfHostWebHostSettingsFactory.Create(Environment.CurrentDirectory);

            (var listenUri, var baseUri, var certificate) = await Setup();

            IWebHost host = await BuildWebHost(settings, workerRuntime, listenUri, certificate);

            var runTask = host.RunAsync();

            var hostService = host.Services.GetRequiredService <WebJobsScriptHostService>();

            await hostService.DelayUntilHostReady();

            ColoredConsole.WriteLine($"Listening on {listenUri}");
            ColoredConsole.WriteLine("Hit CTRL-C to exit...");

            var scriptHost  = hostService.Services.GetRequiredService <IScriptJobHost>();
            var httpOptions = hostService.Services.GetRequiredService <IOptions <HttpOptions> >();

            DisplayHttpFunctionsInfo(scriptHost, httpOptions.Value, baseUri);
            DisplayDisabledFunctions(scriptHost);
            await SetupDebuggerAsync(baseUri);

            await runTask;
        }
        internal static X509Certificate2 GetOrCreateCertificate(string certPath, string certPassword)
        {
            if (!string.IsNullOrEmpty(certPath) && !string.IsNullOrEmpty(certPassword))
            {
                certPassword = File.Exists(certPassword)
                    ? File.ReadAllText(certPassword).Trim()
                    : certPassword;
                return(new X509Certificate2(certPath, certPassword));
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                ColoredConsole
                .WriteLine("Auto cert generation is currently not working on the .NET Core build.")
                .WriteLine("On Windows you can run:")
                .WriteLine()
                .Write(DarkCyan("PS> "))
                .WriteLine($"$cert = {Yellow("New-SelfSignedCertificate")} -Subject localhost -DnsName localhost -FriendlyName \"Functions Development\" -KeyUsage DigitalSignature -TextExtension @(\"2.5.29.37={{text}}1.3.6.1.5.5.7.3.1\")")
                .Write(DarkCyan("PS> "))
                .WriteLine($"{Yellow("Export-PfxCertificate")} -Cert $cert -FilePath certificate.pfx -Password (ConvertTo-SecureString -String {Red("<password>")} -Force -AsPlainText)")
                .WriteLine()
                .WriteLine("For more checkout https://docs.microsoft.com/en-us/aspnet/core/security/https")
                .WriteLine();
            }
            else
            {
                ColoredConsole
                .WriteLine("Auto cert generation is currently not working on the .NET Core build.")
                .WriteLine("On Unix you can run:")
                .WriteLine()
                .Write(DarkGreen("sh> "))
                .WriteLine("openssl req -new -x509 -newkey rsa:2048 -keyout localhost.key -out localhost.cer -days 365 -subj /CN=localhost")
                .Write(DarkGreen("sh> "))
                .WriteLine("openssl pkcs12 -export -out certificate.pfx -inkey localhost.key -in localhost.cer")
                .WriteLine()
                .WriteLine("For more checkout https://docs.microsoft.com/en-us/aspnet/core/security/https")
                .WriteLine();
            }

            throw new CliException("Auto cert generation is currently not working on the .NET Core build.");
        }
Exemplo n.º 29
0
        static void Main(string[] args)
        {
            var actorSystem = ActorSystem.Create("ConsoleApp");

            ColoredConsole.WriteLineGreen($"{actorSystem.Name} Actor System Created.");

            // start the Application Actors
            // var consoleUi = actorSystem.ActorOf<ConsoleUiActor>("ConsoleUi");
            var consoleUi = actorSystem.ActorOf(Props.Create <ConsoleUiActor>(), "ConsoleUi");

            consoleUi.Tell("start");

            // actorSystem.Terminate();

            // wait for the actor system to terminate
            ColoredConsole.WriteLine("Awaiting for ActorSystem Termination.");
            actorSystem.WhenTerminated.Wait();
            ColoredConsole.WriteLine("ActorSystem Terminated.");

            ColoredConsole.WriteLine("Press 'enter' to exit.");
            Console.ReadLine();
        }
        public void Report(int progressPercentage)
        {
            if (isCompleted || Console.IsOutputRedirected)
            {
                return;
            }

            var tick = this.width * progressPercentage / 100;
            var diff = tick - completed;

            completed = tick;
            for (var i = 0; i < diff; i++)
            {
                ColoredConsole.Write('#');
            }

            if (tick == width)
            {
                ColoredConsole.WriteLine(']');
                isCompleted = true;
            }
        }