<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:

def disconnect(self):
        '''
        This is called as part of the agency shutdown.
        '''
        self.log("Disconnecting broker %r.", self)
        d = defer.succeed(None)
        if self.is_master():
            if self.listener is not None:
                d.addCallback(defer.drop_param, self.listener.stopListening)
                d.addCallback(defer.drop_param, self.factory.disconnect)
        elif self.is_slave():
            d = defer.maybeDeferred(self.factory.disconnect)
        elif self._cmp_state(BrokerRole.disconnected):
            return defer.succeed(None)
        d.addCallback(defer.drop_param, self.become_disconnected)
        return d