Skip to content

Commit

Permalink
PagerDuty v2 PR cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
NickCraver committed Feb 7, 2017
1 parent 4f53e1b commit be3fe05
Show file tree
Hide file tree
Showing 11 changed files with 96 additions and 165 deletions.
22 changes: 3 additions & 19 deletions Opserver.Core/Data/Pagerduty/PagerDutyAPI.Actions.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Jil;
Expand All @@ -12,29 +11,18 @@ public partial class PagerDutyAPI
public async Task<Incident> UpdateIncidentStatusAsync(string incidentId, PagerDutyPerson person, IncidentStatus newStatus)
{
if (person == null) throw new ArgumentNullException(nameof(person));
/*
var data = new PagerDutyIncidentPut
{
Incidents = new List<Incident>
{
new Incident {Id = incidentId, Status = newStatus}
},
RequesterId = person.Id
};
*/
var data = new
{
incident = new
{
type = "incident_reference",
status = newStatus.ToString()
}

};

var headers = new Dictionary<string,string>()
var headers = new Dictionary<string,string>
{
{ "From", person.Email}
{ "From", person.Email}
};
try
{
Expand All @@ -55,12 +43,8 @@ public async Task<Incident> UpdateIncidentStatusAsync(string incidentId, PagerDu
);
return null;
}



}



public class PagerDutyIncidentUpdateResp
{
[DataMember(Name = "incident")]
Expand Down
30 changes: 17 additions & 13 deletions Opserver.Core/Data/Pagerduty/PagerDutyAPI.Incidents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ public partial class PagerDutyAPI
.ToList()
);
}));

}

public class IncidentResponse
Expand All @@ -47,41 +46,46 @@ public class Incident : IncidentMinimal, IMonitorStatus
public int Number { get; set; }
[DataMember(Name = "created_at")]
public DateTime? CreationDate { get; set; }
[DataMember(Name = "urgency")]
public string Urgency { get; set; }
[DataMember(Name = "html_url")]
public string Uri { get; set; }
[DataMember(Name = "assigned_to")]
public List<PagerDutyPerson> AssignedTo { get; set; }
[DataMember(Name = "last_status_change_on")]
[DataMember(Name = "last_status_change_at")]
public DateTime? LastChangedOn { get; set; }
[DataMember(Name = "last_status_change_by")]
public PagerDutyInfoReference LastChangedBy { get; set; }
[DataMember(Name = "resolved_by_user")]
public string ResolvedBy {
get
{
return Logs.Result.FirstOrDefault(r => r.LogType == "resolve_log_entry").Agent.Person;
}
}
public string ResolvedBy => Logs.Result.FirstOrDefault(r => r.LogType == "resolve_log_entry")?.Agent.Person;
[DataMember(Name = "resolve_reason")]
public string ResolveReason { get; set; }

[DataMember(Name = "acknowledgers")]
public List<Acknowledgement> AcknowledgedBy {
public List<Acknowledgement> AcknowledgedBy
{
get
{
var a = new List<Acknowledgement>();
foreach(var i in Logs.Result.FindAll(l => l.LogType == "acknowledge_log_entry"))
foreach (var i in Logs.Result.FindAll(l => l.LogType == "acknowledge_log_entry"))
{
a.Add(new Acknowledgement()
{
AckPerson = i.Agent.Person,
AckTime = i.CreationTime
});

}
return a;
}
}
[DataMember(Name="summary")]

[DataMember(Name = "title")]
public string Title { get; set; }
[DataMember(Name = "description")]
public string Description { get; set; }
[DataMember(Name = "summary")]
public string Summary { get; set; }
//public Dictionary<string, string> SummaryData { get; set; }
[DataMember(Name = "service")]
public PagerDutyService AffectedService { get; set; }
[DataMember(Name = "number_of_escalations")]
Expand Down
4 changes: 2 additions & 2 deletions Opserver.Core/Data/Pagerduty/PagerDutyAPI.Logs.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Jil;
Expand All @@ -9,7 +8,6 @@ namespace StackExchange.Opserver.Data.PagerDuty
{
public partial class PagerDutyAPI
{

public Task<List<LogEntry>> GetIncidentEntriesAsync(string id)
{
try
Expand Down Expand Up @@ -39,6 +37,8 @@ public class LogEntry
public string LogId { get; set; }
[DataMember(Name ="summary")]
public string Summary { get; set; }
[DataMember(Name = "html_url")]
public string Url { get; set; }
[DataMember(Name="created_at")]
public DateTime? CreationTime { get; set; }
[DataMember(Name = "type")]
Expand Down
67 changes: 27 additions & 40 deletions Opserver.Core/Data/Pagerduty/PagerDutyAPI.OnCall.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,11 @@ namespace StackExchange.Opserver.Data.PagerDuty
public partial class PagerDutyAPI
{
// TODO: We need to able able to handle when people have more than one on call schedule
public PagerDutyPerson PrimaryOnCall
{
get { return OnCallInfo.Data.FirstOrDefault(p => p.EscalationLevel == 1).AssignedUser; }
}
public PagerDutyPerson PrimaryOnCall =>
OnCallInfo.Data?.FirstOrDefault(p => p.EscalationLevel == 1)?.AssignedUser;

public PagerDutyPerson SecondaryOnCall
{
get { return OnCallInfo.Data.FirstOrDefault(p => p.EscalationLevel == 2).AssignedUser; }
}
public PagerDutyPerson SecondaryOnCall =>
OnCallInfo.Data?.FirstOrDefault(p => p.EscalationLevel == 2)?.AssignedUser;

private Cache<List<OnCall>> _oncallinfo;
public Cache<List<OnCall>> OnCallInfo => _oncallinfo ?? (_oncallinfo = new Cache<List<OnCall>>(
Expand All @@ -29,25 +25,33 @@ public PagerDutyPerson SecondaryOnCall
getData: GetOnCallUsers,
logExceptions: true));

private Task<List<OnCall>> GetOnCallUsers()
private async Task<List<OnCall>> GetOnCallUsers()
{
try
{
return GetFromPagerDutyAsync("oncalls", getFromJson:
var users = await GetFromPagerDutyAsync("oncalls", getFromJson:
response => JSON.Deserialize<PagerDutyOnCallResponse>(response.ToString(), JilOptions).OnCallInfo);

users.Sort((a, b) =>
a.EscalationLevel.GetValueOrDefault(int.MaxValue)
.CompareTo(b.EscalationLevel.GetValueOrDefault(int.MaxValue)));

if (users.Count > 1 && users[0].AssignedUser?.Id == users[1].AssignedUser?.Id)
{
var secondary = users[1];
secondary.MonitorStatus = MonitorStatus.Warning;
secondary.MonitorStatusReason = "Primary and secondary on call are the same";
}
return users;
}
catch (DeserializationException de)
{
Current.LogException(
de.AddLoggedData("Snippet After", de.SnippetAfterError)
.AddLoggedData("Message", de.Message)
);
.AddLoggedData("Message", de.Message));
return null;
}


}

}

public class PagerDutyOnCallResponse
Expand Down Expand Up @@ -92,7 +96,7 @@ public string Phone
{
// The PagerDuty API does not always return a full contact. HANDLE IT.
var m = ContactMethods?.FirstOrDefault(cm => cm.Type == "phone_contact_method" || cm.Type == "sms_contact_method");
_phone = m != null ? m.FormattedAddress : "n/a";
_phone = m?.FormattedAddress ?? "n/a";
}
return _phone;
}
Expand All @@ -118,13 +122,7 @@ public static string GetEscalationLevelDescription(int? level)
}

private string _emailusername;
public string EmailUserName
{
get
{
return _emailusername = (_emailusername ?? (Email.HasValue() ? Email.Split(StringSplits.AtSign)[0] : ""));
}
}
public string EmailUserName => _emailusername ?? (_emailusername = Email.HasValue() ? Email.Split(StringSplits.AtSign)[0] : "");
}

public class PagerDutyContactMethod
Expand Down Expand Up @@ -157,8 +155,6 @@ public string FormattedAddress
}
[DataMember(Name = "type")]
public string Type { get; set; }


}

public class EscalationPolicy
Expand Down Expand Up @@ -186,17 +182,11 @@ public class OnCall : IMonitorStatus
[DataMember(Name = "user")]
public OnCallUser User { get; set; }

public PagerDutyPerson AssignedUser => PagerDutyAPI.Instance.AllUsers.Data.FirstOrDefault(u => u.Id == User.Id);
public PagerDutyPerson AssignedUser => PagerDutyAPI.Instance.AllUsers.Data?.FirstOrDefault(u => u.Id == User.Id);

public bool IsOverride
{
get
{
return
PagerDutyAPI.Instance.PrimaryScheduleOverrides.Data?.Any(
o => o.StartTime <= DateTime.UtcNow && DateTime.UtcNow <= o.EndTime && o.User.Id == AssignedUser.Id) ?? false;
}
}
public bool IsOverride =>
PagerDutyAPI.Instance.PrimaryScheduleOverrides.Data?.Any(
o => o.StartTime <= DateTime.UtcNow && DateTime.UtcNow <= o.EndTime && o.User.Id == AssignedUser.Id) ?? false;

public bool IsPrimary => EscalationLevel == 1;

Expand All @@ -218,10 +208,8 @@ public string EscalationLevelDescription
return EscalationLevel.Value + "th";
}
}
else
{
return "unknown";
}

return "unknown";
}
}

Expand All @@ -240,6 +228,5 @@ public class PagerDutyInfoReference
public string Summary { get; set; }
[DataMember(Name = "self")]
public string ApiLink { get; set; }

}
}
11 changes: 2 additions & 9 deletions Opserver.Core/Data/Pagerduty/PagerDutyAPI.Schedules.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,8 @@ public PagerDutySchedule PrimarySchedule
}
}

public string PrimaryScheduleId
{
get
{
var schedule = PrimarySchedule;
return schedule != null ? schedule.Id : "";
}
}
public string PrimaryScheduleId => PrimarySchedule?.Id ?? "";

private Cache<List<PagerDutySchedule>> _schedules;

public Cache<List<PagerDutySchedule>> AllSchedules =>
Expand All @@ -47,7 +41,6 @@ public Cache<List<PagerDutyScheduleOverride>> PrimaryScheduleOverrides
return _primaryScheduleOverrides ?? (_primaryScheduleOverrides = GetPagerDutyCache(10.Minutes(), PrimarySchedule.GetOverridesAsync));
}
}

}

public class PagerDutyScheduleResponse
Expand Down
19 changes: 3 additions & 16 deletions Opserver.Core/Data/Pagerduty/PagerDutyAPI.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Text;
Expand Down Expand Up @@ -44,7 +43,6 @@ public override IEnumerable<Cache> DataPollers
{
get
{

yield return AllUsers;
yield return OnCallInfo;
yield return Incidents;
Expand Down Expand Up @@ -75,8 +73,6 @@ private Cache<T> GetPagerDutyCache<T>(
public PagerDutyAPI()
{
Settings = Current.Settings.PagerDuty;
//CacheItemFetched += (sender, args) => { _scheduleCache = null; };

}

/// <summary>
Expand Down Expand Up @@ -129,7 +125,6 @@ public async Task<T> GetFromPagerDutyAsync<T>(string path, Func<string, T> getFr
using (var sr = new StreamReader(rs))
{
var result = getFromJson(sr.ReadToEnd());
//_scheduleCache = null;
return result;
}
}
Expand All @@ -147,21 +142,16 @@ public async Task<T> GetFromPagerDutyAsync<T>(string path, Func<string, T> getFr
}
}
}
catch(Exception ex)
catch (Exception)
{
/* we gave it a shot, but don't boom in the boom that feeds */
// TEMPORARY (LOL) for troubleshooting

Current.LogException(
ex
);
// ignored, best effort
}

Current.LogException(
e.AddLoggedData("Sent Data", JSON.Serialize(data, JilOptions))
.AddLoggedData("Endpoint", fullUri)
.AddLoggedData("Headers", req.Headers.ToString())
.AddLoggedData("Contecnt Type", req.ContentType));
.AddLoggedData("Content Type", req.ContentType));
return getFromJson("fail");
}
}
Expand All @@ -172,8 +162,5 @@ public async Task<T> GetFromPagerDutyAsync<T>(string path, Func<string, T> getFr
_allusers ?? (_allusers = GetPagerDutyCache(60.Minutes(),
() => GetFromPagerDutyAsync("users?include[]=contact_methods", r => JSON.Deserialize<PagerDutyUserResponse>(r.ToString(), JilOptions).Users))
);



}
}
13 changes: 13 additions & 0 deletions Opserver/App_Code/Helpers.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,17 @@
{
@:@MonitorStatus.Good.IconSpan() @good.Count.ToComma()
}
}
@helper CacheEmpty(Cache cache, string message)
{
if (!cache.LastPollSuccessful)
{
<div class="alert alert-info">
<h5>@message</h5>
@if (cache.ErrorMessage.HasValue())
{
<p class="error-stack">@cache.ErrorMessage</p>
}
</div>
}
}
Loading

0 comments on commit be3fe05

Please sign in to comment.