Beispiel #1
0
    def is_agent_running(self,
                         fail_if_running=False,
                         fail_if_not_running=False):
        """Returns true if the agent service is running, as determined by this platform implementation.

        This will optionally raise an Exception with an appropriate error message if the agent is running or not
        runnning.

        @param fail_if_running:  True if the method should raise an Exception with a platform-specific error message
            explaining how it determined the agent is running.
        @param fail_if_not_running: True if the method should raise an Exception with a platform-specific error message
            explaining how it determined the agent is not running.

        @type fail_if_running: bool
        @type fail_if_not_running: bool

        @return: True if the agent process is already running.
        @rtype: bool

        @raise AgentAlreadyRunning
        @raise AgentNotRunning
        """

        hscm = None
        hs = None

        try:
            hscm = win32service.OpenSCManager(None, None,
                                              win32service.SC_MANAGER_CONNECT)
            hs = win32serviceutil.SmartOpenService(
                hscm, _SCALYR_AGENT_SERVICE_,
                win32service.SERVICE_QUERY_STATUS)
            status = win32service.QueryServiceStatusEx(hs)

            state = status["CurrentState"]

            is_running = state in (
                win32service.SERVICE_RUNNING,
                win32service.SERVICE_START_PENDING,
            )
            if fail_if_running and is_running:
                pid = status["ProcessId"]
                raise AgentAlreadyRunning(
                    "The operating system reports the Scalyr Agent Service is running with "
                    "pid=%d" % pid)
            if fail_if_not_running and not is_running:
                raise AgentNotRunning(
                    "The operating system reports the Scalyr Agent Service is not running"
                )

            return state in (
                win32service.SERVICE_RUNNING,
                win32service.SERVICE_START_PENDING,
            )

        finally:
            if hs is not None:
                win32service.CloseServiceHandle(hs)
            if hscm is not None:
                win32service.CloseServiceHandle(hscm)
Beispiel #2
0
def setupRecoverService():
    svc_name = UDSActorSvc._svc_name_  # pylint: disable=protected-access

    try:
        hscm = win32service.OpenSCManager(None, None,
                                          win32service.SC_MANAGER_ALL_ACCESS)

        try:
            hs = win32serviceutil.SmartOpenService(
                hscm, svc_name, win32service.SERVICE_ALL_ACCESS)
            service_failure_actions = {
                'ResetPeriod':
                864000,  # Time in ms after which to reset the failure count to zero.
                'RebootMsg':
                u'',  # Not using reboot option
                'Command':
                u'',  # Not using run-command option
                'Actions': [
                    (win32service.SC_ACTION_RESTART,
                     5000),  # action, delay in ms
                    (win32service.SC_ACTION_RESTART, 5000)
                ]
            }
            win32service.ChangeServiceConfig2(
                hs, win32service.SERVICE_CONFIG_FAILURE_ACTIONS,
                service_failure_actions)
        finally:
            win32service.CloseServiceHandle(hs)
    finally:
        win32service.CloseServiceHandle(hscm)
Beispiel #3
0
    def on_host_init_response(self, message):
        global_variables = message.body.get('global_variables') or []
        for kv in global_variables:
            self._global_variables[kv['name']] = kv['value'].encode(
                'utf-8') if kv['value'] else ''

        if 'chef' in message.body and message.body['chef']:
            if linux.os.windows_family:
                self._chef_client_bin = r'C:\opscode\chef\bin\chef-client.bat'
                self._chef_solo_bin = r'C:\opscode\chef\bin\chef-solo.bat'
            else:
                # Workaround for 'chef' behavior enabled, but chef not installed
                self._chef_client_bin = which('chef-client')
                self._chef_solo_bin = which('chef-solo')

            self._chef_data = message.chef.copy()
            if not self._chef_data.get('node_name'):
                self._chef_data['node_name'] = self.get_node_name()

            self._with_json_attributes = self._chef_data.get(
                'json_attributes', {}) or {}
            if self._with_json_attributes:
                self._with_json_attributes = json.loads(
                    self._with_json_attributes)

            self._run_list = self._chef_data.get('run_list')
            if self._run_list:
                self._with_json_attributes['run_list'] = json.loads(
                    self._run_list)
            elif self._chef_data.get('role'):
                self._with_json_attributes['run_list'] = [
                    "role[%s]" % self._chef_data['role']
                ]

            if linux.os.windows_family:
                # TODO: why not doing the same on linux?
                try:
                    # Set startup type to 'manual' for chef-client service
                    hscm = win32service.OpenSCManager(
                        None, None, win32service.SC_MANAGER_ALL_ACCESS)
                    try:
                        hs = win32serviceutil.SmartOpenService(
                            hscm, WIN_SERVICE_NAME,
                            win32service.SERVICE_ALL_ACCESS)
                        try:
                            snc = win32service.SERVICE_NO_CHANGE
                            # change only startup type
                            win32service.ChangeServiceConfig(
                                hs, snc, win32service.SERVICE_DEMAND_START,
                                snc, None, None, 0, None, None, None, None)
                        finally:
                            win32service.CloseServiceHandle(hs)
                    finally:
                        win32service.CloseServiceHandle(hscm)

                    win32serviceutil.StopService(WIN_SERVICE_NAME)

                except:
                    e = sys.exc_info()[1]
                    self._logger.warning('Could not stop chef service: %s' % e)
Beispiel #4
0
def safe_open_service(hSCM, service_name):
  try:
    hSvc = win32serviceutil.SmartOpenService(hSCM, service_name,
                                             win32service.SERVICE_ALL_ACCESS)
  except win32api.error, details:
    if details.winerror == winerror.ERROR_SERVICE_DOES_NOT_EXIST:
      err_msg = "Invalid service name: {0}".format(service_name)
    else:
      err_msg = "Error configuring service {0}: {1}".format(service_name, details.winerror)
    raise Fail(err_msg)
Beispiel #5
0
    def is_running_as_nt_service():
        @contextmanager
        def close_srv(srv):
            try:
                yield srv
            finally:
                ws.CloseServiceHandle(srv)

        with close_srv(ws.OpenSCManager(None, None, ws.SC_MANAGER_ALL_ACCESS)) as hscm:
            with close_srv(wsu.SmartOpenService(hscm, nt_service_name, ws.SERVICE_ALL_ACCESS)) as hs:
                info = ws.QueryServiceStatusEx(hs)
                return info['ProcessId'] == getppid()
Beispiel #6
0
def QueryService(svc_name):
    """Query service and get its config."""
    hscm = win32service.OpenSCManager(None, None,
                                      win32service.SC_MANAGER_ALL_ACCESS)
    result = None
    try:
        hs = win32serviceutil.SmartOpenService(hscm, svc_name,
                                               win32service.SERVICE_ALL_ACCESS)
        result = win32service.QueryServiceConfig(hs)
        win32service.CloseServiceHandle(hs)
    finally:
        win32service.CloseServiceHandle(hscm)

    return result
Beispiel #7
0
    def on_host_init_response(self, message):
        self._global_variables = message.body.get('global_variables') or []
        # global_variables = message.body.get('global_variables') or []
        # for kv in global_variables:
        #     self._global_variables[kv['name']] = kv['value'].encode('utf-8') if kv['value'] else ''

        if 'chef' in message.body and message.body['chef']:
            self._hir_data = message.body.copy()
            self._chef_data = message.chef.copy()
            if not self._chef_data.get('node_name'):
                self._chef_data['node_name'] = self.get_node_name()
            self._chef_data['first_bootstrap'] = True

            self._with_json_attributes = extract_json_attributes(
                self._chef_data)

            if linux.os.windows_family:
                # TODO: why not doing the same on linux?
                try:
                    # Set startup type to 'manual' for chef-client service
                    hscm = win32service.OpenSCManager(
                        None, None, win32service.SC_MANAGER_ALL_ACCESS)
                    try:
                        hs = win32serviceutil.SmartOpenService(
                            hscm, WIN_SERVICE_NAME,
                            win32service.SERVICE_ALL_ACCESS)
                        try:
                            snc = win32service.SERVICE_NO_CHANGE
                            # change only startup type
                            win32service.ChangeServiceConfig(
                                hs, snc, win32service.SERVICE_DEMAND_START,
                                snc, None, None, 0, None, None, None, None)
                        finally:
                            win32service.CloseServiceHandle(hs)
                    finally:
                        win32service.CloseServiceHandle(hscm)

                    win32serviceutil.StopService(WIN_SERVICE_NAME)
                except:
                    e = sys.exc_info()[1]
                    self._logger.warning('Could not stop chef service: %s' % e)
Beispiel #8
0
  def action_uninstall(self):
    hSCM = safe_open_scmanager()

    try:
      try:
        hSvc = win32serviceutil.SmartOpenService(hSCM, self.resource.service_name,
                                                 win32service.SERVICE_ALL_ACCESS)
      except win32api.error, details:
        if details.winerror == winerror.ERROR_SERVICE_DOES_NOT_EXIST:
          # Nothing to do
          return
        else:
          raise Fail("Error removing service {0}: {1}".format(self.resource.service_name, details.winerror))

      try:
        win32service.DeleteService(hSvc)
      except win32api.error:
        # Error mostly means the service is running and its removal is delayed until the next opportunity
        pass
      finally:
        win32service.CloseServiceHandle(hSvc)
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from __future__ import unicode_literals

import win32service
import win32serviceutil

svc_name = "UDSActor"

try:
    hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS)

    try:
        hs = win32serviceutil.SmartOpenService(hscm, svc_name, win32service.SERVICE_ALL_ACCESS)
        service_failure_actions = {
            'ResetPeriod': 864000,  # Time in ms after which to reset the failure count to zero.
            'RebootMsg': u'',  # Not using reboot option
            'Command': u'',  # Not using run-command option
            'Actions': [
                (win32service.SC_ACTION_RESTART, 5000),  # action, delay in ms
                (win32service.SC_ACTION_RESTART, 5000)
            ]
        }
        win32service.ChangeServiceConfig2(hs, win32service.SERVICE_CONFIG_FAILURE_ACTIONS, service_failure_actions)
    finally:
        win32service.CloseServiceHandle(hs)
finally:
    win32service.CloseServiceHandle(hscm)
Beispiel #10
0
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# ----------------------------------------------------------------------

import win32event
import win32api
import win32con
import win32evtlogutil

import win32serviceutil
import servicemanager
import win32service

# Custom Widnows service control in the range of [128-255]
SERVICE_CONTROL_RELOAD = 128
SERVICE_NAME = "emadb"

# Get access to the Service Control Manager
hscm = win32service.OpenSCManager(None, None,
                                  win32service.SC_MANAGER_ALL_ACCESS)

# Open the desired service with
hs = win32serviceutil.SmartOpenService(hscm, SERVICE_NAME,
                                       win32service.SERVICE_ALL_ACCESS)

# Send the custom control
win32service.ControlService(hs, SERVICE_CONTROL_RELOAD)

# Close the service (probably not necessary)
win32service.CloseServiceHandle(hs)