Why did Ezra pull out the hairs on his head and beard?

Because Israelite men married foreign women

They have taken of their daughters for themselves, and for their sons: so that the holy seed have mingled themselves with the people of those lands.

When I heard this thing, I rent my garment and my mantle, and plucked off the hair of my head and of my beard, and sat down astonished. Ezra 9:2-3