Germany and Saudi Arabia have agreed to end a prolonged diplomatic row that prompted the kingdom to pull its ambassador from Berlin and punish German firms operating in the country.