Equilibrium and nonequilibrium many-body perturbation theory: a unified framework based on the Martin-Schwinger hierarchy