Thermodynamics of rare events