  We introduce the notion of almost perfect obstruction theory on a
Deligne-Mumford stack and show that stacks with almost perfect obstruction
theories have virtual structure sheaves which are deformation invariant. The
main components in the construction are an induced embedding of the coarse
moduli sheaf of the intrinsic normal cone into the associated obstruction sheaf
stack and the construction of a $K$-theoretic Gysin map for sheaf stacks.
  We show that many stacks of interest admit almost perfect obstruction
theories. As a result, we are able to define virtual structure sheaves and
$K$-theoretic classical and generalized Donaldson-Thomas invariants of sheaves
and complexes on Calabi-Yau threefolds.
