Skip to content

Commit

Permalink
Implements profiler for blocked recv
Browse files Browse the repository at this point in the history
  • Loading branch information
nakul02 committed Mar 22, 2018
1 parent 563f0ec commit 7d4e2b1
Show file tree
Hide file tree
Showing 27 changed files with 176 additions and 58 deletions.
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 9 additions & 1 deletion components/profile/time.rs
Expand Up @@ -10,7 +10,7 @@ use influent::create_client;
use influent::measurement::{Measurement, Value};
use ipc_channel::ipc::{self, IpcReceiver};
use profile_traits::energy::{energy_interval_ms, read_energy_uj};
use profile_traits::time::{ProfilerCategory, ProfilerChan, ProfilerMsg, TimerMetadata};
use profile_traits::time::{ProfilerCategory, ProfilerChan, ProfilerMsg, ProfilerData, TimerMetadata};
use profile_traits::time::{TimerMetadataFrameType, TimerMetadataReflowType};
use servo_config::opts::OutputOptions;
use std::{f64, thread, u32, u64};
Expand Down Expand Up @@ -158,6 +158,7 @@ impl Formattable for ProfilerCategory {
ProfilerCategory::TimeToFirstPaint => "Time To First Paint",
ProfilerCategory::TimeToFirstContentfulPaint => "Time To First Contentful Paint",
ProfilerCategory::TimeToInteractive => "Time to Interactive",
ProfilerCategory::IpcReceiver => "Blocked at IPC Receive",
ProfilerCategory::ApplicationHeartbeat => "Application Heartbeat",
};
format!("{}{}", padding, name)
Expand Down Expand Up @@ -316,6 +317,13 @@ impl Profiler {
// only print if more data has arrived since the last printout
self.print_buckets();
},
ProfilerMsg::Get(k, sender) => {
let vec_option = self.buckets.get(&k);
match vec_option {
Some(vec_entry) => sender.send(ProfilerData::Record(vec_entry.to_vec())).unwrap(),
None => sender.send(ProfilerData::NoRecords).unwrap(),
};
},
ProfilerMsg::Exit(chan) => {
heartbeats::cleanup();
self.print_buckets();
Expand Down
1 change: 1 addition & 0 deletions components/profile_traits/Cargo.toml
Expand Up @@ -13,6 +13,7 @@ path = "lib.rs"
energy-profiling = ["energymon", "energy-monitor"]

[dependencies]
bincode = "1"
energy-monitor = {version = "0.2.0", optional = true}
energymon = {git = "https://github.com/energymon/energymon-rust.git", optional = true}
ipc-channel = "0.10"
Expand Down
45 changes: 45 additions & 0 deletions components/profile_traits/ipc.rs
@@ -0,0 +1,45 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use bincode;
use ipc_channel::ipc;
use serde::{Deserialize, Serialize};
use std::io::Error;
use time;
use time::ProfilerCategory;
use time::ProfilerChan;

pub struct IpcReceiver<T> where T: for<'de> Deserialize<'de> + Serialize {
ipc_receiver: ipc::IpcReceiver<T>,
time_profile_chan: ProfilerChan,
}

impl<T> IpcReceiver<T> where T: for<'de> Deserialize<'de> + Serialize {
pub fn recv(&self) -> Result<T, bincode::Error> {
time::profile(
ProfilerCategory::IpcReceiver,
None,
self.time_profile_chan.clone(),
move || self.ipc_receiver.recv(),
)
}

pub fn try_recv(&self) -> Result<T, bincode::Error> {
self.ipc_receiver.try_recv()
}

pub fn to_opaque(self) -> ipc::OpaqueIpcReceiver {
self.ipc_receiver.to_opaque()
}
}

pub fn channel<T>(time_profile_chan: ProfilerChan) -> Result<(ipc::IpcSender<T>, IpcReceiver<T>), Error>
where T: for<'de> Deserialize<'de> + Serialize, {
let (ipc_sender, ipc_receiver) = ipc::channel()?;
let profiled_ipc_receiver = IpcReceiver {
ipc_receiver,
time_profile_chan,
};
Ok((ipc_sender, profiled_ipc_receiver))
}
2 changes: 2 additions & 0 deletions components/profile_traits/lib.rs
Expand Up @@ -8,6 +8,7 @@

#![deny(unsafe_code)]

extern crate bincode;
extern crate ipc_channel;
#[macro_use]
extern crate log;
Expand All @@ -17,5 +18,6 @@ extern crate signpost;

#[allow(unsafe_code)]
pub mod energy;
pub mod ipc;
pub mod mem;
pub mod time;
9 changes: 9 additions & 0 deletions components/profile_traits/time.rs
Expand Up @@ -28,10 +28,18 @@ impl ProfilerChan {
}
}

#[derive(Clone, Deserialize, Serialize)]
pub enum ProfilerData {
NoRecords,
Record(Vec<f64>),
}

#[derive(Clone, Deserialize, Serialize)]
pub enum ProfilerMsg {
/// Normal message used for reporting time
Time((ProfilerCategory, Option<TimerMetadata>), (u64, u64), (u64, u64)),
/// Message used to get time spend entries for a particular ProfilerBuckets (in nanoseconds)
Get((ProfilerCategory, Option<TimerMetadata>), IpcSender<ProfilerData>),
/// Message used to force print the profiling metrics
Print,
/// Tells the profiler to shut down.
Expand Down Expand Up @@ -94,6 +102,7 @@ pub enum ProfilerCategory {
TimeToFirstPaint = 0x80,
TimeToFirstContentfulPaint = 0x81,
TimeToInteractive = 0x82,
IpcReceiver = 0x83,
ApplicationHeartbeat = 0x90,
}

Expand Down
12 changes: 6 additions & 6 deletions components/script/dom/blob.rs
Expand Up @@ -12,10 +12,10 @@ use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::str::DOMString;
use dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use ipc_channel::ipc;
use net_traits::{CoreResourceMsg, IpcSend};
use net_traits::blob_url_store::{BlobBuf, get_blob_origin};
use net_traits::filemanager_thread::{FileManagerThreadMsg, ReadFileProgress, RelativePos};
use profile_traits::ipc;
use std::mem;
use std::ops::Index;
use std::path::PathBuf;
Expand Down Expand Up @@ -200,7 +200,7 @@ impl Blob {
BlobImpl::File(ref f) => {
if set_valid {
let origin = get_blob_origin(&global_url);
let (tx, rx) = ipc::channel().unwrap();
let (tx, rx) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap();

let msg = FileManagerThreadMsg::ActivateBlobURL(f.id.clone(), tx, origin.clone());
self.send_to_file_manager(msg);
Expand All @@ -227,7 +227,7 @@ impl Blob {
bytes: bytes.to_vec(),
};

let (tx, rx) = ipc::channel().unwrap();
let (tx, rx) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap();
let msg = FileManagerThreadMsg::PromoteMemory(blob_buf, set_valid, tx, origin.clone());
self.send_to_file_manager(msg);

Expand All @@ -251,7 +251,7 @@ impl Blob {
rel_pos: &RelativePos, parent_len: u64) -> Uuid {
let origin = get_blob_origin(&self.global().get_url());

let (tx, rx) = ipc::channel().unwrap();
let (tx, rx) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap();
let msg = FileManagerThreadMsg::AddSlicedURLEntry(parent_id.clone(),
rel_pos.clone(),
tx, origin.clone());
Expand Down Expand Up @@ -280,7 +280,7 @@ impl Blob {
if let BlobImpl::File(ref f) = *self.blob_impl.borrow() {
let origin = get_blob_origin(&self.global().get_url());

let (tx, rx) = ipc::channel().unwrap();
let (tx, rx) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap();

let msg = FileManagerThreadMsg::DecRef(f.id.clone(), origin, tx);
self.send_to_file_manager(msg);
Expand All @@ -303,7 +303,7 @@ impl Drop for Blob {

fn read_file(global: &GlobalScope, id: Uuid) -> Result<Vec<u8>, ()> {
let resource_threads = global.resource_threads();
let (chan, recv) = ipc::channel().map_err(|_|())?;
let (chan, recv) = ipc::channel(global.time_profiler_chan().clone()).map_err(|_|())?;
let origin = get_blob_origin(&global.get_url());
let check_url_validity = false;
let msg = FileManagerThreadMsg::ReadFile(chan, id, check_url_validity, origin);
Expand Down
3 changes: 2 additions & 1 deletion components/script/dom/bluetooth.rs
Expand Up @@ -34,6 +34,7 @@ use ipc_channel::router::ROUTER;
use js::conversions::ConversionResult;
use js::jsapi::{JSContext, JSObject};
use js::jsval::{ObjectValue, UndefinedValue};
use profile_traits::ipc as ProfiledIpc;
use std::cell::Ref;
use std::collections::HashMap;
use std::rc::Rc;
Expand Down Expand Up @@ -613,7 +614,7 @@ impl PermissionAlgorithm for Bluetooth {
// Step 6.2.2.
// Instead of creating an internal slot we send an ipc message to the Bluetooth thread
// to check if one of the filters matches.
let (sender, receiver) = ipc::channel().unwrap();
let (sender, receiver) = ProfiledIpc::channel(global.time_profiler_chan().clone()).unwrap();
status.get_bluetooth_thread()
.send(BluetoothRequest::MatchesFilter(device_id.clone(),
BluetoothScanfilterSequence::new(scan_filters),
Expand Down
7 changes: 4 additions & 3 deletions components/script/dom/bluetoothdevice.rs
Expand Up @@ -24,7 +24,8 @@ use dom::eventtarget::EventTarget;
use dom::globalscope::GlobalScope;
use dom::promise::Promise;
use dom_struct::dom_struct;
use ipc_channel::ipc::{self, IpcSender};
use ipc_channel::ipc::IpcSender;
use profile_traits::ipc;
use std::cell::Cell;
use std::collections::HashMap;
use std::rc::Rc;
Expand Down Expand Up @@ -129,7 +130,7 @@ impl BluetoothDevice {
}

pub fn is_represented_device_null(&self) -> bool {
let (sender, receiver) = ipc::channel().unwrap();
let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap();
self.get_bluetooth_thread().send(
BluetoothRequest::IsRepresentedDeviceNull(self.Id().to_string(), sender)).unwrap();
receiver.recv().unwrap()
Expand Down Expand Up @@ -204,7 +205,7 @@ impl BluetoothDevice {
}

// Step 3.
let (sender, receiver) = ipc::channel().unwrap();
let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap();
self.get_bluetooth_thread().send(
BluetoothRequest::GATTServerDisconnect(String::from(self.Id()), sender)).unwrap();
receiver.recv().unwrap().map_err(Error::from)
Expand Down
11 changes: 6 additions & 5 deletions components/script/dom/canvasrenderingcontext2d.rs
Expand Up @@ -32,7 +32,7 @@ use dom::imagedata::ImageData;
use dom::node::{Node, NodeDamage, window_from_node};
use dom_struct::dom_struct;
use euclid::{Transform2D, Point2D, Vector2D, Rect, Size2D, vec2};
use ipc_channel::ipc::{self, IpcSender};
use ipc_channel::ipc::IpcSender;
use net_traits::image::base::PixelFormat;
use net_traits::image_cache::CanRequestImages;
use net_traits::image_cache::ImageCache;
Expand All @@ -41,6 +41,7 @@ use net_traits::image_cache::ImageResponse;
use net_traits::image_cache::ImageState;
use net_traits::image_cache::UsePlaceholder;
use num_traits::ToPrimitive;
use profile_traits::ipc;
use script_traits::ScriptMsg;
use servo_url::ServoUrl;
use std::{cmp, fmt, mem};
Expand Down Expand Up @@ -128,7 +129,7 @@ impl CanvasRenderingContext2D {
size: Size2D<i32>)
-> CanvasRenderingContext2D {
debug!("Creating new canvas rendering context.");
let (sender, receiver) = ipc::channel().unwrap();
let (sender, receiver) = ipc::channel(global.time_profiler_chan().clone()).unwrap();
let script_to_constellation_chan = global.script_to_constellation_chan();
debug!("Asking constellation to create new canvas thread.");
script_to_constellation_chan.send(ScriptMsg::CreateCanvasPaintThread(size, sender)).unwrap();
Expand Down Expand Up @@ -371,7 +372,7 @@ impl CanvasRenderingContext2D {
None => return Err(Error::InvalidState),
};

let (sender, receiver) = ipc::channel().unwrap();
let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap();
let msg = CanvasMsg::Canvas2d(Canvas2dMsg::DrawImageInOther(
self.ipc_renderer.clone(),
image_size,
Expand Down Expand Up @@ -782,7 +783,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
CanvasFillRule::Nonzero => FillRule::Nonzero,
CanvasFillRule::Evenodd => FillRule::Evenodd,
};
let (sender, receiver) = ipc::channel::<bool>().unwrap();
let (sender, receiver) = ipc::channel::<bool>(self.global().time_profiler_chan().clone()).unwrap();
self.ipc_renderer
.send(CanvasMsg::Canvas2d(Canvas2dMsg::IsPointInPath(x, y, fill_rule, sender)))
.unwrap();
Expand Down Expand Up @@ -1126,7 +1127,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
let sh = cmp::max(1, sh.to_u32().unwrap());
let sw = cmp::max(1, sw.to_u32().unwrap());

let (sender, receiver) = ipc::channel::<Vec<u8>>().unwrap();
let (sender, receiver) = ipc::channel::<Vec<u8>>(self.global().time_profiler_chan().clone()).unwrap();
let dest_rect = Rect::new(Point2D::new(sx.to_i32().unwrap(), sy.to_i32().unwrap()),
Size2D::new(sw as i32, sh as i32));
let canvas_size = self.canvas.as_ref().map(|c| c.get_size()).unwrap_or(Size2D::zero());
Expand Down
5 changes: 3 additions & 2 deletions components/script/dom/document.rs
Expand Up @@ -93,7 +93,7 @@ use fetch::FetchCanceller;
use html5ever::{LocalName, Namespace, QualName};
use hyper::header::{Header, SetCookie};
use hyper_serde::Serde;
use ipc_channel::ipc::{self, IpcSender};
use ipc_channel::ipc::IpcSender;
use js::jsapi::{JSContext, JSObject, JSRuntime};
use js::jsapi::JS_GetRuntime;
use metrics::{InteractiveFlag, InteractiveMetrics, InteractiveWindow, ProfilerMetadataFactory, ProgressiveWebMetric};
Expand All @@ -106,6 +106,7 @@ use net_traits::pub_domains::is_pub_domain;
use net_traits::request::RequestInit;
use net_traits::response::HttpsState;
use num_traits::ToPrimitive;
use profile_traits::ipc;
use profile_traits::time::{TimerMetadata, TimerMetadataFrameType, TimerMetadataReflowType};
use ref_slice::ref_slice;
use script_layout_interface::message::{Msg, NodesFromPointQueryType, ReflowGoal};
Expand Down Expand Up @@ -3448,7 +3449,7 @@ impl DocumentMethods for Document {
}

let url = self.url();
let (tx, rx) = ipc::channel().unwrap();
let (tx, rx) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap();
let _ = self.window
.upcast::<GlobalScope>()
.resource_threads()
Expand Down
7 changes: 4 additions & 3 deletions components/script/dom/history.rs
Expand Up @@ -8,17 +8,17 @@ use dom::bindings::codegen::Bindings::LocationBinding::LocationBinding::Location
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::inheritance::Castable;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::str::{DOMString, USVString};
use dom::bindings::structuredclone::StructuredCloneData;
use dom::globalscope::GlobalScope;
use dom::window::Window;
use dom_struct::dom_struct;
use ipc_channel::ipc;
use js::jsapi::{HandleValue, Heap, JSContext};
use js::jsval::{JSVal, NullValue, UndefinedValue};
use msg::constellation_msg::TraversalDirection;
use profile_traits::ipc::channel;
use script_traits::ScriptMsg;

enum PushOrReplace {
Expand Down Expand Up @@ -128,7 +128,8 @@ impl HistoryMethods for History {
if !self.window.Document().is_fully_active() {
return Err(Error::Security);
}
let (sender, recv) = ipc::channel().expect("Failed to create channel to send jsh length.");
let (sender, recv) =
channel(self.global().time_profiler_chan().clone()).expect("Failed to create channel to send jsh length.");
let msg = ScriptMsg::JointSessionHistoryLength(sender);
let _ = self.window.upcast::<GlobalScope>().script_to_constellation_chan().send(msg);
Ok(recv.recv().unwrap())
Expand Down
5 changes: 3 additions & 2 deletions components/script/dom/htmlcanvaselement.rs
Expand Up @@ -15,6 +15,7 @@ use dom::bindings::conversions::ConversionResult;
use dom::bindings::error::{Error, Fallible};
use dom::bindings::inheritance::Castable;
use dom::bindings::num::Finite;
use dom::bindings::reflector::DomObject;
use dom::bindings::root::{Dom, DomRoot, LayoutDom};
use dom::bindings::str::DOMString;
use dom::canvasrenderingcontext2d::{CanvasRenderingContext2D, LayoutCanvasRenderingContext2DHelpers};
Expand All @@ -31,10 +32,10 @@ use euclid::Size2D;
use html5ever::{LocalName, Prefix};
use image::ColorType;
use image::png::PNGEncoder;
use ipc_channel::ipc;
use js::error::throw_type_error;
use js::jsapi::{HandleValue, JSContext};
use offscreen_gl_context::GLContextAttributes;
use profile_traits::ipc;
use script_layout_interface::{HTMLCanvasData, HTMLCanvasDataSource};
use servo_config::prefs::PREFS;
use std::iter::repeat;
Expand Down Expand Up @@ -258,7 +259,7 @@ impl HTMLCanvasElement {

let data = match self.context.borrow().as_ref() {
Some(&CanvasContext::Context2d(ref context)) => {
let (sender, receiver) = ipc::channel().unwrap();
let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap();
let msg = CanvasMsg::FromScript(FromScriptMsg::SendPixels(sender));
context.get_ipc_renderer().send(msg).unwrap();

Expand Down
3 changes: 2 additions & 1 deletion components/script/dom/htmliframeelement.rs
Expand Up @@ -27,6 +27,7 @@ use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
use ipc_channel::ipc;
use msg::constellation_msg::{BrowsingContextId, PipelineId, TopLevelBrowsingContextId};
use profile_traits::ipc as ProfiledIpc;
use script_layout_interface::message::ReflowGoal;
use script_thread::ScriptThread;
use script_traits::{IFrameLoadInfo, IFrameLoadInfoWithData, JsEvalResult, LoadData, UpdatePipelineIdReason};
Expand Down Expand Up @@ -559,7 +560,7 @@ impl VirtualMethods for HTMLIFrameElement {

// https://html.spec.whatwg.org/multipage/#a-browsing-context-is-discarded
let window = window_from_node(self);
let (sender, receiver) = ipc::channel().unwrap();
let (sender, receiver) = ProfiledIpc::channel(self.global().time_profiler_chan().clone()).unwrap();

// Ask the constellation to remove the iframe, and tell us the
// pipeline ids of the closed pipelines.
Expand Down

0 comments on commit 7d4e2b1

Please sign in to comment.