/// <summary> /// start the execution of the scenario /// </summary> /// <param name="scenarioId">the scenario ID</param> public void StartSession(Guid scenarioId) { using (SessionConfigurationWizard wizard = new SessionConfigurationWizard(scenarioId)) { if (wizard.ShowDialog(this) == DialogResult.OK) { SessionTicket ticket = wizard.Ticket; SessionId = ticket.SessionId; // Set the display details from the ticket sessionId_Label.Text = ticket.SessionId; sessionName_Label.Text = ticket.SessionName; sessionOwner_Label.Text = ticket.SessionOwner.UserName; // Start the session start_ToolStripButton.Enabled = false; SessionClient.Instance.PowerUp(SessionId); } else { if (_transition != SessionStartupTransition.ReadyToStart && _transition != SessionStartupTransition.None) { ShutdownOptions options = new ShutdownOptions(); options.ShutdownDeviceSimulators = false; SessionClient.Instance.Shutdown(wizard.Ticket.SessionId, options); } } } }
static void SessionStateChanged(object sender, SessionStateEventArgs e) { if (e.SessionId.Equals(_ticket.SessionId)) { Console.WriteLine("{0}".FormatWith(e.State)); switch (e.State) { case SessionState.RunComplete: // This is a place where you could add logic to decide if you want to // Repeat() the run, or continue to shutdown. For now, we are just // going to shutdown. ShutdownOptions options = new ShutdownOptions() { AllowWorkerToComplete = false, CopyLogs = false, PowerOff = true, PowerOffOption = VMPowerOffOption.RevertToSnapshot }; SessionClient.Instance.Shutdown(_ticket.SessionId, options); break; case SessionState.ShutdownComplete: _isSessionCompleted = true; break; } } }
public static void QueueShutdown(string parameters, ShutdownOptions options = ShutdownOptions.Abort, string message = null, int gracePeriod = -1) { // If no user is logged in, skip trying to notify users if (!User.AnyLoggedIn()) { CreateTask(parameters, message); return; } // Check if a task is already in progress if (_timer != null && _timer.Enabled) { Log.Entry(LogName, "Power task already in-progress"); return; } Requested = true; _delayed = false; AggregatedDelayTime = 0; // Load the grace period from Settings or use the default one try { if (gracePeriod == -1) { gracePeriod = (!string.IsNullOrEmpty(Settings.Get("PromptTime"))) ? int.Parse(Settings.Get("PromptTime")) : DefaultGracePeriod * 60; } } catch (Exception) { gracePeriod = DefaultGracePeriod * 60; } // Generate the request data Log.Entry(LogName, $"Creating shutdown command in {gracePeriod} seconds"); _requestData = new JObject(); _requestData.action = "request"; _requestData.period = gracePeriod; _requestData.options = options; _requestData.command = parameters; _requestData.aggregatedDelayTime = AggregatedDelayTime; _requestData.message = message ?? string.Empty; Bus.Emit(Bus.Channel.Power, _requestData, true); _timer = new Timer(gracePeriod * 1000); _timer.Elapsed += TimerElapsed; _timer.Start(); }
/// <summary> /// Starts the session. /// </summary> /// <param name="wizard">The wizard form.</param> /// <param name="ticket">The ticket.</param> /// <returns><c>true</c> if start operation successful, <c>false</c> otherwise.</returns> public bool StartSession(Form wizard, SessionTicket ticket) { bool result = false; var activeSessions = GetActiveSessions().Count(); if (AbleToStartNewSession == false || activeSessions >= MAX_ACTIVE_SESSIONS) { MessageBox.Show(_treeView, "{0} active sessions out of {1} allowed".FormatWith(activeSessions, MAX_ACTIVE_SESSIONS), "Unable To Start Session"); return(result); } if (EnsureDispatcherConnected()) { try { AbleToStartNewSession = false; using (wizard) { var newSession = GetNewExecutingSessionInfo(ticket); if (wizard.ShowDialog(_sessionControl) == DialogResult.OK) { //SessionClient.Instance.PowerUp(newSession.SessionId); newSession.UpdateFromTicket(ticket); result = true; UpdateSessionInfoFromDatabaseAsynch(newSession, false); } else { var transition = newSession.StartupTransition; if (transition != SessionStartupTransition.ReadyToStart && transition != SessionStartupTransition.None) { ShutdownOptions options = new ShutdownOptions(); options.ShutdownDeviceSimulators = false; SessionClient.Instance.Shutdown(newSession.SessionId, options); newSession.State = SessionState.ShutdownComplete; } else { newSession.State = SessionState.Canceled; RemoveManagedSession(newSession); } } } } finally { AbleToStartNewSession = true; } } return(result); }
private void Instance_SessionStateReceived(object sender, SessionStateEventArgs e) { TraceFactory.Logger.Debug($"Session State received: {e.State} for Session {e.SessionId}"); switch (e.State) { case SessionState.RunComplete: { lock (e.SessionId) { var state = SessionClient.Instance.GetSessionState(e.SessionId); if (state != SessionState.ShuttingDown || state != SessionState.ShutdownComplete) { ShutdownOptions shutdownOptions = new ShutdownOptions { CopyLogs = true, ReleaseDeviceReservation = true }; TraceFactory.Logger.Debug($"Shutting down session {e.SessionId}"); SessionClient.Instance.Shutdown(e.SessionId, shutdownOptions); } } } break; case SessionState.ShutdownComplete: { lock (e.SessionId) { TraceFactory.Logger.Debug($"Shutdown complete for session {e.SessionId}"); StfSessionTicket sessionTicket; SessionExecutionDictionary.TryGetValue(e.SessionId, out sessionTicket); if (sessionTicket != null) { //this is a request coming from BTF, let's push data to the btf system if (!string.IsNullOrEmpty(sessionTicket.TestExecutionId)) { //post the data back SendExecutionLogs(e.SessionId, $"artifacts/{sessionTicket.TestArtificatsUrl}"); UpdateTestResult(e.SessionId); } SessionExecutionDictionary.TryRemove(e.SessionId, out sessionTicket); _isSessionExecuting = false; } } } break; } }
public StfWebApiService() : base("StfWebService", "STF Web Service") { Description = "Service to host Web Services for triggering STF Sessions"; _executionTimer.Elapsed += _executionTimer_Elapsed; _executionTimer.Enabled = false; NameValueCollection systems = ConfigurationManager.GetSection("Systems") as NameValueCollection; _btfMessagingServerName = systems["BtfMessageServer"]; _btfArtifactsServerName = systems["BtfArtifactsServer"]; _shutdownOptions = new ShutdownOptions { AllowWorkerToComplete = false, CopyLogs = false, PowerOff = true, PowerOffOption = VMPowerOffOption.PowerOff }; }
private static void WriteLogInFile(ShutdownType shutdownType, ShutdownOptions shutdownOptions, string pathToLogDirectory) { if (!string.IsNullOrEmpty(pathToLogDirectory)) { var filePath = $@"{pathToLogDirectory}\{DateTime.Now.ToString("dd-MM-yyyy")}.log"; //path to log file if (!File.Exists(filePath)) //if file is not exists { var createdFile = File.Create(filePath); //create it createdFile.Close(); //close created file to free process } using (var textWriter = new StreamWriter(filePath)) { textWriter.WriteLine($"{DateTime.Now} - {shutdownType.ToString()} - {shutdownOptions.ToString()}"); } } }
private void _shutdownTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { Invoke(new Action( () => { end_ToolStripButton.Enabled = false; dispatcherLog_ToolStripButton.Enabled = false; })); ShutdownOptions options = new ShutdownOptions() { AllowWorkerToComplete = false, CopyLogs = false, PowerOff = true, PowerOffOption = VMPowerOffOption.PowerOff }; SessionClient.Instance.Shutdown(SessionId, options); _shutdownTimer.Enabled = false; }
private void ShutDown() { ShutdownOptions options = new ShutdownOptions() { AllowWorkerToComplete = false, CopyLogs = true, PowerOff = true, PowerOffOption = VMPowerOffOption.RevertToSnapshot }; try { SessionClient.Instance.Shutdown(_ticket.SessionId, options); } catch (Exception ex) { UpdateStatus(ex.ToString()); TraceFactory.Logger.Error(ex); } }
/// <summary> /// Starts the automatic shut down. /// </summary> /// <param name="sessionId">The session identifier.</param> /// <exception cref="System.Exception">{0} is not a currently managed session</exception> public void StartAutoShutDown(string sessionId) { if (!IsManagedSession(sessionId)) { throw new Exception("{0} is not a currently managed session"); } try { // Check for system setting value on how long to wait before shutting down a completed session // ignore if no such setting exists string autoShutdownKey = "AutoShutdownTime"; if (GlobalSettings.Items.ContainsKey(autoShutdownKey)) { if (!string.IsNullOrEmpty(GlobalSettings.Items[autoShutdownKey])) { double autoShutdownTime = Convert.ToDouble(GlobalSettings.Items[autoShutdownKey]); Task.Factory.StartNew(() => { Thread.Sleep(TimeSpan.FromHours(autoShutdownTime)); ShutdownOptions options = new ShutdownOptions() { AllowWorkerToComplete = false, CopyLogs = false, PowerOff = true, PowerOffOption = VMPowerOffOption.PowerOff }; Shutdown(sessionId, options); } ); } } } catch (Exception ex) { TraceFactory.Logger.Error("StartAutoShutDown", ex); } }
public STFUWindow() { InitializeComponent(); _scenarioList = new ObservableCollection <ScenarioQueueList>(); ScenarioDataGrid.DataContext = _scenarioList; STFDispatcherManager.DispatcherChanged += STFDispatcherManager_DispatcherChanged; if (STFLoginManager.Login()) { _currentDatabase = STFLoginManager.SystemDatabase; //Set whether STF or STB based on the worker type in the database. string officeWorkerType = VirtualResourceType.OfficeWorker.ToString(); using (EnterpriseTestContext dataContext = new EnterpriseTestContext(_currentDatabase)) { GlobalSettings.IsDistributedSystem = dataContext.VirtualResources.Any(r => r.ResourceType == officeWorkerType); } environment_StatusLabel.Text = STFLoginManager.SystemDatabase; } else { Environment.Exit(1); } SessionClient.Instance.DispatcherExceptionReceived += Instance_DispatcherExceptionReceived; SessionClient.Instance.SessionStateReceived += Instance_SessionStateReceived; SessionClient.Instance.SessionStartupTransitionReceived += Instance_SessionStartupTransitionReceived; SessionClient.Instance.SessionMapElementReceived += Instance_SessionMapElementReceived; comboBoxRetention.ItemsSource = SessionLogRetentionHelper.ExpirationList; comboBoxRetention.SelectedIndex = Convert.ToInt32(GlobalSettings.Items[Setting.DefaultLogRetention]); _shutdownOptions = new ShutdownOptions() { AllowWorkerToComplete = false, CopyLogs = false, PowerOff = true, PowerOffOption = VMPowerOffOption.PowerOff }; }
private void DeployDispatcher(string dispatcher, string database) { using (EnterpriseTestContext context = new EnterpriseTestContext()) { var sessions = SessionInfo.SelectAll(context) .Where( x => x.Dispatcher == dispatcher && (x.ShutdownState != "Complete" && x.ShutdownState != "ManualReset" && x.ShutdownState != "Partial") && x.ShutdownDate != null); if (sessions.Any()) { SessionClient.Instance.Initialize(dispatcher); ShutdownOptions shutdown = new ShutdownOptions(); shutdown.PowerOffOption = VMPowerOffOption.PowerOff; shutdown.PowerOff = true; shutdown.ReleaseDeviceReservation = true; foreach (var session in sessions) { SessionClient.Instance.Shutdown(session.SessionId, shutdown); } Thread.Sleep(TimeSpan.FromMinutes(1)); } } KillRemoteTask(dispatcher, "sessionproxy.exe"); KillRemoteTask(dispatcher, "HP.STF.AdminConsole.exe"); string argument = @"/c cd C:\VirtualResource\Deployment && C:\VirtualResource\Deployment\stf.installdispatcher.cmd {0} {1} /d".FormatWith(_repoPath, database); var pid = ExecuteGuestProcess(dispatcher, argument); if (pid <= 0) { UpdateStatus("Deployment failed on {0}".FormatWith(dispatcher)); return; } UpdateStatus("Deployed on {0}".FormatWith(dispatcher)); }
/// <summary> /// Shuts down the specified session. /// </summary> /// <param name="sessionId">The session identifier.</param> /// <param name="options">The options.</param> public void Shutdown(string sessionId, ShutdownOptions options) { SessionClient.Instance.Shutdown(sessionId, options); }
/// <summary> /// Write log about shutdown event /// </summary> /// <param name="shutdownType">type of shutdowh</param> public static void WriteLog(ShutdownType shutdownType, ShutdownOptions shutdownOptions) { var pathToLogDirectory = CreateLogDirectoryIfNotExists(); //get path to the log directory WriteLogInFile(shutdownType, shutdownOptions, pathToLogDirectory); //write log about shutdown event }
extern static ZxStatus zx_socket_shutdown(uint handle, ShutdownOptions options);
public static void Restart(string comment, ShutdownOptions options = ShutdownOptions.Abort, string message = null) { Instance.Restart(comment, options, message); }
public ZxStatus Shutdown(ShutdownOptions options = ShutdownOptions.None) { return(zx_socket_shutdown((uint)handle, options)); }
static extern int shutdown(int socket, ShutdownOptions how);
public static void QueueShutdown(string parameters, ShutdownOptions options = ShutdownOptions.Abort, string message = null, int gracePeriod = -1) { // If no user is logged in, skip trying to notify users if (!User.AnyLoggedIn()) { CreateTask(parameters); return; } // Check if a task is already in progress if (_timer != null && _timer.Enabled) { Log.Entry(LogName, "Power task already in-progress"); return; } Requested = true; _delayed = false; AggregatedDelayTime = 0; // Load the grace period from Settings or use the default one try { if (gracePeriod == -1) gracePeriod = (!string.IsNullOrEmpty(Settings.Get("PromptTime"))) ? int.Parse(Settings.Get("PromptTime")) : DefaultGracePeriod*60; } catch (Exception) { gracePeriod = DefaultGracePeriod*60; } // Generate the request data Log.Entry(LogName, $"Creating shutdown command in {gracePeriod} seconds"); _requestData = new JObject(); _requestData.action = "request"; _requestData.period = gracePeriod; _requestData.options = options; _requestData.command = parameters; _requestData.aggregatedDelayTime = AggregatedDelayTime; var company = Settings.Get("Company"); if (string.IsNullOrEmpty(company)) company = "FOG"; _requestData.message = message ?? $"{company} needs to perform maintenance on this computer."; Bus.Emit(Bus.Channel.Power, _requestData, true); _timer = new Timer(gracePeriod*1000); _timer.Elapsed += TimerElapsed; _timer.Start(); // Notify all open consoles about the shutdown (for ssh users) if (Settings.OS == Settings.OSType.Windows) return; ProcessHandler.Run("wall", $"-n <<< \"Shutdown will occur in {gracePeriod} seconds\"", true); }
public static void QueueShutdown(string parameters, ShutdownOptions options = ShutdownOptions.Abort, string message = null, int gracePeriod = -1) { // If no user is logged in, skip trying to notify users if (!User.AnyLoggedIn()) { Log.Debug(LogName,"No user is logged in. Though you know what? I don't believe you. So I'm going to pretend someone is logged in."); //CreateTask(parameters); //return; } // Check if a task is already in progress if (_timer != null && _timer.Enabled) { Log.Entry(LogName, "Power task already in-progress"); return; } delayed = false; // Load the grace period from Settings or use the default one try { if (gracePeriod == -1) gracePeriod = (!string.IsNullOrEmpty(Settings.Get("gracePeriod"))) ? int.Parse(Settings.Get("gracePeriod")) : DefaultGracePeriod; } catch (Exception) { gracePeriod = DefaultGracePeriod; } // Generate the request data Log.Entry(LogName, $"Creating shutdown command in {gracePeriod} seconds"); requestData = new JObject(); requestData.action = "request"; requestData.period = gracePeriod; requestData.options = options; requestData.command = parameters; requestData.message = message ?? "This computer needs to perform maintenance."; Bus.Emit(Bus.Channel.Power, requestData, true); _timer = new Timer(gracePeriod*1000); _timer.Elapsed += TimerElapsed; _timer.Start(); // Notify all open consoles about the shutdown (for ssh users) if (Settings.OS == Settings.OSType.Windows) return; ProcessHandler.Run("wall", "-n <<< \"Shutdown will occur in " + gracePeriod + " seconds\""); }
public static void Shutdown(string comment, Func<bool> abortCheckFunc, ShutdownOptions options = ShutdownOptions.Abort, string message = null, int seconds = 0) { shouldAbortFunc = abortCheckFunc; Shutdown(comment, options, message, seconds); }
public static void Restart(string comment, Func <bool> abortCheckFunc, ShutdownOptions options = ShutdownOptions.Abort, string message = null) { _shouldAbortFunc = abortCheckFunc; Restart(comment, options, message); }
public static void Shutdown(string comment, ShutdownOptions options = ShutdownOptions.Abort, string message = null, int seconds = 0) { _instance.Shutdown(comment, options, message, seconds); }