Track memory utilization of processes and graph the data via Chartkick, Highcharts, and Rails
In this post I’ll share some code to track the memory utilization of a number of processes and graph the data via Chartkick, Highcharts, and Rails for the backend.
Initial project setup:
Add Chatkick gem, edit file: Gemfile, add:
Execute bundle install to install the new gem.
Create the migrations for two new tables: one for the process name, and another for the memory profile entries. I had plans to track more information in both tables, but decided to simplify for this post. For instance: a custom regex for each process, and being able to track each process’s child processes separately.
Execute rake db:migrate to create the new tables.
Add model validations and association to ProcessProperty, edit file: app/models/process_property.rb
Add model validations and association to ProcessMemoryItem, edit file: app/models/process_memory_item.rb
I then seeded my database, either via rails console or in db/seeds.rb
Next I created a new service class (ProcessMemoryService) to execute a ps command, parse the output, and create model data for each process name. new file: app/models/process_memory_service.rb
Create a new rake task to run the new service, new file: lib/tasks/monitor.rake
Started the monitoring service via: rake monitor:process_memory. I left this running to collect data for an extended period.
I then shifted gears to build the frontend. I added a class method to ProcessMemoryItem to join the tables together, group by process name, and then collect the data per process by created_at and memory usage. edit file: app/models/process_memory_item.rb
I added a new controller to execute the above class method and pass the data to an ERB view, new file: app/controllers/process_memories_controller.rb
Contents of new ERB file, app/views/process_memories/index.html.erb
And last added the controller route, edit file: config/routes.rb
Started rails via rails s, browsed to http://localhost:3000 to see the memory utilization graphed: