Esempio n. 1
0
        public SQLiteJobServerTest()
        {
            //Configure storage connection
            var clientConfig = new ClientConfig();
            //clientConfig.DBConnectionString = @"Data Source=C:\projects\Github\Shift\Shift.UnitTest\testdatabase.db";
            string cs = SQLiteDBHelpers.GetLocalDB("testdatabase");

            clientConfig.DBConnectionString = cs;

            clientConfig.StorageMode = "sqlite";
            jobClient = new JobClient(clientConfig);

            var serverConfig = new ServerConfig();

            //serverConfig.DBConnectionString = @"Data Source=C:\projects\Github\Shift\Shift.UnitTest\testdatabase.db";
            serverConfig.DBConnectionString = cs;
            serverConfig.StorageMode        = "sqlite";
            serverConfig.ProcessID          = "JobServerTest";
            serverConfig.Workers            = 1;
            serverConfig.MaxRunnableJobs    = 1;

            serverConfig.ProgressDBInterval = new TimeSpan(0);
            serverConfig.AutoDeletePeriod   = null;
            serverConfig.ForceStopServer    = true;
            serverConfig.StopServerDelay    = 3000;
            jobServer = new JobServer(serverConfig);
        }
        /// <summary>
        /// Retrieves an instance of ProxyAccount from job server using name provided.
        /// If proxy does not exist it throws an exception.
        /// </summary>
        /// <param name="proxyAccountName">Name of the proxy to get</param>
        /// <param name="jobServer">Job server to get the proxy from</param>
        /// <returns>A valid proxy account.</returns>
        internal static ProxyAccount GetProxyAccount(string proxyAccountName, JobServer jobServer)
        {
            if (proxyAccountName == null || proxyAccountName.Length == 0)
            {
                throw new ArgumentException("proxyAccountName");
            }

            if (jobServer == null)
            {
                throw new ArgumentNullException("jobServer");
            }

            ProxyAccount proxyAccount = jobServer.ProxyAccounts[proxyAccountName];

            if (proxyAccount == null)
            {
                // proxy not found. Try refreshing the collection
                jobServer.ProxyAccounts.Refresh();
                proxyAccount = jobServer.ProxyAccounts[proxyAccountName];

                // if still cannot get the proxy throw an exception
                if (proxyAccount == null)
                {
                    throw new ApplicationException(SR.ProxyAccountNotFound(proxyAccountName));
                }
            }
            return(proxyAccount);
        }
        /// <summary>
        /// Load the data for the jobs that notify this operator. Can be called multiple times and will
        /// only load the data initially, or after a reset.
        /// </summary>
        private void LoadJobNotificationData()
        {
            if (this.jobNotifications != null)
            {
                return;
            }

            // just set defaults if we're creating as no jobs will point to this operator yet.
            if (createMode)
            {
                LoadJobNotificationDefaults();
                return;
            }

            JobServer jobServer = GetJobServer();

            this.jobNotifications = new List <AgentJobNotificationHelper>();

            // we have to loop through each job and see if it notifies us.
            foreach (Job job in jobServer.Jobs)
            {
                bool emailOperator = (job.OperatorToEmail == this.originalOperatorName);
                bool pageOperator  = (job.OperatorToPage == this.originalOperatorName);
                if (emailOperator || pageOperator)
                {
                    // only return jobs that notify this operator
                    AgentJobNotificationHelper notification = new AgentJobNotificationHelper(job.Name
                                                                                             , job.EmailLevel
                                                                                             , job.PageLevel
                                                                                             );
                    this.jobNotifications.Add(notification);
                }
            }
        }
Esempio n. 4
0
        private static void InitShiftServer()
        {
            var config = new Shift.ServerConfig();

            config.AssemblyFolder = ConfigurationManager.AppSettings["AssemblyFolder"];
            //config.AssemblyListPath = ConfigurationManager.AppSettings["AssemblyListPath"];
            config.MaxRunnableJobs = Convert.ToInt32(ConfigurationManager.AppSettings["MaxRunnableJobs"]);
            //config.ProcessID = ConfigurationManager.AppSettings["ShiftPID"]; //demo/testing ID
            config.DBConnectionString = ConfigurationManager.ConnectionStrings["ShiftDBConnection"].ConnectionString;
            config.DBAuthKey          = ConfigurationManager.AppSettings["DocumentDBAuthKey"];
            config.Workers            = Convert.ToInt32(ConfigurationManager.AppSettings["ShiftWorkers"]);

            config.StorageMode = ConfigurationManager.AppSettings["StorageMode"];
            var progressDBInterval = ConfigurationManager.AppSettings["ProgressDBInterval"];

            if (!string.IsNullOrWhiteSpace(progressDBInterval))
            {
                config.ProgressDBInterval = TimeSpan.Parse(progressDBInterval); //Interval when progress is updated in main DB
            }
            var autoDeletePeriod = ConfigurationManager.AppSettings["AutoDeletePeriod"];

            config.AutoDeletePeriod = string.IsNullOrWhiteSpace(autoDeletePeriod) ? null : (int?)Convert.ToInt32(autoDeletePeriod);
            //config.AutoDeleteStatus = new List<JobStatus?> { JobStatus.Completed, JobStatus.Error }; //Auto delete only the jobs that has completed or with error.

            config.ForceStopServer = Convert.ToBoolean(ConfigurationManager.AppSettings["ForceStopServer"]); //Set to true to allow windows service to shut down after a set delay in StopServerDelay
            config.StopServerDelay = Convert.ToInt32(ConfigurationManager.AppSettings["StopServerDelay"]);

            //config.EncryptionKey = "[OPTIONAL_ENCRYPTIONKEY]"; //optional, will encrypt parameters in DB if filled
            config.PollingOnce = Convert.ToBoolean(ConfigurationManager.AppSettings["PollingOnce"]);

            jobServer = new JobServer(config);
        }
Esempio n. 5
0
        private Job CreateJob(out JobServer manager, string projectDirectory)
        {
            var job = CreateOnServer(out manager, server => server.CreateJob(), projectDirectory);

            JobCollection.AddJob(job);
            return(job);
        }
Esempio n. 6
0
        public SqlJobServerTest()
        {
            //Configure storage connection
            var clientConfig = new ClientConfig();

            //clientConfig.DBConnectionString = "Data Source=localhost\\SQL2014;Initial Catalog=ShiftJobsDB;Integrated Security=SSPI;";
            string cs = SqlDBHelpers.GetLocalDB("testdatabase");

            clientConfig.DBConnectionString = cs;

            clientConfig.StorageMode = "mssql";
            jobClient = new JobClient(clientConfig);

            var serverConfig = new ServerConfig();

            //serverConfig.DBConnectionString = "Data Source=localhost\\SQL2014;Initial Catalog=ShiftJobsDB;Integrated Security=SSPI;";
            serverConfig.DBConnectionString = cs;

            clientConfig.DBConnectionString = cs;
            serverConfig.StorageMode        = "mssql";
            serverConfig.ProcessID          = "JobServerTest";
            serverConfig.Workers            = 1;
            serverConfig.MaxRunnableJobs    = 1;

            serverConfig.ProgressDBInterval = new TimeSpan(0);
            serverConfig.AutoDeletePeriod   = null;
            serverConfig.ForceStopServer    = true;
            serverConfig.StopServerDelay    = 3000;
            jobServer = new JobServer(serverConfig);
        }
Esempio n. 7
0
        private void btnStarScheduler_Click(object sender, EventArgs e)
        {
            var jobServer = new JobServer(new Uri("http://localhost:9090/scheduler"));

            jobServer.Start();
            btnStarScheduler.Text = jobServer.State.ToString();
        }
Esempio n. 8
0
        public JobServerRedisAsyncTest()
        {
            var appSettingsReader = new AppSettingsReader();

            //Configure storage connection
            var clientConfig = new ClientConfig();

            clientConfig.DBConnectionString = appSettingsReader.GetValue("RedisConnectionString", typeof(string)) as string;
            clientConfig.StorageMode        = "redis";
            jobClient = new JobClient(clientConfig);

            var serverConfig = new ServerConfig();

            serverConfig.DBConnectionString = appSettingsReader.GetValue("RedisConnectionString", typeof(string)) as string;
            serverConfig.StorageMode        = "redis";
            serverConfig.ProcessID          = this.ToString();
            serverConfig.Workers            = 1;
            serverConfig.MaxRunnableJobs    = 1;

            serverConfig.ProgressDBInterval = new TimeSpan(0);
            serverConfig.AutoDeletePeriod   = null;
            serverConfig.ForceStopServer    = true;
            serverConfig.StopServerDelay    = 3000;
            jobServer = new JobServer(serverConfig);
        }
Esempio n. 9
0
        public async Task WaitTillProcessesAreDone_ReachedMaxTimeout()
        {
            // Arrange
            var cancellationToken = new CancellationToken(false);

            JobStorage.Current = new TestJobStorage(monitoringApi.Object);

            var agentId = 123;

            this.agentServiceMock.Setup(m => m.AgentID).Returns(agentId);
            this.agentRepositoryMock.Setup(m => m.ReadAgentEnabled(agentId)).Returns(true);
            this.configurationRepositoryMock.Setup(
                m => m.ReadValue <int>(ConfigurationKeys.JobServerSleepTime)).Returns(31);
            this.configurationRepositoryMock.Setup(
                m => m.ReadValue <int>(ConfigurationKeys.JobServerMaxExecution)).Returns(30);

            using (var server = new JobServer(this.agentRepositoryMock.Object, this.configurationRepositoryMock.Object, this.loggerMock.Object, this.agentServiceMock.Object, this.jobServerOptionsFactoryMock.Object, this.timeService))
            {
                // Act
                await server.WaitTillProcessesAreDone(cancellationToken);

                // Assert
                this.configurationRepositoryMock.Verify(m => m.ReadValue <int>(ConfigurationKeys.JobServerSleepTime), Times.Once);
                this.configurationRepositoryMock.Verify(m => m.ReadValue <int>(ConfigurationKeys.JobServerMaxExecution), Times.Once);
                this.agentRepositoryMock.Verify(m => m.ReadAgentEnabled(agentId), Times.Once);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Script the SQLAgent Jobs
        /// </summary>
        /// <param name="j">JobServer</param>
        private void ScriptSQLAgentJobs(JobServer j)
        {
            string path  = String.Format(@"{0}\SQLAgent", m_Server);
            int    files = 0;

            if (j.Jobs.Count > 0)
            {
                if (Directory.Exists(path) == false)
                {
                    Directory.CreateDirectory(path);
                }
                else
                {
                    DeleteAllSQLFiles(path);
                }

                //
                // Loop over all the SQL Agent jobs
                //
                foreach (Job job in j.Jobs)
                {
                    //
                    // Create the script
                    //
                    m_ScriptingOptions.FileName = Path.Combine(path, ConvertToFileName(job.Name.ToString()));
                    SendLogMessage(null, job.Name, m_ScriptingOptions.FileName, SQLServerScripterType.SQLAgentJob);
                    job.Script(m_ScriptingOptions);
                    files++;
                }
            }
            if (files == 0 && Directory.Exists(path))
            {
                Directory.Delete(path, true);
            }
        }
Esempio n. 11
0
        private SoT CreateSoT(out JobServer manager, string projectDirectory)
        {
            var sot = CreateOnServer(out manager, server => server.CreateSoT(), projectDirectory);

            JobCollection.AddSoT(sot);
            return(sot);
        }
Esempio n. 12
0
 protected override void BeginProcessing()
 {
     base.BeginProcessing();
     _js = !this.MyInvocation.BoundParameters.ContainsKey("SqlServer")
         ? SmoContext.Connection.JobServer
         : this.SqlServer.JobServer;
 }
Esempio n. 13
0
 protected override void BeginProcessing()
 {
     base.BeginProcessing();
     _list = new List <JobCategory>();
     _js   = !this.MyInvocation.BoundParameters.ContainsKey("JobServer")
         ? SmoContext.Connection.JobServer
         : this.JobServer;
 }
Esempio n. 14
0
 private static void CurrentDomain_ProcessExit(object?sender, EventArgs e)
 {
     // If the application exits, notify the server to stop and do it's cleanup
     if (JobServer != null)
     {
         JobServer.Stop();
     }
 }
Esempio n. 15
0
        private T CreateOnServer <T>(out JobServer manager, Func <JobServer, T> create, string projectDirectory)
        {
            T sot;

            manager = (JobServer)Activator.GetObject(typeof(JobServer), JobServerConnection.OriginalString);
            sot     = create(manager);
            return(sot);
        }
Esempio n. 16
0
        static void Main(string[] args)
        {
            var publisher  = Environment.GetEnvironmentVariable("JOB_SERVER_PUBLISHER");
            var subscriber = Environment.GetEnvironmentVariable("JOB_SERVER_SUBSCRIBER");

            var jobServer = new JobServer(publisher, subscriber);

            jobServer.Execute();
        }
        /// <summary>
        /// Get the job server. Will throw if it is not available
        /// </summary>
        /// <returns>Job server object</returns>
        private JobServer GetJobServer()
        {
            JobServer jobServer = this.dataContainer.Server.JobServer;

            if (jobServer == null)
            {
                throw new ApplicationException(SR.JobServerIsNotAvailable);
            }
            return(jobServer);
        }
Esempio n. 18
0
        public void JobServerDBConnectionStringNullTest()
        {
            var config = new ServerConfig();

            config.StorageMode        = "redis";
            config.DBConnectionString = "";
            config.ProcessID          = processID;

            var ex = Assert.Throws <ArgumentNullException>(() => { var jobServer = new JobServer(config); });
        }
Esempio n. 19
0
 private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
 {
     // If the application exits, notify the server to stop and do it's cleanup
     // Set the Cancel property to true to prevent the process from terminating.
     e.Cancel = true;
     if (JobServer != null)
     {
         JobServer.Stop();
     }
 }
Esempio n. 20
0
 public DashboardController(HttpContextBase httpContext)
 {
     if (jobClient == null)
     {
         jobClient = httpContext.Application["Shift.JobClient"] as JobClient;
     }
     if (jobServer == null)
     {
         jobServer = httpContext.Application["Shift.JobServer"] as JobServer;
     }
 }
Esempio n. 21
0
        protected override void OnStart(string[] args)
        {
            this.rptServer = new ReportServer(new Uri("http://localhost:9090/reports"));
            rptServer.Start();

            this.jobServer = new JobServer(new Uri("http://localhost:9090/scheduler"));
            jobServer.Start();

            //base.OnStart(args);
            //ItsFrameService<T>.Run();
        }
Esempio n. 22
0
        static void Main(string[] args)
        {
            JobServer manager = (JobServer)Activator.GetObject(typeof(JobServer),
                                                               "tcp://localhost:35010/JobServer");
            Job j = manager.CreateJob();

            j.RunCommand       = "cmd.exe";
            j.Title            = "Test cmd.exe";
            j.WorkingDirectory = "c:\\";
            manager.AddJob(j);
        }
Esempio n. 23
0
        public void JobServerProcessIDTest()
        {
            var config = new ServerConfig();

            config.StorageMode        = "redis";
            config.DBConnectionString = connectionString;
            config.ProcessID          = "";

            var jobServer = new JobServer(config);

            Assert.NotNull(config.ProcessID);
        }
        /// <summary>
        /// Get the current operator. If we are creating this will be a new operator. If we are modifying
        /// an existing operator it will be the existing operator, and will throw if the operator has been
        /// deleted.
        /// </summary>
        /// <returns>Operator object</returns>
        private Operator GetCurrentOperator()
        {
            JobServer jobServer       = GetJobServer();
            Operator  currentOperator = jobServer.Operators[this.originalOperatorName];

            this.createMode = (currentOperator == null);
            if (this.createMode)
            {
                currentOperator = new Microsoft.SqlServer.Management.Smo.Agent.Operator(jobServer, this.name);
            }
            return(currentOperator);
        }
Esempio n. 25
0
        protected override void BeginProcessing()
        {
            base.BeginProcessing();
            _js = !this.MyInvocation.BoundParameters.ContainsKey("JobServer")
                ? SmoContext.Connection.JobServer
                : this.JobServer;

            if (_js.JobCategories.Contains(this.Name))
            {
                throw new JobCategoryAlreadyExistsException(this.Name);
            }
        }
Esempio n. 26
0
        public void JobServerMaxRunnableJobsZeroTest()
        {
            var config = new ServerConfig();

            config.StorageMode        = "redis";
            config.DBConnectionString = connectionString;
            config.ProcessID          = processID;
            config.MaxRunnableJobs    = 0;

            var jobServer = new JobServer(config);

            Assert.True(true);
        }
Esempio n. 27
0
        public async Task RunServerAsyncTest()
        {
            var config = new ServerConfig();

            config.StorageMode        = "redis";
            config.DBConnectionString = connectionString;
            config.ProcessID          = processID;
            config.MaxRunnableJobs    = 1;

            var jobServer = new JobServer(config);
            await jobServer.RunServerAsync();

            Assert.True(true);
        }
Esempio n. 28
0
        public bool IsStarted(string JobName)
        {
            bool ret = false;

            using (SqlConnection oConnection = new SqlConnection(ConnectionString))
            {
                ServerConnection serverConnection = new ServerConnection(oConnection);
                Server           oSqlServer       = new Server(serverConnection);
                JobServer        oAgent           = oSqlServer.JobServer;
                Job oJob = oAgent.Jobs[JobName];
                ret = (oJob.CurrentRunStatus != JobExecutionStatus.Idle);
            }
            return(ret);
        }
Esempio n. 29
0
        public DateTime GetLastRunDate(string JobName)
        {
            DateTime ret = DateTime.Now;

            using (SqlConnection oConnection = new SqlConnection(ConnectionString))
            {
                ServerConnection serverConnection = new ServerConnection(oConnection);
                Server           oSqlServer       = new Server(serverConnection);
                JobServer        oAgent           = oSqlServer.JobServer;
                Job oJob = oAgent.Jobs[JobName];
                ret = oJob.LastRunDate;
            }
            return(ret);
        }
        /// <summary>
        /// set the alert notification defaults. This list will contain all of the alerts
        /// </summary>
        private void LoadAlertNotificationDefaults()
        {
            this.alertNotifications = new List <AgentAlertNotificationHelper>();

            JobServer jobServer = GetJobServer();

            AgentAlertNotificationHelper alertNotification;

            foreach (Alert alert in jobServer.Alerts)
            {
                alertNotification = new AgentAlertNotificationHelper(alert.Name, notifyEmail: false, notifyPager: false, alert: alert);
                this.alertNotifications.Add(alertNotification);
            }
        }