Beispiel #1
0
 def test_context_manager(self):
     with xmlrpclib.ServerProxy(URL) as server:
         server.add(2, 3)
         self.assertNotEqual(server('transport')._connection,
                             (None, None))
     self.assertEqual(server('transport')._connection,
                      (None, None))
 def test_context_manager(self):
     with xmlrpclib.ServerProxy(URL) as server:
         server.add(2, 3)
         self.assertNotEqual(server('transport')._connection,
                             (None, None))
     self.assertEqual(server('transport')._connection,
                      (None, None))
Beispiel #3
0
 def test_context_manager_method_error(self):
     try:
         with xmlrpclib.ServerProxy(URL) as server:
             server.add(2, "a")
     except xmlrpclib.Fault:
         pass
     self.assertEqual(server('transport')._connection, (None, None))
Beispiel #4
0
	def __init__(self, port, loglevel, *controls):
		global	LOGLEVEL
		LOGLEVEL	= loglevel	# need to set for the debug function
		self.port	= port		# port to serv on
		xmlrpc.setLogLevel(loglevel)	# set the module logging level
		usage		= USAGE		# usage string
		self.killed	= 0		# true if we've been killed
		self.contrl	= []		# list of our control objects
		self.cmdlist	= {		# our command list
			'getclient'	: self.cgetclient,
			'kill'		: self.ckill,
			'leave'		: self.cleave,
			'ping'		: self.cping,
			'usage'		: self.cusage,
			}
		for cont in controls:
			(self.cmdlist, usage) = cont.link(self.cmdlist, usage)
			self.contrl.append(cont)
		self.usage	= usage
		self.server	= xmlrpc.server()
		self.server.addMethods(self.cmdlist)
		if sys.platform[:5] != 'linux':
			return			# cause this doesn't work on windows
		self.stdin	= xmlrpc.source(sys.stdin.fileno())
		self.stdin.setCallback(self.cstdin, xmlrpc.ACT_INPUT, self.server)
		self.server.addSource(self.stdin)
Beispiel #5
0
 def test_context_manager_method_error(self):
     try:
         with xmlrpclib.ServerProxy(URL) as server:
             server.add(2, "a")
     except xmlrpclib.Fault:
         pass
     self.assertEqual(server('transport')._connection,
                      (None, None))
Beispiel #6
0
def exampleCallback():
	src = xmlrpc.source(sys.stdin.fileno())
	print dir(src)
	serv = xmlrpc.server()
	serv.bindAndListen(2343)
	src.setCallback(stdinHandler, xmlrpc.ACT_INPUT, serv)
	serv.addSource(src)
	serv.work()
Beispiel #7
0
def exampleError():
	s = xmlrpc.server()
	s.bindAndListen(PORT)
	s.setOnErr(errorHandler)
	while 1:
		try:
			s.work()	# you could set a timeout if desired
		except:
			e = sys.exc_info()
			if e[0] in (KeyboardInterrupt, SystemExit):
				raise e[0], e[1], e[2]
			traceback.print_exc()
Beispiel #8
0
def main():
	METHODS = {
		'validator1.arrayOfStructsTest'		: arrayOfStructsTest,
		'validator1.countTheEntities'		: countTheEntities,
		'validator1.easyStructTest'		: easyStructTest,
		'validator1.echoStructTest'		: echoStructTest,
		'validator1.manyTypesTest'		: manyTypesTest,
		'validator1.moderateSizeArrayCheck'	: moderateSizeArrayCheck,
		'validator1.simpleStructReturnTest'	: simpleStructReturnTest,
		'validator1.nestedStructTest'		: nestedStructTest
	}
	s = xmlrpc.server()
	s.addMethods(METHODS)
	s.bindAndListen(PORT)
	while 1:
		try:
			s.work()
		except:
			traceback.print_exc()
Beispiel #9
0
def main():
	METHODS = {
		'interopEchoTests.echoString'		: echoStringTest,
		'interopEchoTests.echoInteger'		: echoIntegerTest,
		'interopEchoTests.echoFloat'		: echoFloatTest,
		'interopEchoTests.echoStruct'		: echoStructTest,
		'interopEchoTests.echoBase64'		: echoBase64Test,
		'interopEchoTests.echoDate'		: echoDateTest,
		'interopEchoTests.echoStringArray'	: echoStringArrayTest,
		'interopEchoTests.echoIntegerArray'	: echoIntegerArrayTest,
		'interopEchoTests.echoFloatArray'	: echoFloatArrayTest,
		'interopEchoTests.echoStructArray'	: echoStructArrayTest,
	}
	s = xmlrpc.server()
	s.addMethods(METHODS)
	s.bindAndListen(PORT)
	while 1:
		try:
			s.work()
		except:
			traceback.print_exc()
Beispiel #10
0
def exampleServer():
	global exitFlag

	exitFlag = 0
	s = xmlrpc.server()
	xmlrpc.setLogLevel(9)
#	s.setAuth(authenticate)
	s.addMethods({
		'echo' : echoMethod,
		'exit' : exitMethod,
		'fault' : faultMethod,
		'postpone' : postponeMethod
	})
	s.bindAndListen(PORT)
	while 1:
		try:
			s.work()	# you could set a timeout if desired
		except:
			e = sys.exc_info()
			if e[0] in (KeyboardInterrupt, SystemExit):
				raise e[0], e[1], e[2]
			traceback.print_exc()
		if exitFlag:
			break
Beispiel #11
0
    def Execute(self, opt, args):
        if opt.jobs:
            self.jobs = opt.jobs
        if self.jobs > 1:
            soft_limit, _ = _rlimit_nofile()
            self.jobs = min(self.jobs, (soft_limit - 5) / 3)

        if opt.network_only and opt.detach_head:
            print('error: cannot combine -n and -d', file=sys.stderr)
            sys.exit(1)
        if opt.network_only and opt.local_only:
            print('error: cannot combine -n and -l', file=sys.stderr)
            sys.exit(1)
        if opt.manifest_name and opt.smart_sync:
            print('error: cannot combine -m and -s', file=sys.stderr)
            sys.exit(1)
        if opt.manifest_name and opt.smart_tag:
            print('error: cannot combine -m and -t', file=sys.stderr)
            sys.exit(1)
        if opt.manifest_server_username or opt.manifest_server_password:
            if not (opt.smart_sync or opt.smart_tag):
                print('error: -u and -p may only be combined with -s or -t',
                      file=sys.stderr)
                sys.exit(1)
            if None in [
                    opt.manifest_server_username, opt.manifest_server_password
            ]:
                print('error: both -u and -p must be given', file=sys.stderr)
                sys.exit(1)

        if opt.manifest_name:
            self.manifest.Override(opt.manifest_name)

        if opt.smart_sync or opt.smart_tag:
            if not self.manifest.manifest_server:
                print(
                    'error: cannot smart sync: no manifest server defined in'
                    'manifest',
                    file=sys.stderr)
                sys.exit(1)

            manifest_server = self.manifest.manifest_server

            if not '@' in manifest_server:
                username = None
                password = None
                if opt.manifest_server_username and opt.manifest_server_password:
                    username = opt.manifest_server_username
                    password = opt.manifest_server_password
                else:
                    try:
                        info = netrc.netrc()
                    except IOError:
                        print(
                            '.netrc file does not exist or could not be opened',
                            file=sys.stderr)
                    else:
                        try:
                            parse_result = urllib.parse(manifest_server)
                            if parse_result.hostname:
                                username, _account, password = \
                                    info.authenticators(parse_result.hostname)
                        except TypeError:
                            # TypeError is raised when the given hostname is not present
                            # in the .netrc file.
                            print('No credentials found for %s in .netrc' %
                                  parse_result.hostname,
                                  file=sys.stderr)
                        except netrc.NetrcParseError as e:
                            print('Error parsing .netrc file: %s' % e,
                                  file=sys.stderr)

                if username and password:
                    manifest_server = manifest_server.replace(
                        '://', '://%s:%s@' % (username, password), 1)

            try:
                server = xmlrpc.server(manifest_server)
                if opt.smart_sync:
                    p = self.manifest.manifestProject
                    b = p.GetBranch(p.CurrentBranch)
                    branch = b.merge
                    if branch.startswith(R_HEADS):
                        branch = branch[len(R_HEADS):]

                    env = os.environ.copy()
                    if ('TARGET_PRODUCT' in env
                            and 'TARGET_BUILD_VARIANT' in env):
                        target = '%s-%s' % (env['TARGET_PRODUCT'],
                                            env['TARGET_BUILD_VARIANT'])
                        [success, manifest_str
                         ] = server.GetApprovedManifest(branch, target)
                    else:
                        [success,
                         manifest_str] = server.GetApprovedManifest(branch)
                else:
                    assert (opt.smart_tag)
                    [success, manifest_str] = server.GetManifest(opt.smart_tag)

                if success:
                    manifest_name = "smart_sync_override.xml"
                    manifest_path = os.path.join(
                        self.manifest.manifestProject.worktree, manifest_name)
                    try:
                        f = open(manifest_path, 'w')
                        try:
                            f.write(manifest_str)
                        finally:
                            f.close()
                    except IOError:
                        print('error: cannot write manifest to %s' %
                              manifest_path,
                              file=sys.stderr)
                        sys.exit(1)
                    self.manifest.Override(manifest_name)
                else:
                    print('error in getting manifest: %s' % manifest_str,
                          file=sys.stderr)
                    sys.exit(1)
            except (socket.error, IOError, xmlrpc.client.Fault) as e:
                print('error: cannot connect to manifest server %s:\n%s' %
                      (self.manifest.manifest_server, e),
                      file=sys.stderr)
                sys.exit(1)
            except xmlrpc.client.ProtocolError as e:
                print('error: cannot connect to manifest server %s:\n%d %s' %
                      (self.manifest.manifest_server, e.errcode, e.errmsg),
                      file=sys.stderr)
                sys.exit(1)

        rp = self.manifest.repoProject
        rp.PreSync()

        mp = self.manifest.manifestProject
        mp.PreSync()

        if opt.repo_upgraded:
            _PostRepoUpgrade(self.manifest, quiet=opt.quiet)

        if not opt.local_only:
            mp.Sync_NetworkHalf(quiet=opt.quiet,
                                current_branch_only=opt.current_branch_only)

        if mp.HasChanges:
            syncbuf = SyncBuffer(mp.config)
            mp.Sync_LocalHalf(syncbuf)
            if not syncbuf.Finish():
                sys.exit(1)
            self.manifest._Unload()
            if opt.jobs is None:
                self.jobs = self.manifest.default.sync_j

            if not portable.isPosix():
                # fix broken manifest.xml link
                pass

        all_projects = self.GetProjects(args,
                                        missing_ok=True,
                                        submodules_ok=opt.fetch_submodules)

        self._fetch_times = _FetchTimes(self.manifest)
        if not opt.local_only:
            to_fetch = []
            now = time.time()
            if _ONE_DAY_S <= (now - rp.LastFetch):
                to_fetch.append(rp)
            to_fetch.extend(all_projects)
            to_fetch.sort(key=self._fetch_times.Get, reverse=True)

            fetched = self._Fetch(to_fetch, opt)
            _PostRepoFetch(rp, opt.no_repo_verify)

            if opt.network_only:
                # bail out now; the rest touches the working tree
                return

            # Iteratively fetch missing and/or nested unregistered submodules
            previously_missing_set = set()
            while True:
                self.manifest._Unload()
                all_projects = self.GetProjects(
                    args, missing_ok=True, submodules_ok=opt.fetch_submodules)
                missing = []
                for project in all_projects:
                    if project.gitdir not in fetched:
                        missing.append(project)
                if not missing:
                    break
                    # Stop us from non-stopped fetching actually-missing repos: If set of
                # missing repos has not been changed from last fetch, we break.
                missing_set = set(p.name for p in missing)
                if previously_missing_set == missing_set:
                    break
                previously_missing_set = missing_set
                fetched.update(self._Fetch(missing, opt))

        if self.manifest.IsMirror:
            # bail out now, we have no working tree
            return

        if self.UpdateProjectList():
            sys.exit(1)

        syncbuf = SyncBuffer(mp.config, detach_head=opt.detach_head)
        pm = Progress('Syncing work tree', len(all_projects))
        for project in all_projects:
            pm.update()
            if project.worktree:
                if opt.report:
                    p = GitCommand(
                        project,
                        ['log', '--pretty=%h %s (%cn, %ar)', 'HEAD..m/master'],
                        capture_stdout=True)
                    if p.Wait() != 0:
                        print("Failed to create report")
                    else:
                        if len(p.stdout):
                            print('\n' + project.name + ':\n')
                            print(portable.stream2str(p.stdout)[:-1])
                            print('\n')
                if not opt.dry_run:
                    project.Sync_LocalHalf(syncbuf)
        pm.end()
        print(file=sys.stderr)
        if not syncbuf.Finish():
            sys.exit(1)

        # If there's a notice that's supposed to print at the end of the sync, print
        # it now...
        if self.manifest.notice:
            print(self.manifest.notice)
Beispiel #12
0
    def Execute(self, opt, args):
        if opt.jobs:
            self.jobs = opt.jobs
        if self.jobs > 1:
            soft_limit, _ = _rlimit_nofile()
            self.jobs = min(self.jobs, (soft_limit - 5) / 3)

        if opt.network_only and opt.detach_head:
            print('error: cannot combine -n and -d', file=sys.stderr)
            sys.exit(1)
        if opt.network_only and opt.local_only:
            print('error: cannot combine -n and -l', file=sys.stderr)
            sys.exit(1)
        if opt.manifest_name and opt.smart_sync:
            print('error: cannot combine -m and -s', file=sys.stderr)
            sys.exit(1)
        if opt.manifest_name and opt.smart_tag:
            print('error: cannot combine -m and -t', file=sys.stderr)
            sys.exit(1)
        if opt.manifest_server_username or opt.manifest_server_password:
            if not (opt.smart_sync or opt.smart_tag):
                print('error: -u and -p may only be combined with -s or -t',
                      file=sys.stderr)
                sys.exit(1)
            if None in [opt.manifest_server_username, opt.manifest_server_password]:
                print('error: both -u and -p must be given', file=sys.stderr)
                sys.exit(1)

        if opt.manifest_name:
            self.manifest.Override(opt.manifest_name)

        if opt.smart_sync or opt.smart_tag:
            if not self.manifest.manifest_server:
                print('error: cannot smart sync: no manifest server defined in'
                      'manifest', file=sys.stderr)
                sys.exit(1)

            manifest_server = self.manifest.manifest_server

            if not '@' in manifest_server:
                username = None
                password = None
                if opt.manifest_server_username and opt.manifest_server_password:
                    username = opt.manifest_server_username
                    password = opt.manifest_server_password
                else:
                    try:
                        info = netrc.netrc()
                    except IOError:
                        print('.netrc file does not exist or could not be opened',
                              file=sys.stderr)
                    else:
                        try:
                            parse_result = urllib.parse(manifest_server)
                            if parse_result.hostname:
                                username, _account, password = \
                                    info.authenticators(parse_result.hostname)
                        except TypeError:
                            # TypeError is raised when the given hostname is not present
                            # in the .netrc file.
                            print('No credentials found for %s in .netrc'
                                  % parse_result.hostname, file=sys.stderr)
                        except netrc.NetrcParseError as e:
                            print('Error parsing .netrc file: %s' % e, file=sys.stderr)

                if username and password:
                    manifest_server = manifest_server.replace('://', '://%s:%s@' %
                                                                     (username, password),
                                                              1)

            try:
                server = xmlrpc.server(manifest_server)
                if opt.smart_sync:
                    p = self.manifest.manifestProject
                    b = p.GetBranch(p.CurrentBranch)
                    branch = b.merge
                    if branch.startswith(R_HEADS):
                        branch = branch[len(R_HEADS):]

                    env = os.environ.copy()
                    if ('TARGET_PRODUCT' in env and
                                'TARGET_BUILD_VARIANT' in env):
                        target = '%s-%s' % (env['TARGET_PRODUCT'],
                                            env['TARGET_BUILD_VARIANT'])
                        [success, manifest_str] = server.GetApprovedManifest(branch, target)
                    else:
                        [success, manifest_str] = server.GetApprovedManifest(branch)
                else:
                    assert (opt.smart_tag)
                    [success, manifest_str] = server.GetManifest(opt.smart_tag)

                if success:
                    manifest_name = "smart_sync_override.xml"
                    manifest_path = os.path.join(self.manifest.manifestProject.worktree,
                                                 manifest_name)
                    try:
                        f = open(manifest_path, 'w')
                        try:
                            f.write(manifest_str)
                        finally:
                            f.close()
                    except IOError:
                        print('error: cannot write manifest to %s' % manifest_path,
                              file=sys.stderr)
                        sys.exit(1)
                    self.manifest.Override(manifest_name)
                else:
                    print('error in getting manifest: %s' % manifest_str, file=sys.stderr)
                    sys.exit(1)
            except (socket.error, IOError, xmlrpc.client.Fault) as e:
                print('error: cannot connect to manifest server %s:\n%s'
                      % (self.manifest.manifest_server, e), file=sys.stderr)
                sys.exit(1)
            except xmlrpc.client.ProtocolError as e:
                print('error: cannot connect to manifest server %s:\n%d %s'
                      % (self.manifest.manifest_server, e.errcode, e.errmsg),
                      file=sys.stderr)
                sys.exit(1)

        rp = self.manifest.repoProject
        rp.PreSync()

        mp = self.manifest.manifestProject
        mp.PreSync()

        if opt.repo_upgraded:
            _PostRepoUpgrade(self.manifest, quiet=opt.quiet)

        if not opt.local_only:
            mp.Sync_NetworkHalf(quiet=opt.quiet,
                                current_branch_only=opt.current_branch_only)

        if mp.HasChanges:
            syncbuf = SyncBuffer(mp.config)
            mp.Sync_LocalHalf(syncbuf)
            if not syncbuf.Finish():
                sys.exit(1)
            self.manifest._Unload()
            if opt.jobs is None:
                self.jobs = self.manifest.default.sync_j

            if not portable.isPosix():
                # fix broken manifest.xml link
                pass

        all_projects = self.GetProjects(args,
                                        missing_ok=True,
                                        submodules_ok=opt.fetch_submodules)

        self._fetch_times = _FetchTimes(self.manifest)
        if not opt.local_only:
            to_fetch = []
            now = time.time()
            if _ONE_DAY_S <= (now - rp.LastFetch):
                to_fetch.append(rp)
            to_fetch.extend(all_projects)
            to_fetch.sort(key=self._fetch_times.Get, reverse=True)

            fetched = self._Fetch(to_fetch, opt)
            _PostRepoFetch(rp, opt.no_repo_verify)

            if opt.network_only:
                # bail out now; the rest touches the working tree
                return

            # Iteratively fetch missing and/or nested unregistered submodules
            previously_missing_set = set()
            while True:
                self.manifest._Unload()
                all_projects = self.GetProjects(args,
                                                missing_ok=True,
                                                submodules_ok=opt.fetch_submodules)
                missing = []
                for project in all_projects:
                    if project.gitdir not in fetched:
                        missing.append(project)
                if not missing:
                    break
                    # Stop us from non-stopped fetching actually-missing repos: If set of
                # missing repos has not been changed from last fetch, we break.
                missing_set = set(p.name for p in missing)
                if previously_missing_set == missing_set:
                    break
                previously_missing_set = missing_set
                fetched.update(self._Fetch(missing, opt))

        if self.manifest.IsMirror:
            # bail out now, we have no working tree
            return

        if self.UpdateProjectList():
            sys.exit(1)

        syncbuf = SyncBuffer(mp.config,
                             detach_head=opt.detach_head)
        pm = Progress('Syncing work tree', len(all_projects))
        for project in all_projects:
            pm.update()
            if project.worktree:
                if opt.report:
                    p = GitCommand(project, ['log',
                        '--pretty=%h %s (%cn, %ar)',
                        'HEAD..m/master'],
                           capture_stdout=True)
                    if p.Wait() != 0:
                        print("Failed to create report")
                    else:
                        if len(p.stdout):
                            print('\n' + project.name + ':\n')
                            print(portable.stream2str(p.stdout)[:-1])
                            print('\n')
                if not opt.dry_run:
                    project.Sync_LocalHalf(syncbuf)
        pm.end()
        print(file=sys.stderr)
        if not syncbuf.Finish():
            sys.exit(1)

        # If there's a notice that's supposed to print at the end of the sync, print
        # it now...
        if self.manifest.notice:
            print(self.manifest.notice)