private static async Task <(string output, string error)> RunDockerCommand(string args, string containerId = null, bool ignoreError = false)
        {
            var printArgs = string.IsNullOrWhiteSpace(containerId)
                ? args
                : args.Replace(containerId, containerId.Substring(0, 6));

            ColoredConsole.Write($"Running 'docker {printArgs}'.");
            var task = InternalRunDockerCommand(args, ignoreError);

            while (!task.IsCompleted)
            {
                await Task.Delay(TimeSpan.FromSeconds(1));

                ColoredConsole.Write(".");
            }
            ColoredConsole.WriteLine("done");

            (var output, var error) = await task;

            if (StaticSettings.IsDebug)
            {
                ColoredConsole
                .WriteLine($"Output: {output}")
                .WriteLine($"Error: {error}");
            }
            return(output, error);
        }
        public SimpleProgressBar(string title)
        {
            try
            {
                var bufferWidth = Console.BufferWidth;
                bufferWidth = bufferWidth > 100 ? 100 : bufferWidth;
                this.width  = bufferWidth - (title.Length + 4);

                ColoredConsole.Write(title);

                ColoredConsole.Write(" [");

                for (var i = 0; i < width; i++)
                {
                    ColoredConsole.Write('-');
                }

                ColoredConsole.Write("]");

                for (var i = 0; i < width + 1; i++)
                {
                    ColoredConsole.Write('\b');
                }
            }
            catch
            {
                isCompleted = true;
                ColoredConsole.WriteLine();
            }
        }
        public void Write(string message, ConsoleColor?background, ConsoleColor?foreground)
        {
            ConsoleColor color = foreground ?? Console.ForegroundColor;
            var          value = ColorString(message, color);

            ColoredConsole.Write(value);
        }
        public static async Task <DeployStatus> WaitForDedicatedBuildToComplete(HttpClient client, Site functionApp)
        {
            // There is a tracked Locking issue in kudulite causing Race conditions, so we have to use this API
            // to gather deployment progress.
            ColoredConsole.Write("Remote build in progress, please wait");
            while (true)
            {
                var json = await InvokeRequest <IDictionary <string, string> >(client, HttpMethod.Get, "/api/isdeploying");

                if (bool.TryParse(json["value"], out bool isDeploying))
                {
                    if (!isDeploying)
                    {
                        string deploymentId = await GetLatestDeploymentId(client, functionApp, restrictedToken : null);

                        DeployStatus status = await GetDeploymentStatusById(client, functionApp, restrictedToken : null, id : deploymentId);

                        ColoredConsole.Write($"done{Environment.NewLine}");
                        return(status);
                    }
                }
                else
                {
                    throw new CliException($"Expected \"value\" from /api/isdeploying endpoing to be a boolean. Actual: {json["value"]}");
                }

                ColoredConsole.Write(".");
                await Task.Delay(5000);
            }
        }
Exemplo n.º 5
0
        protected virtual Part ReadPart(ref int referencecounter)
        {
            var part    = new Part();
            var int32_1 = BigEndianBitConverter.ToInt32(fileData, iPos);

            ColoredConsole.WriteLine("{0:x8}     Number of Vertex Lists: 0x{1:x8}", (object)iPos, (object)int32_1);
            iPos += 4;
            for (var index = 0; index < int32_1; ++index)
            {
                ColoredConsole.WriteLine("{0:x8}       Vertex List 0x{1:x8}", (object)iPos, (object)index);
                part.VertexListReferences1.Add(GetVertexListReference(ref referencecounter, out var _));
            }
            iPos += 4;
            part.IndexListReference1 = GetIndexListReference(ref referencecounter);
            part.OffsetIndices       = BigEndianBitConverter.ToInt32(fileData, iPos);
            ColoredConsole.WriteLine("{0:x8}     Offset Indices: 0x{1:x8}", (object)iPos, (object)part.OffsetIndices);
            iPos += 4;
            part.NumberIndices = BigEndianBitConverter.ToInt32(fileData, iPos);
            ColoredConsole.WriteLine("{0:x8}     Number Indices: 0x{1:x8}", (object)iPos, (object)part.NumberIndices);
            iPos += 4;
            part.OffsetVertices = BigEndianBitConverter.ToInt32(fileData, iPos);
            ColoredConsole.WriteLine("{0:x8}     Offset Vertices: 0x{1:x8}", (object)iPos, (object)part.OffsetVertices);
            iPos += 4;
            if (BigEndianBitConverter.ToInt16(fileData, iPos) != (short)0)
            {
                throw new NotSupportedException("ReadPart Offset Vertices + 4");
            }
            iPos += 2;
            part.NumberVertices = BigEndianBitConverter.ToInt32(fileData, iPos);
            ColoredConsole.WriteLine("{0:x8}     Number Vertices: 0x{1:x8}", (object)iPos, (object)part.NumberVertices);
            iPos += 4;
            ++referencecounter;
            byte lastByte = 0;

            iPos += 4;
            var int32_2 = BigEndianBitConverter.ToInt32(fileData, iPos);

            iPos += 4;
            if (int32_2 > 0)
            {
                ColoredConsole.Write("{0:x8}     ", (object)iPos);
                for (var index = 0; index < int32_2; ++index)
                {
                    ColoredConsole.Write("{0:x2} ", (object)fileData[iPos]);
                    lastByte = fileData[iPos];
                    ++iPos;
                }
                ColoredConsole.WriteLine();
                ++referencecounter;
            }
            var int32_3 = BigEndianBitConverter.ToInt32(fileData, iPos);

            iPos += 4;
            if (int32_3 != 0)
            {
                var num = ReadRelativePositionList(lastByte);
                referencecounter += num;
            }
            return(part);
        }
Exemplo n.º 6
0
        private static (WorkerRuntime, string) ResolveWorkerRuntimeAndLanguage(string workerRuntimeString, string languageString)
        {
            WorkerRuntime workerRuntime;
            string        language;

            if (!string.IsNullOrEmpty(workerRuntimeString))
            {
                workerRuntime = WorkerRuntimeLanguageHelper.NormalizeWorkerRuntime(workerRuntimeString);
                language      = languageString ?? WorkerRuntimeLanguageHelper.NormalizeLanguage(workerRuntimeString);
            }
            else if (GlobalCoreToolsSettings.CurrentWorkerRuntimeOrNone == Helpers.WorkerRuntime.None)
            {
                ColoredConsole.Write("Select a worker runtime: ");
                workerRuntime = SelectionMenuHelper.DisplaySelectionWizard(WorkerRuntimeLanguageHelper.AvailableWorkersList);
                ColoredConsole.WriteLine(TitleColor(workerRuntime.ToString()));
                language = LanguageSelectionIfRelevant(workerRuntime);
            }
            else
            {
                workerRuntime = GlobalCoreToolsSettings.CurrentWorkerRuntime;
                language      = GlobalCoreToolsSettings.CurrentLanguageOrNull ?? languageString ?? WorkerRuntimeLanguageHelper.NormalizeLanguage(workerRuntime.ToString());
            }

            return(workerRuntime, language);
        }
        private static (WorkerRuntime, string) ResolveWorkerRuntimeAndLanguage(string workerRuntimeString, string languageString)
        {
            WorkerRuntime workerRuntime;
            string        language;

            if (!string.IsNullOrEmpty(workerRuntimeString))
            {
                workerRuntime = WorkerRuntimeLanguageHelper.NormalizeWorkerRuntime(workerRuntimeString);
                language      = languageString ?? WorkerRuntimeLanguageHelper.NormalizeLanguage(workerRuntimeString);
            }
            else if (GlobalCoreToolsSettings.CurrentWorkerRuntimeOrNone == Helpers.WorkerRuntime.None)
            {
                ColoredConsole.Write("Select a worker runtime: ");
                IDictionary <WorkerRuntime, string> workerRuntimeToDisplayString = WorkerRuntimeLanguageHelper.GetWorkerToDisplayStrings();
                workerRuntimeString = SelectionMenuHelper.DisplaySelectionWizard(workerRuntimeToDisplayString.Values);
                workerRuntime       = workerRuntimeToDisplayString.FirstOrDefault(wr => wr.Value.Equals(workerRuntimeString)).Key;
                ColoredConsole.WriteLine(TitleColor(workerRuntime.ToString()));
                language = LanguageSelectionIfRelevant(workerRuntime);
            }
            else
            {
                workerRuntime = GlobalCoreToolsSettings.CurrentWorkerRuntime;
                language      = GlobalCoreToolsSettings.CurrentLanguageOrNull ?? languageString ?? WorkerRuntimeLanguageHelper.NormalizeLanguage(workerRuntime.ToString());
            }

            return(workerRuntime, language);
        }
        public override async Task RunAsync()
        {
            var functionApp = await AzureHelper.GetFunctionApp(FunctionAppName, AccessToken, ManagementURL);

            if (functionApp.IsLinux && functionApp.IsDynamic)
            {
                throw new CliException("Log stream is not currently supported in Linux Consumption Apps. Please use 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);
                }
            }
        }
        private static T DisplaySelectionWizardUnix <T>(IEnumerable <T> options)
        {
            if (!options.Any())
            {
                return(default(T));
            }

            // The windows one expects to remain on the same line, but not this version.
            ColoredConsole.WriteLine();

            var optionsArray = options.ToArray();

            for (var i = 0; i < optionsArray.Length; i++)
            {
                ColoredConsole.WriteLine($"{i + 1}. {optionsArray[i].ToString()}");
            }

            while (true)
            {
                ColoredConsole.Write(TitleColor("Choose option: "));
                var response = Console.ReadLine();
                if (int.TryParse(response, out int selection))
                {
                    selection -= 1;

                    if (selection == 0 || (selection > 0 && selection < optionsArray.Length))
                    {
                        return(optionsArray[selection]);
                    }
                }
            }
        }
        public async Task Rewind(string connectionStringKey, string taskHubName, string instanceId, string reason)
        {
            Initialize(out _orchestrationService, out _client, connectionStringKey, taskHubName);

            var oldStatus = await _client.GetOrchestrationStateAsync(instanceId, false);

            try
            {
                await _orchestrationService.RewindTaskOrchestrationAsync(instanceId, reason);
            }
            catch (ArgumentOutOfRangeException e)
            {
                // DurableTask.AzureStorage throws this error when it cannot find an orchestration instance matching the query
                throw new CliException("Orchestration instance not rewound. Must have a status of 'Failed', or an EventType of 'TaskFailed' or 'SubOrchestrationInstanceFailed' to be rewound.");
            }

            ColoredConsole.WriteLine($"Rewind message sent to instance '{instanceId}'. Retrieving new status now...");

            // Wait three seconds before retrieving the updated status
            await Task.Delay(3000);

            var newStatus = await _client.GetOrchestrationStateAsync(instanceId, false);

            if (oldStatus != null && oldStatus.Count > 0 &&
                newStatus != null && newStatus.Count > 0)
            {
                ColoredConsole.Write(Green("Status before rewind: "));
                ColoredConsole.WriteLine($"{oldStatus[0].OrchestrationStatus}");
                ColoredConsole.Write(Green("Status after rewind: "));
                ColoredConsole.WriteLine($"{newStatus[0].OrchestrationStatus}");
            }
        }
Exemplo n.º 11
0
        private void PostInit()
        {
            if (InitDocker)
            {
                ColoredConsole
                .WriteLine()
                .WriteLine(Yellow("Next Steps:"));
            }

            if (InitDocker)
            {
                ColoredConsole
                .Write(Green("Run> "))
                .WriteLine(DarkCyan("docker build -t <image name> ."));

                ColoredConsole
                .WriteLine("to build a docker image with your functions")
                .WriteLine();

                ColoredConsole
                .Write(Green("Run> "))
                .WriteLine(DarkCyan("docker run -p 8080:80 -it <image name>"));

                ColoredConsole
                .WriteLine("To run the container then trigger your function on port 8080.")
                .WriteLine();
            }
        }
Exemplo n.º 12
0
        public static async Task RunAsync <T>(string[] args, IContainer container)
        {
            var app    = new ConsoleApp(args, typeof(T).Assembly, container);
            var action = app.Parse();

            // If all goes well, we will have an action to run.
            // This action can be an actual action, or just a HelpAction, but this method doesn't care
            // since HelpAction is still an IAction.
            if (action != null)
            {
                try
                {
                    // All Actions are async. No return value is expected from any action.
                    await action.RunAsync();
                }
                catch (Exception ex)
                {
                    if (StaticSettings.IsDebug)
                    {
                        // If CLI is in debug mode, display full call stack.
                        ColoredConsole.Error.WriteLine(ErrorColor(ex.ToString()));
                    }
                    else
                    {
                        ColoredConsole.Error.WriteLine(ErrorColor(ex.Message));
                    }

                    if (args.Any(a => a.Equals("--pause-on-error", StringComparison.OrdinalIgnoreCase)))
                    {
                        ColoredConsole.Write("Press any to continue....");
                        Console.ReadKey(true);
                    }
                }
            }
        }
        public async override Task RunAsync()
        {
            if (Console.IsOutputRedirected || Console.IsInputRedirected)
            {
                if (string.IsNullOrEmpty(TemplateName) ||
                    string.IsNullOrEmpty(FunctionName))
                {
                    ColoredConsole
                    .Error
                    .WriteLine(ErrorColor("Running with stdin\\stdout redirected. Command must specify --template, and --name explicitly."))
                    .WriteLine(ErrorColor("See 'func help function' for more details"));
                    return;
                }
            }

            var templates = await _templatesManager.Templates;

            templates = templates.Concat(_templatesManager.PythonTemplates);

            var language = _secretsManager.GetSecrets().FirstOrDefault(s => s.Key.Equals(Constants.FunctionsLanguageSetting, StringComparison.OrdinalIgnoreCase)).Value;

            if (string.IsNullOrWhiteSpace(language))
            {
                ColoredConsole.Write("Select a language: ");
                language = Language ?? SelectionMenuHelper.DisplaySelectionWizard(templates.Select(t => t.Metadata.Language).Distinct());

                ColoredConsole.WriteLine(TitleColor(language));

                language = InitAction.NormalizeLanguage(language);

                _secretsManager.SetSecret(Constants.FunctionsLanguageSetting, language);
                ColoredConsole
                .WriteLine(WarningColor("Starting from 2.0.1-beta.26 it's required to set a language for your project in your settings"))
                .WriteLine(WarningColor($"'{language}' has been set in your local.settings.json"));
            }

            if (language.Equals("csharp", StringComparison.OrdinalIgnoreCase))
            {
                language = "C#";
            }

            ColoredConsole.Write("Select a template: ");
            var name = TemplateName ?? SelectionMenuHelper.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);
            }
        }
        public async Task DeleteTaskHub(string connectionStringKey, string taskHubName)
        {
            Initialize(out _orchestrationService, out _client, connectionStringKey, taskHubName);

            await _orchestrationService.DeleteAsync();

            ColoredConsole.Write(Green($"Task hub '{_taskHubName}' successfully deleted."));
        }
        private async Task <Uri> RecursiveDiscoverServer(int iteration, bool noInteractive)
        {
            var server = new Uri($"http://localhost:{Port + iteration}");

            if (!await server.IsServerRunningAsync())
            {
                // create the server
                if (_settings.DisplayLaunchingRunServerWarning && !noInteractive)
                {
                    ColoredConsole
                    .WriteLine()
                    .WriteLine("We need to launch a server that will host and run your functions.")
                    .WriteLine("The server will auto load any changes you make to the function.");
                    string answer = null;
                    do
                    {
                        ColoredConsole
                        .Write(QuestionColor("Do you want to always display this warning before launching a new server [yes/no]? [yes] "));

                        answer = Console.ReadLine()?.Trim()?.ToLowerInvariant();
                        answer = string.IsNullOrEmpty(answer) ? "yes" : answer;
                    } while (answer != "yes" && answer != "no");
                    _settings.DisplayLaunchingRunServerWarning = answer == "yes" ? true : false;
                }

                //TODO: factor out to PlatformHelper.LaunchInNewConsole and implement for Mac using AppleScript
                var exeName = System.Reflection.Assembly.GetEntryAssembly().Location;
                var exe     = PlatformHelper.IsWindows
                    ? new Executable(exeName, $"host start -p {Port + iteration} --pause-on-error", streamOutput: false, shareConsole: true)
                    : new Executable("mono", $"{exeName} host start -p {Port + iteration} --pause-on-error", streamOutput: false, shareConsole: false);

                exe.RunAsync().Ignore();
                await Task.Delay(500);

                if (PlatformHelper.IsWindows)
                {
                    ConsoleNativeMethods.GetFocusBack();
                }

                return(server);
            }
            else
            {
                if (await IsRightServer(server))
                {
                    return(server);
                }
                else
                {
                    return(await RecursiveDiscoverServer(iteration + 1, noInteractive));
                }
            }
        }
Exemplo n.º 16
0
 public string GetProxy(string name)
 {
     if (Proxies.ContainsKey(name))
     {
         return(JsonConvert.SerializeObject(Proxies[name], Formatting.Indented));
     }
     else
     {
         ColoredConsole.Write($"A proxy with the name {name} does not exist.");
         return(string.Empty);
     }
 }
Exemplo n.º 17
0
 private void LanguageSelectionIfRelevant(WorkerRuntime workerRuntime)
 {
     if (workerRuntime == Helpers.WorkerRuntime.node)
     {
         if (WorkerRuntimeLanguageHelper.WorkerToSupportedLanguages.TryGetValue(workerRuntime, out IEnumerable <string> languages) &&
             languages.Count() != 0)
         {
             ColoredConsole.Write("Select a Language: ");
             Language = SelectionMenuHelper.DisplaySelectionWizard(languages);
             ColoredConsole.WriteLine(TitleColor(Language));
         }
     }
 }
 public static void DisplaySelectionWizardPrompt(string selectionItem)
 {
     if (IsEnvironmentCursorTopFriendly())
     {
         // windows
         ColoredConsole.Write("Use the up/down arrow keys to select a " + selectionItem + ":");
     }
     else
     {
         // *nix/generic
         ColoredConsole.Write("Select a number for " + selectionItem + ":");
     }
 }
Exemplo n.º 19
0
 private static void SetupGlobalExceptionHandler()
 {
     AppDomain.CurrentDomain.UnhandledException += (s, e) =>
     {
         if (e.IsTerminating)
         {
             ColoredConsole.Error.WriteLine(ErrorColor(e.ExceptionObject.ToString()));
             ColoredConsole.Write("Press any to continue....");
             Console.ReadKey(true);
             Environment.Exit(ExitCodes.GeneralError);
         }
     };
 }
Exemplo n.º 20
0
        private void PrintTargetsToRun(Node start, Node end)
        {
            while (start != null)
            {
                ColoredConsole.Write($"{start.Name} ==> ".Magenta());
                if (start == end)
                {
                    break;
                }

                start = start.Next;
            }
            ColoredConsole.WriteLine("DONE".Magenta());
        }
Exemplo n.º 21
0
        public override async Task RunAsync()
        {
            if (SourceControl != SourceControl.Git)
            {
                throw new Exception("Only Git is supported right now for vsc");
            }

            if (!string.IsNullOrEmpty(FolderName))
            {
                var folderPath = Path.Combine(Environment.CurrentDirectory, FolderName);
                FileSystemHelpers.EnsureDirectory(folderPath);
                Environment.CurrentDirectory = folderPath;
            }

            WorkerRuntime workerRuntime;

            if (Csx)
            {
                workerRuntime = Helpers.WorkerRuntime.dotnet;
            }
            else if (string.IsNullOrEmpty(WorkerRuntime))
            {
                ColoredConsole.Write("Select a worker runtime: ");
                IDictionary <WorkerRuntime, string> workerRuntimeToDisplayString = WorkerRuntimeLanguageHelper.GetWorkerToDisplayStrings();
                var workerRuntimeString = SelectionMenuHelper.DisplaySelectionWizard(workerRuntimeToDisplayString.Values);
                workerRuntime = workerRuntimeToDisplayString.FirstOrDefault(wr => wr.Value.Equals(workerRuntimeString)).Key;
                ColoredConsole.WriteLine(TitleColor(workerRuntime.ToString()));
                LanguageSelectionIfRelevant(workerRuntime);
            }
            else
            {
                workerRuntime = WorkerRuntimeLanguageHelper.NormalizeWorkerRuntime(WorkerRuntime);
                Language      = Language ?? WorkerRuntimeLanguageHelper.NormalizeLanguage(WorkerRuntime);
            }

            if (workerRuntime == Helpers.WorkerRuntime.dotnet && !Csx)
            {
                await DotnetHelpers.DeployDotnetProject(Utilities.SanitizeLiteral(Path.GetFileName(Environment.CurrentDirectory), allowed: "-"), Force);
            }
            else
            {
                await InitLanguageSpecificArtifacts(workerRuntime);
                await WriteFiles();
                await WriteLocalSettingsJson(workerRuntime);
            }

            await WriteExtensionsJson();
            await SetupSourceControl();
            await WriteDockerfile(workerRuntime);
        }
Exemplo n.º 22
0
        public async Task Deploy(string Name, Template template)
        {
            var path = Path.Combine(Environment.CurrentDirectory, Name);

            if (FileSystemHelpers.DirectoryExists(path))
            {
                var response = "n";
                do
                {
                    ColoredConsole.Write($"A directory with the name {Name} already exists. Overwrite [y/n]? [n] ");
                    response = Console.ReadLine();
                } while (response != "n" && response != "y");
                if (response == "n")
                {
                    return;
                }
            }

            if (FileSystemHelpers.DirectoryExists(path))
            {
                FileSystemHelpers.DeleteDirectorySafe(path, ignoreErrors: false);
            }

            FileSystemHelpers.EnsureDirectory(path);

            foreach (var file in template.Files.Where(kv => !kv.Key.EndsWith(".dat")))
            {
                var filePath = Path.Combine(path, file.Key);
                ColoredConsole.WriteLine($"Writing {filePath}");
                await FileSystemHelpers.WriteAllTextToFileAsync(filePath, file.Value);
            }
            var functionJsonPath = Path.Combine(path, "function.json");

            ColoredConsole.WriteLine($"Writing {functionJsonPath}");
            await FileSystemHelpers.WriteAllTextToFileAsync(functionJsonPath, JsonConvert.SerializeObject(template.Function, Formatting.Indented));

            if (template.Metadata.Extensions != null)
            {
                foreach (var extension in template.Metadata.Extensions)
                {
                    var installAction = new InstallExtensionAction(_secretsManager, false)
                    {
                        Package = extension.Id,
                        Version = extension.Version
                    };
                    await installAction.RunAsync();
                }
            }
        }
Exemplo n.º 23
0
        public override async Task RunAsync()
        {
            if (SourceControl != SourceControl.Git)
            {
                throw new Exception("Only Git is supported right now for vsc");
            }

            if (!string.IsNullOrEmpty(FolderName))
            {
                var folderPath = Path.Combine(Environment.CurrentDirectory, FolderName);
                FileSystemHelpers.EnsureDirectory(folderPath);
                Environment.CurrentDirectory = folderPath;
            }

            WorkerRuntime workerRuntime;

            if (Csx)
            {
                workerRuntime = Helpers.WorkerRuntime.dotnet;
            }
            else if (string.IsNullOrEmpty(WorkerRuntime))
            {
                ColoredConsole.Write("Select a worker runtime: ");
                workerRuntime = SelectionMenuHelper.DisplaySelectionWizard(WorkerRuntimeLanguageHelper.AvailableWorkersList);
                ColoredConsole.WriteLine(TitleColor(workerRuntime.ToString()));
            }
            else
            {
                workerRuntime = WorkerRuntimeLanguageHelper.NormalizeWorkerRuntime(WorkerRuntime);
            }

            if (workerRuntime == Helpers.WorkerRuntime.dotnet && !Csx)
            {
                await DotnetHelpers.DeployDotnetProject(Path.GetFileName(Environment.CurrentDirectory), Force);
            }
            else
            {
                await InitLanguageSpecificArtifacts(workerRuntime);
                await WriteFiles();
                await WriteLocalSettingsJson(workerRuntime);
            }

            await WriteExtensionsJson();
            await SetupSourceControl();
            await WriteDockerfile(workerRuntime);

            // PostInit();
        }
Exemplo n.º 24
0
 public override Task RunAsync()
 {
     if (string.IsNullOrEmpty(Value))
     {
         ColoredConsole.Write("Please enter the value: ");
         Value = SecurityHelpers.ReadPassword();
     }
     if (IsConnectionString)
     {
         _secretsManager.SetConnectionString(Name, Value);
     }
     else
     {
         _secretsManager.SetSecret(Name, Value);
     }
     return(Task.CompletedTask);
 }
        public async Task GetHistory(string connectionStringKey, string taskHubName, string instanceId)
        {
            Initialize(out _orchestrationService, out _client, connectionStringKey, taskHubName);

            var historyString = await _orchestrationService.GetOrchestrationHistoryAsync(instanceId, null);

            JArray history = JArray.Parse(historyString);

            JArray chronologicalHistory = new JArray(history.OrderBy(obj => (string)obj["TimeStamp"]));

            foreach (JObject jobj in chronologicalHistory)
            {
                // Convert EventType enum values to their equivalent string value
                Enum.TryParse(jobj["EventType"].ToString(), out EventType eventName);
                jobj["EventType"] = eventName.ToString();
            }

            ColoredConsole.Write($"{chronologicalHistory.ToString(Formatting.Indented)}");
        }
Exemplo n.º 26
0
        private static async Task <DateTime> DisplayDeploymentLog(HttpClient client, Site functionApp, string id, DateTime lastUpdate, Uri innerUrl = null, StringBuilder innerLogger = null)
        {
            string logUrl = innerUrl != null?innerUrl.ToString() : $"/deployments/{id}/log";

            StringBuilder sbLogger = innerLogger != null ? innerLogger : new StringBuilder();

            var json = await InvokeRequest <List <Dictionary <string, string> > >(client, HttpMethod.Get, logUrl);

            var      logs = json.Where(dict => DateTime.Parse(dict["log_time"]) > lastUpdate || dict["details_url"] != null);
            DateTime currentLogDatetime = lastUpdate;

            foreach (var log in logs)
            {
                // Filter out details_url log
                if (DateTime.Parse(log["log_time"]) > lastUpdate)
                {
                    sbLogger.AppendLine(log["message"]);
                }

                // Recursively log details_url from scm/api/deployments/xxx/log endpoint
                if (log["details_url"] != null && Uri.TryCreate(log["details_url"], UriKind.Absolute, out Uri detailsUrl))
                {
                    DateTime innerLogDatetime = await DisplayDeploymentLog(client, functionApp, id, currentLogDatetime, detailsUrl, sbLogger);

                    currentLogDatetime = innerLogDatetime > currentLogDatetime ? innerLogDatetime : currentLogDatetime;
                }
            }

            if (logs.LastOrDefault() != null)
            {
                DateTime lastLogDatetime = DateTime.Parse(logs.Last()["log_time"]);
                currentLogDatetime = lastLogDatetime > currentLogDatetime ? lastLogDatetime : currentLogDatetime;
            }

            // Report build status on the root level parser
            if (innerUrl == null && sbLogger.Length > 0)
            {
                ColoredConsole.Write(sbLogger.ToString());
            }

            return(currentLogDatetime);
        }
Exemplo n.º 27
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);
            }
        }
Exemplo n.º 28
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()
        {
            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!");
            }
        }
Exemplo n.º 30
0
 public void AddProxy(string name, ProxyDefinition proxyDefinition)
 {
     if (Proxies.ContainsKey(name))
     {
         var response = "n";
         do
         {
             ColoredConsole.Write($"A proxy with the name {name} already exists. Overwrite [y/n]? [n] ");
             response = Console.ReadLine();
         } while (response != "n" && response != "y");
         if (response == "n")
         {
             return;
         }
         Proxies[name] = proxyDefinition;
     }
     else
     {
         Proxies.Add(name, proxyDefinition);
     }
 }