예제 #1
0
        public JobCreateOrUpdateResponse CreateOrUpdateJOB(string jobCollectionName, string jobID,DateTime startTime, string URL, JobActionType jobActionType = JobActionType.Http, String method = HttpActionMethod.Get, JobRecurrenceFrequency jobRecurrenceFrequency = JobRecurrenceFrequency.Hour, int interval = 1, int executionCount = 1)
        {
            var credentials = _credentialManager.GetManagementCredentials();
            var schedulerClient = new SchedulerClient(cloudSerivceName, jobCollectionName, credentials);

            var result = schedulerClient.Jobs.CreateOrUpdate(jobID,new JobCreateOrUpdateParameters()
            {
                Action = new JobAction()
                {
                    Type = jobActionType,
                    Request = new JobHttpRequest()
                    {
                        Method = HttpActionMethod.Post,
                        Uri = new Uri(URL)
                    }
                },
                StartTime = startTime,
                Recurrence = new JobRecurrence()
                {
                    Frequency = jobRecurrenceFrequency,
                    Interval = interval,
                    Count = executionCount
                }
            });
            return result;
        }
        public PSJobDetail CreateHttpJob(PSCreateJobParams jobRequest, out string status)
        {
            SchedulerClient schedulerClient = new SchedulerClient(csmClient.Credentials, jobRequest.Region.ToCloudServiceName(), jobRequest.JobCollectionName);
            JobCreateOrUpdateParameters jobCreateParams = new JobCreateOrUpdateParameters
            {
                Action = new JobAction
                {
                    Request = new JobHttpRequest
                    {
                        Uri = jobRequest.Uri,
                        Method = jobRequest.Method
                    },
                }
            };

            if (jobRequest.Headers != null)
            {
                jobCreateParams.Action.Request.Headers = jobRequest.Headers.ToDictionary();
            }

            if (jobRequest.Method.Equals("PUT", StringComparison.OrdinalIgnoreCase) || jobRequest.Method.Equals("POST", StringComparison.OrdinalIgnoreCase))
                jobCreateParams.Action.Request.Body = jobRequest.Body;

            //Populate job error action
            jobCreateParams.Action.ErrorAction = PopulateErrorAction(jobRequest);

            jobCreateParams.StartTime = jobRequest.StartTime ?? default(DateTime?);
           
            if (jobRequest.Interval != null || jobRequest.ExecutionCount != null || !string.IsNullOrEmpty(jobRequest.Frequency) || jobRequest.EndTime !=null)
            {
                jobCreateParams.Recurrence = new JobRecurrence();
                jobCreateParams.Recurrence.Count = jobRequest.ExecutionCount ?? default(int?);

                if (!string.IsNullOrEmpty(jobRequest.Frequency))
                    jobCreateParams.Recurrence.Frequency = (JobRecurrenceFrequency)Enum.Parse(typeof(JobRecurrenceFrequency), jobRequest.Frequency);

                jobCreateParams.Recurrence.Interval = jobRequest.Interval ?? default(int?);

                jobCreateParams.Recurrence.EndTime = jobRequest.EndTime ?? default(DateTime?);
            }
            
            JobCreateOrUpdateResponse jobCreateResponse = schedulerClient.Jobs.CreateOrUpdate(jobRequest.JobName, jobCreateParams);
            
            if (!string.IsNullOrEmpty(jobRequest.JobState) && jobRequest.JobState.Equals("DISABLED", StringComparison.OrdinalIgnoreCase))
                schedulerClient.Jobs.UpdateState(jobRequest.JobName, new JobUpdateStateParameters { State = JobState.Disabled });

            status = jobCreateResponse.StatusCode.ToString().Equals("OK") ? "Job has been updated" : jobCreateResponse.StatusCode.ToString();

            return GetJobDetail(jobRequest.JobCollectionName, jobRequest.JobName, jobRequest.Region.ToCloudServiceName());
        }
        protected override void Clone(ServiceClient <SchedulerClient> client)
        {
            base.Clone(client);
            SchedulerClient management = client as SchedulerClient;

            if (management != null)
            {
                management._credentials       = Credentials;
                management._cloudServiceName  = CloudServiceName;
                management._jobCollectionName = JobCollectionName;
                management._baseUri           = BaseUri;
                management.Credentials.InitializeServiceClient(management);
            }
        }
        public PSJobDetail PatchStorageJob(PSCreateJobParams jobRequest, out string status)
        {
            SchedulerClient schedulerClient = new SchedulerClient(csmClient.Credentials, jobRequest.Region.ToCloudServiceName(), jobRequest.JobCollectionName);

            //Get Existing job
            Job job = schedulerClient.Jobs.Get(jobRequest.JobName).Job;

            JobCreateOrUpdateParameters jobUpdateParams = PopulateExistingJobParams(job, jobRequest, job.Action.Type);

            JobCreateOrUpdateResponse jobUpdateResponse = schedulerClient.Jobs.CreateOrUpdate(jobRequest.JobName, jobUpdateParams);

            if (!string.IsNullOrEmpty(jobRequest.JobState))
                schedulerClient.Jobs.UpdateState(jobRequest.JobName, new JobUpdateStateParameters
                {
                    State = jobRequest.JobState.Equals("Enabled", StringComparison.OrdinalIgnoreCase) ? JobState.Enabled
                        : JobState.Disabled
                });

            status = jobUpdateResponse.StatusCode.ToString().Equals("OK") ? "Job has been updated" : jobUpdateResponse.StatusCode.ToString();

            return GetJobDetail(jobRequest.JobCollectionName, jobRequest.JobName, jobRequest.Region.ToCloudServiceName());
        }
        public PSJobDetail CreateStorageJob(PSCreateJobParams jobRequest, out string status)
        {
            SchedulerClient schedulerClient = new SchedulerClient(csmClient.Credentials, jobRequest.Region.ToCloudServiceName(), jobRequest.JobCollectionName);
            JobCreateOrUpdateParameters jobCreateParams = new JobCreateOrUpdateParameters
            {
                Action = new JobAction
                {
                    Type = JobActionType.StorageQueue,
                    QueueMessage = new JobQueueMessage
                    {
                        Message = jobRequest.Body ?? string.Empty,
                        StorageAccountName = jobRequest.StorageAccount,
                        QueueName = jobRequest.QueueName,
                        SasToken = jobRequest.SasToken
                    },
                }
            };

            //Populate job error action
            jobCreateParams.Action.ErrorAction = PopulateErrorAction(jobRequest);

            jobCreateParams.StartTime = jobRequest.StartTime ?? default(DateTime?);

            if (jobRequest.Interval != null || jobRequest.ExecutionCount != null || !string.IsNullOrEmpty(jobRequest.Frequency) || jobRequest.EndTime != null)
            {
                jobCreateParams.Recurrence = new JobRecurrence();
                jobCreateParams.Recurrence.Count = jobRequest.ExecutionCount ?? default(int?);

                if (!string.IsNullOrEmpty(jobRequest.Frequency))
                    jobCreateParams.Recurrence.Frequency = (JobRecurrenceFrequency)Enum.Parse(typeof(JobRecurrenceFrequency), jobRequest.Frequency);

                jobCreateParams.Recurrence.Interval = jobRequest.Interval ?? default(int?);

                jobCreateParams.Recurrence.EndTime = jobRequest.EndTime ?? default(DateTime?);
            }

            JobCreateOrUpdateResponse jobCreateResponse = schedulerClient.Jobs.CreateOrUpdate(jobRequest.JobName, jobCreateParams);

            if (!string.IsNullOrEmpty(jobRequest.JobState) && jobRequest.JobState.Equals("DISABLED", StringComparison.OrdinalIgnoreCase))
                schedulerClient.Jobs.UpdateState(jobRequest.JobName, new JobUpdateStateParameters { State = JobState.Disabled });

            status = jobCreateResponse.StatusCode.ToString().Equals("OK") ? "Job has been updated" : jobCreateResponse.StatusCode.ToString();

            return GetJobDetail(jobRequest.JobCollectionName, jobRequest.JobName, jobRequest.Region.ToCloudServiceName());
           
        }
        void CreateWebJob(WebJobParameter parameters)
        {
            Console.WriteLine("Getting the web space list");

            var webSpaceListResult = _webSiteMgmtClient.WebSpaces.List();

            var webSpace = webSpaceListResult.WebSpaces.First(x => x.GeoRegion == parameters.regionName);

            // create the web site
            Console.WriteLine("Checking for existing site");

            try
            {
                // in a try/catch because the 404 will yield an error if the site isn't found
                _webSiteMgmtClient.WebSites.Get(webSpace.Name, parameters.webSiteName, new WebSiteGetParameters());
            }
            catch
            {
                // if it wasn't found, we need it, so let's create it
                Console.WriteLine("Creating the web site");

                _webSiteMgmtClient.WebSites.Create(webSpace.Name, new WebSiteCreateParameters
                    {
                        Name = parameters.webSiteName,
                        WebSpaceName = webSpace.Name
                    });
            }

            // get the web site
            Console.WriteLine("Getting the web site's username & password");

            var webSiteGetResult = _webSiteMgmtClient.WebSites.Get(webSpace.Name,
                parameters.webSiteName,
                new WebSiteGetParameters
                {
                    PropertiesToInclude = new string[] { "PublishingUsername", "PublishingPassword" }
                });

            var username = webSiteGetResult.WebSite.SiteProperties.Properties["PublishingUsername"];
            var password = webSiteGetResult.WebSite.SiteProperties.Properties["PublishingPassword"];

            // create the webjob
            var kuduClient = CloudContext.Clients.CreateWebSiteExtensionsClient(new BasicAuthenticationCloudCredentials
            {
                Password = password,
                Username = username,
            }, parameters.webSiteName);

            using (FileStream stream = File.Open(parameters.filePath, FileMode.Open))
            {
                Console.WriteLine("Creating the WebJob and uploading the Console App");
                var webJobCreateResult = kuduClient.WebJobs.UploadTriggered(parameters.webJobName, stream);
            }

            // build the cloud/job service names based on the web site name
            var cloudServiceName = string.Format("{0}SchedulerJobsCloudService", parameters.webSiteName);
            var jobCollectionName = string.Format("{0}SchedulerJobsCollection", parameters.webSiteName);

            // create the cloud service for the scheduler jobs
            if (!_cloudServiceManagementClient.CloudServices.List().CloudServices.Any(x => x.Name == cloudServiceName))
            {
                Console.WriteLine("Creating the scheduler cloud service");

                var cloudServiceCreateResult = _cloudServiceManagementClient.CloudServices.Create(cloudServiceName,
                    new CloudServiceCreateParameters
                    {
                        GeoRegion = parameters.regionName,
                        Label = cloudServiceName,
                        Description = string.Format("Scheduled Jobs for WebJob {0}", parameters.webJobName)
                    });
            }

            Console.WriteLine("Creating the scheduler job collection");

            // create the scheduler job collection
            try
            {
                _schedulerMgmtClient.JobCollections.Create(cloudServiceName, jobCollectionName,
                    new JobCollectionCreateParameters
                    {
                        Label = jobCollectionName,
                        IntrinsicSettings = new JobCollectionIntrinsicSettings
                        {
                            Plan = JobCollectionPlan.Free,
                            Quota = new JobCollectionQuota
                            {
                                MaxJobCount = 5,
                                MaxJobOccurrence = 1,
                                MaxRecurrence = new JobCollectionMaxRecurrence
                                {
                                    Frequency = JobCollectionRecurrenceFrequency.Hour,
                                    Interval = 1
                                }
                            }
                        }
                    });
            }
            catch
            {
                // job collection was already there
            }

            // get the webjob's details
            var webJob = kuduClient.WebJobs.GetTriggered(parameters.webJobName);

            // create the scheduler job
            Console.WriteLine("Creating the scheduler job");

            _schedulerClient = new SchedulerClient(_credential, cloudServiceName, jobCollectionName);

            var request =
                new JobHttpRequest
                {
                    // build the Uri for the REST call to run a webjob
                    Uri = new Uri(string.Format("{0}/run", webJob.WebJob.Url.AbsoluteUri)),
                    Method = "POST"
                };

            // build the base64 string to use for authorizing
            var rawAuthorizationString = string.Format("{0}:{1}", username, password);
            var encryptedAuthorizationString =
                Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(rawAuthorizationString));

            // add the headers to the request
            request.Headers.Add("authorization", string.Format("Basic {0}", encryptedAuthorizationString));
            request.Headers.Add("content-Type", "text/plain");

            // create the job
            _schedulerClient.Jobs.Create(new JobCreateParameters
            {
                Action = new JobAction
                {
                    Type = JobActionType.Https,
                    Request = request
                },
                Recurrence = new JobRecurrence
                {
                    Frequency = parameters.jobRecurrenceFrequency,
                    Interval = parameters.interval,
                    EndTime = parameters.endTime
                },
                StartTime = parameters.startTime
            });

            Console.WriteLine("Job Created");
        }
 public bool DeleteJob(string jobCollection, string jobName, string region = "")
 {
     if (!string.IsNullOrEmpty(region))
     {
         SchedulerClient schedulerClient = new SchedulerClient(csmClient.Credentials, region.ToCloudServiceName(), jobCollection);
         OperationResponse response = schedulerClient.Jobs.Delete(jobName);
         return response.StatusCode == System.Net.HttpStatusCode.OK ? true : false;
     }
     else if (string.IsNullOrEmpty(region))
     {
         CloudServiceListResponse csList = csmClient.CloudServices.List();
         foreach (CloudServiceListResponse.CloudService cs in csList.CloudServices)
         {
             foreach (CloudServiceGetResponse.Resource csRes in csmClient.CloudServices.Get(cs.Name).Resources)
             {
                 if (csRes.Type.Contains(Constants.JobCollectionResource))
                 {
                     JobCollectionGetResponse jcGetResponse = schedulerManagementClient.JobCollections.Get(cs.Name, csRes.Name);
                     if (jcGetResponse.Name.Equals(jobCollection, StringComparison.OrdinalIgnoreCase))
                     {
                         foreach (PSSchedulerJob job in GetSchedulerJobs(cs.Name, jobCollection))
                         {
                             if (job.JobName.Equals(jobName, StringComparison.OrdinalIgnoreCase))
                             {
                                 SchedulerClient schedulerClient = new SchedulerClient(csmClient.Credentials, cs.Name, jobCollection);
                                 OperationResponse response = schedulerClient.Jobs.Delete(jobName);
                                 return response.StatusCode == System.Net.HttpStatusCode.OK ? true : false;
                             }
                         }
                     }
                 }
             }
         }
     }
     return false;
 }
 public PSJobDetail GetJobDetail(string jobCollection, string job, string cloudService)
 {
     CloudServiceGetResponse csDetails = csmClient.CloudServices.Get(cloudService);
     foreach (CloudServiceGetResponse.Resource csRes in csDetails.Resources)
     {
         if (csRes.ResourceProviderNamespace.Equals(Constants.SchedulerRPNameProvider, StringComparison.OrdinalIgnoreCase) && csRes.Name.Equals(jobCollection, StringComparison.OrdinalIgnoreCase))
         {
             SchedulerClient schedClient = new SchedulerClient(csmClient.Credentials, cloudService, jobCollection);
             JobListResponse jobs = schedClient.Jobs.List(new JobListParameters
             {
                 Skip = 0,
             });
             foreach (Job j in jobs)
             {
                 if (j.Id.ToLower().Equals(job.ToLower()))
                 {
                     if(Enum.GetName(typeof(JobActionType), j.Action.Type).Contains("Http"))
                     {
                         return new PSHttpJobDetail
                         {
                             JobName = j.Id,
                             JobCollectionName = jobCollection,
                             CloudService = cloudService,
                             ActionType = Enum.GetName(typeof(JobActionType), j.Action.Type),
                             Uri = j.Action.Request.Uri,
                             Method = j.Action.Request.Method,
                             Body = j.Action.Request.Body,
                             Headers = j.Action.Request.Headers,
                             Status = j.State.ToString(),
                             StartTime = j.StartTime,
                             EndSchedule = GetEndTime(j),
                             Recurrence = j.Recurrence == null ? "" : j.Recurrence.Interval.ToString() + " per " + j.Recurrence.Frequency.ToString(),
                             Failures = j.Status == null ? default(int?) : j.Status.FailureCount,
                             Faults = j.Status == null ? default(int?) : j.Status.FaultedCount,
                             Executions = j.Status == null ? default(int?) : j.Status.ExecutionCount,
                             Lastrun = j.Status == null ? null : j.Status.LastExecutionTime,
                             Nextrun = j.Status == null ? null : j.Status.NextExecutionTime
                         };
                     }
                     else
                     {
                         return new PSStorageQueueJobDetail
                         {
                             JobName = j.Id,
                             JobCollectionName = jobCollection,
                             CloudService = cloudService,
                             ActionType = Enum.GetName(typeof(JobActionType), j.Action.Type),
                             StorageAccountName = j.Action.QueueMessage.StorageAccountName,
                             StorageQueueName = j.Action.QueueMessage.QueueName,
                             SasToken =  j.Action.QueueMessage.SasToken,
                             QueueMessage = j.Action.QueueMessage.Message,
                             Status = j.State.ToString(),
                             EndSchedule = GetEndTime(j),
                             StartTime = j.StartTime,
                             Recurrence = j.Recurrence == null ? "" : j.Recurrence.Interval.ToString() + " per " + j.Recurrence.Frequency.ToString(),
                             Failures = j.Status == null ? default(int?) : j.Status.FailureCount,
                             Faults = j.Status == null ? default(int?) : j.Status.FaultedCount,
                             Executions = j.Status == null ? default(int?) : j.Status.ExecutionCount,
                             Lastrun = j.Status == null ? null : j.Status.LastExecutionTime,
                             Nextrun = j.Status == null ? null : j.Status.NextExecutionTime
                         };
                     }
                 }
             }
         }
     }
     return null;
 }
        public List<PSJobHistory> GetJobHistory(string jobCollection, string job, string region, string jobStatus = "")
        {
            List<PSJobHistory> lstPSJobHistory = new List<PSJobHistory>();
            string cloudService = region.ToCloudServiceName();
            CloudServiceGetResponse csDetails = csmClient.CloudServices.Get(cloudService);
            foreach (CloudServiceGetResponse.Resource csRes in csDetails.Resources)
            {
                if (csRes.ResourceProviderNamespace.Equals(Constants.SchedulerRPNameProvider, StringComparison.InvariantCultureIgnoreCase) && csRes.Name.Equals(jobCollection, StringComparison.OrdinalIgnoreCase))
                {
                    SchedulerClient schedClient = new SchedulerClient(csmClient.Credentials, cloudService, jobCollection.Trim());
                    List<JobGetHistoryResponse.JobHistoryEntry> lstHistory = new List<JobGetHistoryResponse.JobHistoryEntry>();
                    int currentTop = 100;

                    if(string.IsNullOrEmpty(jobStatus))
                    {
                        JobGetHistoryResponse history = schedClient.Jobs.GetHistory(job.Trim(), new JobGetHistoryParameters { Top = 100});
                        lstHistory.AddRange(history.JobHistory);
                        while(history.JobHistory.Count > 99)
                        {
                            history = schedClient.Jobs.GetHistory(job.Trim(), new JobGetHistoryParameters { Top = 100, Skip = currentTop});
                            currentTop+= 100;
                            lstHistory.AddRange(history.JobHistory);
                        }
                    }
                    else if(!string.IsNullOrEmpty(jobStatus))
                    {
                        JobHistoryStatus status = jobStatus.Equals("Completed") ? JobHistoryStatus.Completed : JobHistoryStatus.Failed;
                        JobGetHistoryResponse history = schedClient.Jobs.GetHistoryWithFilter(job.Trim(), new JobGetHistoryWithFilterParameters { Top = 100, Status = status});
                        lstHistory.AddRange(history.JobHistory);
                        while(history.JobHistory.Count > 99)
                        {
                            history = schedClient.Jobs.GetHistoryWithFilter(job.Trim(), new JobGetHistoryWithFilterParameters { Top = 100, Skip = currentTop });
                            currentTop+= 100;
                            lstHistory.AddRange(history.JobHistory);
                        }
                    }
                    foreach (JobGetHistoryResponse.JobHistoryEntry entry in lstHistory)
                    {
                        PSJobHistory historyObj = new PSJobHistory();
                        historyObj.Status = entry.Status.ToString();
                        historyObj.StartTime = entry.StartTime;
                        historyObj.EndTime = entry.EndTime;
                        historyObj.JobName = entry.Id;
                        historyObj.Details = GetHistoryDetails(entry.Message);
                        historyObj.Retry = entry.RetryCount;
                        historyObj.Occurence = entry.RepeatCount;
                        if (JobHistoryActionName.ErrorAction == entry.ActionName)
                        {
                            PSJobHistoryError errorObj = historyObj.ToJobHistoryError();
                            errorObj.ErrorAction = JobHistoryActionName.ErrorAction.ToString();
                            lstPSJobHistory.Add(errorObj);
                        }
                        else
                            lstPSJobHistory.Add(historyObj); 
                    }
                }
            }
            return lstPSJobHistory;
        }
예제 #10
0
 private List<PSSchedulerJob> GetSchedulerJobs(string cloudService, string jobCollection)
 {
     List<PSSchedulerJob> lstJobs = new List<PSSchedulerJob>();
     CloudServiceGetResponse csDetails = csmClient.CloudServices.Get(cloudService);
     foreach (CloudServiceGetResponse.Resource csRes in csDetails.Resources)
     {
         if (csRes.ResourceProviderNamespace.Equals(Constants.SchedulerRPNameProvider, StringComparison.OrdinalIgnoreCase) && csRes.Name.Equals(jobCollection, StringComparison.OrdinalIgnoreCase))
         {
             SchedulerClient schedClient = new SchedulerClient(csmClient.Credentials, cloudService, jobCollection);
             JobListResponse jobs = schedClient.Jobs.List(new JobListParameters
             {
                 Skip = 0,
             });
             foreach (Job job in jobs)
             {
                 lstJobs.Add(new PSSchedulerJob
                 {
                     JobName = job.Id,
                     Lastrun = job.Status == null ? null : job.Status.LastExecutionTime,
                     Nextrun = job.Status == null ? null : job.Status.NextExecutionTime,
                     Status = job.State.ToString(),
                     StartTime = job.StartTime,
                     Recurrence = job.Recurrence == null ? "" : job.Recurrence.Interval.ToString() + " per " + job.Recurrence.Frequency.ToString(),
                     Failures = job.Status == null ? default(int?) : job.Status.FailureCount,
                     Faults = job.Status == null ? default(int?) : job.Status.FaultedCount,
                     Executions = job.Status == null ? default(int?) : job.Status.ExecutionCount,
                     EndSchedule = GetEndTime(job),
                     JobCollectionName = jobCollection
                 });
             }
         }
     }
     return lstJobs;
 }