def main():
    # Connect to LP
    print("connecting to launchpad")
    try:
        Launchpad.login_with('openstack-releasing', 'production')
    except Exception as error:
        abort(2, 'Could not connect to Launchpad: ' + str(error))
def get_launchpad(use_staging=False, use_cred_file=os.path.expanduser(CRED_FILE_PATH)):
    '''Get THE Launchpad'''
    global launchpad
    if not launchpad:
        if use_staging:
            server = 'staging'
        else:
            server = 'production'

        # as launchpadlib isn't multiproc, fiddling the cache dir if any
        launchpadlib_dir = os.getenv("JOB_NAME")
        if launchpadlib_dir:
            launchpadlib_dir = os.path.join(COMMON_LAUNCHPAD_CACHE_DIR, launchpadlib_dir)

        if use_cred_file:
            launchpad = Launchpad.login_with('cupstream2distro', server, allow_access_levels=["WRITE_PRIVATE"],
                                             version='devel',  # devel because copyPackage is only available there
                                             credentials_file=use_cred_file,
                                             launchpadlib_dir=launchpadlib_dir)
        else:
            launchpad = Launchpad.login_with('cupstream2distro', server, allow_access_levels=["WRITE_PRIVATE"],
                                             version='devel',  # devel because copyPackage is only available there
                                             launchpadlib_dir=launchpadlib_dir)

    return launchpad
示例#3
0
def login(instance):
    try:
        import launchpadlib.credentials
        store = launchpadlib.credentials.KeyringCredentialStore(None,
                                                                fallback=True)
        return Launchpad.login_with("ubuntu-cdimage",
                                    instance,
                                    version="devel",
                                    credential_store=store)
    except TypeError:
        # prior to focal (1.10.13), the fallback= kwarg didn't exist and
        # Launchpadlib worked under sudo
        return Launchpad.login_with("ubuntu-cdimage",
                                    instance,
                                    version="devel")
示例#4
0
def main():
    description = """
    Command line tool to operate with bugs and blueprints
    """
    parser = argparse.ArgumentParser(epilog=description)
    parser.add_argument('project', type=str)
    parser.add_argument('cmd', type=str, choices=['get', 'set'])
    parser.add_argument('item_type', type=str, choices=['bp', 'bug'])
    parser.add_argument('item_id', type=str, nargs='+')
    parser.add_argument('--milestone', type=str)
    parser.add_argument('--series', type=str)
    parser.add_argument('--approve', dest='approved', action='store_true')
    parser.add_argument('--create', action='store_true')
    parser.add_argument('--delete', action='store_true')
    parser.add_argument('--priority', type=str)
    parser.add_argument('--status', type=str)
    params, other_params = parser.parse_known_args()
    global lp
    global prj
    lp = Launchpad.login_with('lp-client', 'production', version='devel')
    prj = lp.projects[params.project]
    if params.cmd == 'set':
        for item_id in params.item_id:
            if params.item_type == 'bp':
                update_bp(item_id, params)
            if params.item_type == 'bug':
                update_bug(item_id, params)
示例#5
0
def upload_file(environment):
    "Send a file to Launchpad"
    filenames = glob.glob("dist/*.tar.gz")
    if len(filenames) > 1:
        print "Directory is unclean"
        sys.exit(1)
    
    filename = filenames[0]
    file_content = open(os.path.join(filename), 'r').read()

    signature_filename = filename+".asc"
    if not os.path.isfile(signature_filename):
        os.system("gpg --armor --sign --detach-sig %s" % filename)

    signature_content = open(signature_filename, 'r').read()

    component_info = yaml.load(open("component_info.yml").read())
    description = component_info["description"]

    print("Logging in to Launchpad %s..." % LAUNCHPAD_ENVIRONMENT)
    launchpad = Launchpad.login_with(APP_NAME, environment, CACHE_DIR)
    project = launchpad.projects["bombardier"]
    series1 = project.series[1] # 1.00
    alpha = series1.releases[0]
    #beta = series1.releases[1]

    print("Uploading file (%s)..." % description)
    alpha.add_file(file_type="Code Release Tarball",
                   description = description,
                   filename = base(filename),
                   content_type = "application/x-gtar",
                   file_content = file_content,
                   signature_filename = base(signature_filename),
                   signature_content = signature_content,
                  )
示例#6
0
 def _lp_login(self, access_level=['READ_PRIVATE']):
     """ internal LP login code """
     self._logger.debug("lp_login")
     # use cachedir
     cachedir = SOFTWARE_CENTER_CACHE_DIR
     if not os.path.exists(cachedir):
         os.makedirs(cachedir)
     # login into LP with GUI
     try:
         self._launchpad = Launchpad.login_with(
             'software-center',
             SERVICE_ROOT,
             cachedir,
             allow_access_levels=access_level,
             authorizer_class=AuthorizeRequestTokenFromThread)
         self.display_name = self._launchpad.me.display_name
     except Exception as e:
         if type(e) == UserCancelException:
             return
         self._logger.exception("Launchpad.login_with()")
         # remove token on failure, it may be e.g. expired
         # FIXME: store the token in a different place and to avoid
         #        having to use _get_paths()
         (service_root, launchpadlib_dir, cache_path,
          service_root_dir) = Launchpad._get_paths(SERVICE_ROOT, cachedir)
         credentials_path = os.path.join(service_root_dir, 'credentials')
         consumer_credentials_path = os.path.join(credentials_path,
                                                  'software-center')
         # ---
         if os.path.exists(consumer_credentials_path):
             os.remove(consumer_credentials_path)
         self._lp_login(access_level)
         return
     self.login_state = LOGIN_STATE_SUCCESS
     self._logger.debug("/done %s" % self._launchpad)
示例#7
0
文件: lp_api.py 项目: zeta1999/breezy
def connect_launchpad(base_url,
                      timeout=None,
                      proxy_info=None,
                      version=Launchpad.DEFAULT_VERSION):
    """Log in to the Launchpad API.

    :return: The root `Launchpad` object from launchpadlib.
    """
    if proxy_info is None:
        import httplib2
        proxy_info = httplib2.proxy_info_from_environment('https')
    try:
        cache_directory = get_cache_directory()
    except EnvironmentError:
        cache_directory = None
    credential_store = get_credential_store()
    authorization_engine = get_auth_engine(base_url)
    return Launchpad.login_with('breezy',
                                base_url,
                                cache_directory,
                                timeout=timeout,
                                credential_store=credential_store,
                                authorization_engine=authorization_engine,
                                proxy_info=proxy_info,
                                version=version)
示例#8
0
    def take_action(self, parsed_args):
        self.log.debug('connecting to Launchpad')
        lp = Launchpad.login_with('lp-report-bot',
                                  'production',
                                  version='devel')

        teams_map = {}
        for team_filter in parsed_args.substring:
            for team in lp.people.findTeam(text=team_filter):
                self.log.debug("found team: %s" % team.name)
                teams_map[team.name] = []
        self.log.debug("Getting teams members")
        i = 0
        for t in teams_map:
            i += 1
            self.log.debug("%d/%d %s" % (i, len(teams_map), t))
            for p in lp.people[t].members:
                try:
                    teams_map[t] += [p.name]
                except KeyError:
                    teams_map[t] = [p.name]

        df_teams = pd.DataFrame(columns=teams_map.keys())

        for t in teams_map.keys():
            for p in teams_map[t]:
                try:
                    df_teams.loc[p][t] = t
                except KeyError:
                    df_teams.loc[p] = float('nan')
                    df_teams.loc[p][t] = t

        self.log.debug("Saving data to %s" % parsed_args.outfile)
        df_teams.to_csv(parsed_args.outfile, encoding='utf-8')
    def process_stacks(self, stacks, threshold, default_config_path):
        launchpad = Launchpad.login_with('check_stalled_mps', 'production',
                                         credentials_file=CREDENTIALS_FILE,
                                         launchpadlib_dir=LAUNCHPADLIB_DIR)
        threshold = datetime.timedelta(minutes=threshold)
        stalled = []

        for stack in stacks:
            default_config = load_default_cfg(default_config_path)
            stackcfg = load_stack_cfg(stack, default_config)
            if not stackcfg:
                logging.error('Stack configuration failed to load. Ignoring')
                break
            for section_name in ['projects']:
                project_section = stackcfg.get(section_name, [])
                if project_section is None:
                    continue
                for project in project_section:
                    parameters = stackcfg[section_name][project]
                    target_branch = 'lp:' + project
                    if parameters and 'target_branch' in parameters:
                        target_branch = parameters['target_branch']
                    branch_stalled = self.check_branch(launchpad,
                                                       target_branch,
                                                       threshold)
                    if branch_stalled:
                        stalled = stalled + branch_stalled
        for message in stalled:
            logging.error(message)
        if stalled:
            return 1
        return 0
示例#10
0
    def set_authorization(self, application=None, server=None):

        if application is not None and server is not None:
            self.launchpad = Launchpad.login_with(application, server, self.__cachedir,
                                                  credential_save_failed=self.__no_credential, version='devel')
        else:
            self.launchpad = Launchpad.login_anonymously('just testing', 'production', self.__cachedir, version='devel')
示例#11
0
def create_bug(name, version, url):
    '''Taking advantage of launchpadlib we can create a Launchpad Bug, 
it is assumed you first used compare_titles() to verify a bug does not already exits'''
    launchpad = Launchpad.login_with(os.path.basename(sys.argv[0]), 'production')
    ius = launchpad.projects.search(text='ius')[0]
    mytitle = 'UPDATE REQUEST: ' +  name + ' ' +  str(version) + ' is available upstream'
    launchpad.bugs.createBug(description='New Source from Upstream: ' + url, title=mytitle, target=ius)
示例#12
0
def main():
    global jira_server
    usage = """\
usage: lp-to-jira-monitor project-id

Examples:
    lp-to-jira-monitor FR
    """
    opt_parser = OptionParser(usage)
    opts, args = opt_parser.parse_args()

    # # Make sure there's at least 1 arguments
    if len(args) < 1:
        opt_parser.print_usage()
        return 1

    jira_project = args[0]

    # 1. Initialize JIRA API
    print("Initialize JIRA API ...")
    api = jira_api()
    jira_server = api.server
    jira = JIRA(api.server, basic_auth=(api.login, api.token))

    # TODO: catch exception if the Launchpad API isn't open
    # 2. Initialize Launchpad API
    print("Initialize Launchpad API ...")
    lp = Launchpad.login_with('foundations', 'production', version='devel')

    try:
        with open(db_json) as fp:
            jira_lp_db = json.load(fp)
        # TODO: check if there's new entry in JIRA that need to be added to the DB
        # refresh_db(jira, lp, jira_project, jira_lp_db)
    except (FileNotFoundError):
        jira_lp_db = build_db(jira, lp, jira_project)

    print("\nFound %s issues" % len(jira_lp_db))
    # Saving DB to disk
    with open(db_json, 'w') as fp:
        json.dump(jira_lp_db, fp, indent=2)

    has_changed = False
    while not has_changed:
        print("Searching for changes %s" % datetime.datetime.now())
        for bug in jira_lp_db:
            try:
                old_date = jira_lp_db[bug]['LAST_CHANGE']
                current_date = "%s" % lp.bugs[int(bug)].date_last_updated
                if current_date != old_date:
                    has_changed = True
                    print("%s has changed since last refresh" % bug)
                    # TODO: compare issues and update JIRA item accordingly
                    # TODO: then replace date in db
                    # TODO: We could think of policy allowing to only update certain field like description, title

            except Exception:
                pass

    return 0
示例#13
0
    def __init__(self):
        #
        # getuser - getpassword - getdatabase
        #
        self.dbuser = "******"
        self.dbpass = "******"
        self.dbname = "launchpad_test"
        self.pname = "glance"
        self.delay = 3

        self._initialize_database()

        print("Launchpad test using the project %s" % self.pname)

        homedir = pwd.getpwuid(os.getuid()).pw_dir
        cachedir = os.path.join(homedir, ".cache/bicho/")
        if not os.path.exists(cachedir):
            os.makedirs(cachedir)
        cre_file = os.path.join(cachedir + 'launchpad-credential')
        self.lp = Launchpad.login_with('Bicho','production',
                                       credentials_file = cre_file)
        sys.stdout.write("Using credential file %s \n" % str(cre_file))

        self.all_bugs = self.lp.projects[self.pname].searchTasks(
            status=_all_status,
            omit_duplicates=False)

        self.notdupe_bugs = self.lp.projects[self.pname].searchTasks(
            status=_all_status,
            omit_duplicates=True)

        self.patches_bugs = self.lp.projects[self.pname].searchTasks(
            status=_all_status,
            omit_duplicates=False,
            has_patch=True)
示例#14
0
def main():
    """Find and delete superseded packages in Liquorix PPA"""
    cachedir = os.path.expanduser('~/.launchpadlib/cache')
    launchpad = Launchpad.login_with('Liquorix',
                                     'production',
                                     cachedir,
                                     version='devel')
    ppa = launchpad.me.getPPAByName(name="liquorix")

    # We can either user superseded sources or binaries.  Sources supersede
    # immediately while binaries only superseded after a new binary has been
    # published.  This works in our favor since we only want to delete the
    # package if there's a new version available for download.
    #
    # However, I've found that even though you may delete the superseded
    # binaries, they get stuck in the PPA until the package is removed
    # through the published source.  So in that case, this script will
    # find superseded sources, attempt to delete any superseded binaries in
    # the process.  If any binaries that can't be removed are found, then
    # the sources will not be deleted.
    sources = ppa.getPublishedSources(status="Superseded")

    for source_entry in sources.entries:
        delete_source(launchpad, source_entry)

    print("[INFO ] Script complete!")
示例#15
0
def main(args):
    global launchpad 
    global dist 

    usage = """%s: bug-id %s""" % (sys.argv[0], __doc__)
    parser = OptionParser(usage=usage)

    parser.add_option(
        '-n', '--dryrun', action='store_true',
        help='Describe what the script would do without doing it.')
    parser.add_option(
            '-p', '--project', type="string", action="store", dest="project",
            default="juniperopenstack", help="launchpad project to work on")
    parser.add_option(
            '-e', '--series', type="string", action="store", dest="series", 
            default="all", help="Edit or create series. default is 'all'")

    (options, args) = parser.parse_args(args=args)

    if len(args) < 2:
        parser.print_usage()
        return 1

    for bug_id in args[1:]:
        launchpad = Launchpad.login_with('delete_scope', 'production', version='devel')
        dist = launchpad.distributions[options.project]
        bug = launchpad.bugs[bug_id]
        if options.series is not None:
            delete_scope(bug, options)
示例#16
0
def main():
    parser = ArgumentParser(
        description="Calculate some statistics about project bugs.",
        epilog=dedent("""\
            Known caveats:
            Historical data uses the current task metadata rather than
            historical values. This is primarily due to performance
            considerations with the LP API and may be rectified in future (e.g.
            by mirroring the data persistently). As an example, if a bug is
            currently set to 'critical', it will show as critical in all time
            periods rather than progressing through different categories as it
            is triaged.
            """))
    parser.add_argument(
        '-p', '--project', default='projects/nova.json',
        help='JSON file describing the project to generate stats for.')
    args = parser.parse_args()
    projects = utils.get_projects_info(args.project, False)
    lp_project_listeners = {}
    listeners = set()
    if not projects:
        sys.stderr.write('No projects found: please specify one or more.\n')
        return 1
    launchpad = Launchpad.login_with(
        'openstack-releasing', 'production', credentials_file='.lpcreds')

    for project in projects:
        lp_projects = project.get('lp_projects', [])
        if not lp_projects:
            print "Please specify a project."
            return 1
        listener = Listener(project['name'], lp_projects)
        listeners.add(listener)
        for lp_project in project.get('lp_projects', []):
            lp_project_listeners.setdefault(lp_project, []).append(listener)

    statuses = ['New', 'Incomplete', 'Opinion', 'Invalid', "Won't Fix",
        'Confirmed', 'Triaged', 'In Progress', "Fix Committed", "Fix Released"]

    bugs_by_bug_link = {}
    for lp_project, receivers in lp_project_listeners.items():
        proj = launchpad.projects[lp_project]
        # Sort by id to make creating time periods easy.
        bugtasks = proj.searchTasks(status=statuses, order_by="id")
        for task in bugtasks:
            if task.bug_link not in bugs_by_bug_link:
                bugs_by_bug_link[task.bug_link] = task.bug
            bug = bugs_by_bug_link[task.bug_link]
            for receiver in receivers:
                receiver.categorise_task(task, bug)

    for listener in listeners:
        sys.stdout.write("Project: %s\n" % listener.name)
        sys.stdout.write("LP Projects: %s\n" % listener.lp_projects)
        table = prettytable.PrettyTable(
            ('Period', 'critical', 'high', 'undecided', 'other', 'total',
             'created', 'closed', 'critical-tags'))
        for period in listener.summarise():
            table.add_row(period)
        sys.stdout.write("%s\n" % table)
def main():
    args = _parse_args()

    lp = Launchpad.login_with('openstack-releasing', 'production')

    for project in args.projects:
        _cleanup_project(lp, project)
示例#18
0
def main():
    args = parse_options()
    logging.basicConfig(level=log_level(args.verbose),
                        format='%(levelname)s:%(message)s')

    review_message = get_message(args.message)  # before connecting to lp

    logging.debug('login with %s launchpad:', args.lp_instance)
    lp = Launchpad.login_with('charm-pilot', args.lp_instance)

    bug_id = args.bug_id
    logging.debug('find bug %s:', bug_id)
    bug = lp.bugs[bug_id]

    if bug:
        logging.debug('found bug')

        if args.skip_prompt or prompt_to_continue(bug_id):
            logging.debug('adding comment')
            # TODO check return or catch exception
            bug.newMessage(content=review_message)
        else:
            logging.debug('not adding comment')

    else:
        logging.error("no bug: %s", bug_id)
        return 1

    return 0
示例#19
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('hook')
    #common
    parser.add_argument('--change', default=None)
    parser.add_argument('--change-url', default=None)
    parser.add_argument('--project', default=None)
    parser.add_argument('--branch', default=None)
    parser.add_argument('--commit', default=None)
    #change-merged
    parser.add_argument('--submitter', default=None)
    # patchset-created
    parser.add_argument('--uploader', default=None)
    parser.add_argument('--patchset', default=None)

    args = parser.parse_args()

    launchpad = Launchpad.login_with('Gerrit User Sync',
                                     LPNET_SERVICE_ROOT,
                                     GERRIT_CACHE_DIR,
                                     credentials_file=GERRIT_CREDENTIALS,
                                     version='devel')

    conn = MySQLdb.connect(user=DB_USER, passwd=DB_PASS, db=DB_DB)

    find_specs(launchpad, conn, args)
示例#20
0
def main_(options, args):
    logging.basicConfig(level=log_level(options.verbose),
                        format='%(levelname)s:%(message)s')

    if len(args):
        charm_dir = args[0]
    else:
        charm_dir = os.getcwd()

    proof_charm(charm_dir, options.force, options.ignore_warnings)

    logging.debug('login with %s launchpad:', options.lp_instance)
    lp = Launchpad.login_with('promulgate', options.lp_instance)

    if options.unpromulgate:
        logging.info('unpromulgating...')
        charm_branch = None  # makes LP delete the source package.
    else:
        logging.info('promulgating...')
        charm_branch = find_branch_to_promulgate(lp, charm_dir, options.branch)

    if not is_valid_owner(charm_branch, options.promulgate_owner_branch):
        logging.error(" Invalid branch owner: %s", branch_owner(charm_branch))
        logging.error(" Branch push location must be owned by '~charmers'\n"
                      "   use `bzr push --remember lp:~charmers/charms/"
                      "<series>/<charm-name>/trunk`\n   or override this "
                      "behavior using the '--owner-branch'"
                      " option")
        return 1

    update_official_charm_branch(lp, options.series, charm_branch,
                                 charm_name_from_metadata(charm_dir))

    return 0
示例#21
0
def main(args):
    parser = ArgumentParser("Generate red / green chart for release tracking")
    parser.add_argument('series')
    args = parser.parse_args()

    series = args.series

    try:
        lp = Launchpad.login_with("pypypy", "production", version="devel")
    except:
        print "** ERROR: Could not open LP "
        sys.exit(1)

    try:
        project = lp.projects["juju-core"]
    except KeyError:
        print "** ERROR: Project name does not exist: juju-core"
        sys.exit(1)

    # We need to find both the trunk and the specified series
    found = False
    lpSeries = project.series
    for ls in lpSeries:
        if ls.name == "trunk":
            trunk = ls
        if ls.name == series:
            repSeries = ls
            found = True


    if not found:
        print "** ERROR: Unable to find series: %s" % series
        sys.exit(1)

    writeSeriesFile(series, repSeries, trunk)
示例#22
0
def main_(options, args):
    logging.basicConfig(level=log_level(options.verbose),
                        format='%(levelname)s:%(message)s')

    if len(args):
        charm_dir = args[0]
    else:
        charm_dir = os.getcwd()

    proof_charm(charm_dir, options.force, options.ignore_warnings)

    logging.debug('login with %s launchpad:', options.lp_instance)
    lp = Launchpad.login_with('promulgate', options.lp_instance)

    if options.unpromulgate:
        logging.info('unpromulgating...')
        charm_branch = None  # makes LP delete the source package.
    else:
        logging.info('promulgating...')
        charm_branch = find_branch_to_promulgate(lp, charm_dir, options.branch)

    if not is_valid_owner(charm_branch, options.promulgate_owner_branch):
        logging.error(" Invalid branch owner: %s", branch_owner(charm_branch))
        logging.error(" Branch push location must be owned by '~charmers'\n"
                      "   use `bzr push --remember lp:~charmers/charms/"
                      "<series>/<charm-name>/trunk`\n   or override this "
                      "behavior using the '--owner-branch'"
                      " option")
        return 1

    update_official_charm_branch(lp, options.series, charm_branch,
                                 charm_name_from_metadata(charm_dir))

    return 0
示例#23
0
    def get_launchpad_object(self, filename=None, staging=False):
        '''Return a Launchpad object for making API requests.'''
        # XXX: rockstar - 2009 Dec 13 - Ideally, we should be using
        # Launchpad.login_with, but currently, it doesn't support the option of
        # putting the credentials file somewhere other than where the cache
        # goes, and that's kinda nasty (and a security issue according to
        # Kees).
        if not filename:
            filename = self.config.CREDENTIALS

        if staging:
            SERVICE_ROOT = STAGING_SERVICE_ROOT
        else:
            SERVICE_ROOT = LPNET_SERVICE_ROOT

        self.logger.debug(
            "Connecting to the Launchpad API at {0}".format(SERVICE_ROOT))

        self.logger.debug("  Loading credentials from {0}".format(filename))
        if not os.path.exists(filename):
            self.logger.debug("  No existing API credentials were found")
            self.logger.debug("  Fetching new credentials from {0}".format(
                SERVICE_ROOT))

        launchpad = Launchpad.login_with(
            u'Tarmac', service_root=SERVICE_ROOT,
            credentials_file=filename,
            launchpadlib_dir=self.config.CACHE_HOME)

        self.logger.debug("Connected")
        return launchpad
示例#24
0
def main():
    # Argument parsing
    parser = argparse.ArgumentParser(description='Rename Launchpad milestones')
    parser.add_argument('project', help='Project the milestone is defined in')
    parser.add_argument('from_milestone', help='Milestone to rename')
    parser.add_argument('to_milestone', help='New milestone name')
    parser.add_argument("--test", action='store_const', const='staging',
                        default='production', help='Use LP staging server to test')
    args = parser.parse_args()

    # Connect to Launchpad
    print("Connecting to Launchpad...")
    try:
        launchpad = Launchpad.login_with('openstack-releasing', args.test)
    except Exception as error:
        abort(2, 'Could not connect to Launchpad: ' + str(error))

    # Retrieve project
    try:
        project = launchpad.projects[args.project]
    except KeyError:
        abort(2, 'Could not find project: %s' % args.project)

    # Retrieve milestone
    milestone = project.getMilestone(name=args.from_milestone)
    if milestone is None:
        abort(2, 'Could not find milestone %s in project %s' % (
              args.from_milestone, args.project))

    milestone.name = args.to_milestone
    milestone.code_name = ''
    milestone.lp_save()
    print("Renamed")
示例#25
0
    def take_action(self, parsed_args):
        self.log.debug('connecting to Launchpad')
        lp = Launchpad.login_with(
            'lp-report-bot', 'production', version='devel')

        teams_map = {}
        for team_filter in parsed_args.substring:
            for team in lp.people.findTeam(text=team_filter):
                self.log.debug("found team: %s" % team.name)
                teams_map[team.name] = []
        self.log.debug("Getting teams members")
        i = 0
        for t in teams_map:
            i += 1
            self.log.debug("%d/%d %s" % (i, len(teams_map), t))
            for p in lp.people[t].members:
                try:
                    teams_map[t] += [p.name]
                except KeyError:
                    teams_map[t] = [p.name]

        df_teams = pd.DataFrame(columns=teams_map.keys())

        for t in teams_map.keys():
            for p in teams_map[t]:
                try:
                    df_teams.loc[p][t] = t
                except KeyError:
                    df_teams.loc[p] = float('nan')
                    df_teams.loc[p][t] = t

        self.log.debug("Saving data to %s" % parsed_args.outfile)
        df_teams.to_csv(parsed_args.outfile, encoding='utf-8')
示例#26
0
def main():
    parser = argparse.ArgumentParser(
        description="Release Ceilometer bugs for a milestone.")
    parser.add_argument(
        '--milestone', help="The name of the milestone to release for.",
        required=True)
    args = parser.parse_args()

    lp = Launchpad.login_with(
        "ceilometer-bug-release-script", SERVICE_ROOT)
    the_project = lp.projects[PROJECT_NAME]
    milestone = lp.load(
        "%s/+milestone/%s" % (the_project.self_link, args.milestone))
    bugs_for_milestone = the_project.searchTasks(
        status=PRE_RELEASE_STATUS, milestone=milestone)
    bug_count = len(bugs_for_milestone)
    if bug_count == 0:
        print("No bugs to release for milestone %s" % milestone.name)
        sys.exit(0)
    mark_released = raw_input(RELEASE_PROMPT.format(
        bug_count=bug_count,
        pre_release_status=PRE_RELEASE_STATUS,
        milestone_title=milestone.name))
    if mark_released.lower() != "y":
        print("Not releasing bugs.")
        sys.exit(0)
    for bug_task in bugs_for_milestone:
        # We re-load the bugtask to avoid having bug 369293 bite us.
        bug_task = lp.load(bug_task.self_link)
        sys.stdout.write("Updating %s..." % bug_task.bug.id)
        bug_task.status = "Fix Released"
        bug_task.lp_save()
        bug_task.bug.newMessage(
            MESSAGE_TEMPLATE.format(milestone_title=milestone.title))
        sys.stdout.write("DONE\n")
def main():
    args = _parse_args()

    lp = Launchpad.login_with('openstack-releasing', 'production')

    for project in args.projects:
        _cleanup_project(lp, project)
示例#28
0
文件: utils.py 项目: rbrady/filch
def remove_tags_from_launchpad_bug(bug_id, tags):
    launchpad = Launchpad.login_with('Filch', 'production', version='devel')
    bug = launchpad.bugs[bug_id]
    for tag in tags:
        bug.tags.remove(tag)
    bug.tags = bug.tags
    bug.lp_save()
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('hook')
    #common
    parser.add_argument('--change', default=None)
    parser.add_argument('--change-url', default=None)
    parser.add_argument('--project', default=None)
    parser.add_argument('--branch', default=None)
    parser.add_argument('--commit', default=None)
    #change-merged
    parser.add_argument('--submitter', default=None)
    # patchset-created
    parser.add_argument('--uploader', default=None)
    parser.add_argument('--patchset', default=None)

    args = parser.parse_args()

    launchpad = Launchpad.login_with('Gerrit User Sync', LPNET_SERVICE_ROOT,
                                     GERRIT_CACHE_DIR,
                                     credentials_file = GERRIT_CREDENTIALS,
                                     version='devel')

    conn = MySQLdb.connect(user = DB_USER, passwd = DB_PASS, db = DB_DB)

    find_specs(launchpad, conn, args)
示例#30
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('hook')
    #common
    parser.add_argument('--change', default=None)
    parser.add_argument('--change-url', default=None)
    parser.add_argument('--project', default=None)
    parser.add_argument('--branch', default=None)
    parser.add_argument('--commit', default=None)
    #change-merged
    parser.add_argument('--submitter', default=None)
    #patchset-created
    parser.add_argument('--uploader', default=None)
    parser.add_argument('--patchset', default=None)

    args = parser.parse_args()

    # Connect to Launchpad
    launchpad = Launchpad.login_with('Gerrit User Sync', LPNET_SERVICE_ROOT,
                                     GERRIT_CACHE_DIR,
                                     credentials_file=GERRIT_CREDENTIALS,
                                     version='devel')

    # Get git log
    git_log = extract_git_log(args)

    # Process bugtasks found in git log
    for bugtask in find_bugs(launchpad, git_log, args):
        process_bugtask(launchpad, bugtask, git_log, args)
示例#31
0
def main():
    parser = argparse.ArgumentParser(
        description="Release Ceilometer bugs for a milestone.")
    parser.add_argument('--milestone',
                        help="The name of the milestone to release for.",
                        required=True)
    args = parser.parse_args()

    lp = Launchpad.login_with("ceilometer-bug-release-script", SERVICE_ROOT)
    the_project = lp.projects[PROJECT_NAME]
    milestone = lp.load("%s/+milestone/%s" %
                        (the_project.self_link, args.milestone))
    bugs_for_milestone = the_project.searchTasks(status=PRE_RELEASE_STATUS,
                                                 milestone=milestone)
    bug_count = len(bugs_for_milestone)
    if bug_count == 0:
        print("No bugs to release for milestone %s" % milestone.name)
        sys.exit(0)
    mark_released = raw_input(
        RELEASE_PROMPT.format(bug_count=bug_count,
                              pre_release_status=PRE_RELEASE_STATUS,
                              milestone_title=milestone.name))
    if mark_released.lower() != "y":
        print("Not releasing bugs.")
        sys.exit(0)
    for bug_task in bugs_for_milestone:
        # We re-load the bugtask to avoid having bug 369293 bite us.
        bug_task = lp.load(bug_task.self_link)
        sys.stdout.write("Updating %s..." % bug_task.bug.id)
        bug_task.status = "Fix Released"
        bug_task.lp_save()
        bug_task.bug.newMessage(
            MESSAGE_TEMPLATE.format(milestone_title=milestone.title))
        sys.stdout.write("DONE\n")
示例#32
0
def get_bug(number):
    launchpad = Launchpad.login_with(
        'openstack-lp-scripts',
        'production',
        CACHEDIR,
        credentials_file=os.path.expanduser('~/.lp'))
    return launchpad.bugs[number]
示例#33
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('hook')
    #common
    parser.add_argument('--change', default=None)
    parser.add_argument('--change-url', default=None)
    parser.add_argument('--project', default=None)
    parser.add_argument('--branch', default=None)
    parser.add_argument('--commit', default=None)
    #change-merged
    parser.add_argument('--submitter', default=None)
    #patchset-created
    parser.add_argument('--uploader', default=None)
    parser.add_argument('--patchset', default=None)

    args = parser.parse_args()

    # Connect to Launchpad
    launchpad = Launchpad.login_with('Gerrit User Sync',
                                     LPNET_SERVICE_ROOT,
                                     GERRIT_CACHE_DIR,
                                     credentials_file=GERRIT_CREDENTIALS,
                                     version='devel')

    # Get git log
    git_log = extract_git_log(args)

    # Process bugtasks found in git log
    for bugtask in find_bugs(launchpad, git_log, args):
        process_bugtask(launchpad, bugtask, git_log, args)
示例#34
0
def main():
    description = """
    Command line tool to operate with bugs and blueprints
    """
    parser = argparse.ArgumentParser(epilog=description)
    parser.add_argument('project', type=str)
    parser.add_argument('cmd', type=str, choices=['get', 'set'])
    parser.add_argument('item_type', type=str, choices=['bp', 'bug'])
    parser.add_argument('item_id', type=str, nargs='+')
    parser.add_argument('--milestone', type=str)
    parser.add_argument('--series', type=str)
    parser.add_argument('--approve', dest='approved', action='store_true')
    parser.add_argument('--create', action='store_true')
    parser.add_argument('--delete', action='store_true')
    parser.add_argument('--priority', type=str)
    parser.add_argument('--status', type=str)
    params, other_params = parser.parse_known_args()
    global lp
    global prj
    lp = Launchpad.login_with('lp-client', 'production', version='devel')
    prj = lp.projects[params.project]
    if params.cmd == 'set':
        for item_id in params.item_id:
            if params.item_type == 'bp':
                update_bp(item_id, params)
            if params.item_type == 'bug':
                update_bug(item_id, params)
示例#35
0
 def _lp_login(self, access_level=['READ_PRIVATE']):
     """ internal LP login code """
     self._logger.debug("lp_login")
     # use cachedir
     cachedir = SOFTWARE_CENTER_CACHE_DIR
     if not os.path.exists(cachedir):
         os.makedirs(cachedir)
     # login into LP with GUI
     try:
         self._launchpad = Launchpad.login_with(
             'software-center', SERVICE_ROOT, cachedir,
             allow_access_levels=access_level,
             authorizer_class=AuthorizeRequestTokenFromThread)
         self.display_name = self._launchpad.me.display_name
     except Exception as e:
         if type(e) == UserCancelException:
             return
         self._logger.exception("Launchpad.login_with()")
         # remove token on failure, it may be e.g. expired
         # FIXME: store the token in a different place and to avoid
         #        having to use _get_paths()
         (service_root, launchpadlib_dir, cache_path,
          service_root_dir) = Launchpad._get_paths(SERVICE_ROOT, cachedir)
         credentials_path = os.path.join(service_root_dir, 'credentials')
         consumer_credentials_path = os.path.join(credentials_path,
             'software-center')
         # ---
         if os.path.exists(consumer_credentials_path):
             os.remove(consumer_credentials_path)
         self._lp_login(access_level)
         return
     self.login_state = LOGIN_STATE_SUCCESS
     self._logger.debug("/done %s" % self._launchpad)
示例#36
0
 def _login_lp(self, staging=False, saved_credential=False):
     cachedir = os.path.join(os.environ["HOME"], ".launchpadlib/cache")
     if saved_credential and os.path.exists(CONFIG_PATH):
         if staging:
             fatal(_("Cannot use saved credential on staging server."));    
         else:
             staging_level = "production"
             parser = SafeConfigParser()
             parser.read(CONFIG_PATH)
             credentials = Credentials(parser.get('credential', 'consumer'))
             content = ''.join(['oauth_token=', parser.get('credential', 'token'), 
                                '&oauth_token_secret=', parser.get('credential', 'secret'), 
                                '&lp.context=', parser.get('credential', 'context')])
             credentials.access_token = AccessToken.from_string(content)
             lp = Launchpad(credentials, None, None, service_root="production")
     else:
         if staging:
             staging_level = "staging"
         else:
             staging_level = "production"
         lp = Launchpad.login_with(sys.argv[0], staging_level, cachedir , version="devel")
     logging.info("Use {0} server".format(staging_level))
     if not lp:
         fatal(_("failed to connect to launchpad"));
     return lp
示例#37
0
文件: review.py 项目: axw/charm-tools
def main():
    args = parse_options()
    logging.basicConfig(level=log_level(args.verbose),
                        format='%(levelname)s:%(message)s')

    review_message = get_message(args.message)  # before connecting to lp

    logging.debug('login with %s launchpad:', args.lp_instance)
    lp = Launchpad.login_with('charm-pilot', args.lp_instance)

    bug_id = args.bug_id
    logging.debug('find bug %s:', bug_id)
    bug = lp.bugs[bug_id]

    if bug:
        logging.debug('found bug')

        if args.skip_prompt or prompt_to_continue(bug_id):
            logging.debug('adding comment')
            # TODO check return or catch exception
            bug.newMessage(content=review_message)
        else:
            logging.debug('not adding comment')

    else:
        logging.error("no bug: %s", bug_id)
        return 1

    return 0
示例#38
0
def trigger_lp_builders(track):
    """Trigger the LP builder of the track provided. This method will
    login using the cached credentials or prompt you for authorization."""
    if track == "latest":
        snap_name = configbag.snap_name
    else:
        snap_name = "{}-{}".format(configbag.snap_name, track)

    # log in
    launchpad = Launchpad.login_with(
        "Launchpad Snap Build Trigger",
        "production",
        configbag.cachedir,
        credentials_file=configbag.creds,
        version="devel",
    )

    # get launchpad team data and ppa
    snappydev = launchpad.people[configbag.people_name]

    try:
        # get snap
        microk8s = launchpad.snaps.getByName(name=snap_name, owner=snappydev)
    except HTTPError as e:
        click.echo("Cannot trigger build for track {}. ({})".format(track, e.response))
        return None

    # trigger build
    ubuntu = launchpad.distributions["ubuntu"]
    request = microk8s.requestBuilds(archive=ubuntu.main_archive, pocket="Updates")
    return request
示例#39
0
def _get_launchpad_client():
    cred_location = os.path.expanduser('~/.lp_creds')
    credential_store = UnencryptedFileCredentialStore(cred_location)
    return Launchpad.login_with('cpc',
                                'production',
                                version='devel',
                                credential_store=credential_store)
示例#40
0
    def __init__(self, config_filename):
        with open(config_filename, "r") as f:
            self.config = yaml.load(f.read())

        self.teams = self.config['teams']
        self.trunc = self.config['trunc_report']

        cache_dir = self.config['cache_dir']

        if self.config['use_auth']:
            lp = Launchpad.login_with(
                'lp-report-bot', 'production',
                cache_dir, version='devel'
            )
        else:
            lp = Launchpad.login_anonymously(
                'lp-report-bot', 'production', version='devel'
            )
        #import pdb; pdb.set_trace()
        self.projects = [lp.projects[prj] for prj in self.config['project']]

        # for backward compatibility
        #self.project = lp.projects[self.config['project'][0]]

        self.blueprint_series = {}
示例#41
0
def get_lp(script_name, credentials_file=None):
    """Return an LP API client."""
    lp_args = dict(service_root='https://api.launchpad.net', version='devel')
    if credentials_file:
        credentials_file = os.path.expanduser(credentials_file)
        lp_args['credentials_file'] = credentials_file
    lp = Launchpad.login_with(script_name, **lp_args)
    return lp
示例#42
0
def get_lp(login=True):
    if not login:
        return Launchpad.login_anonymously('review-queue', 'production')

    return Launchpad.login_with(
        'review-queue', 'production',
        credentials_file='lp-creds',
        credential_save_failed=lambda: None)
def main():
    args = _parse_args()

    lp = Launchpad.login_with('openstack-releasing', 'production')

    bugs = [line.strip() for line in sys.stdin.readlines()]
    for bug in _filter_bugs(lp, args.project, args.tag, bugs):
        print(bug)
示例#44
0
    def connect(self):
        """Connect"""

        self.logger.info("Connecting to Launchpad")
        self.lp = lp.login_with(
            self.application,
            self.staging,
            self.version)
def main(argv=None):
    args = get_args(argv)
    lp = Launchpad.login_with(
        'lp-copy-packages', service_root='https://api.launchpad.net',
        version='devel', credentials_file=args.credentials)
    ret_code = copy_packages(
        lp, args.version, args.to_archive_name, args.dry_run)
    return ret_code
示例#46
0
def main():
    args = _parse_args()

    lp = Launchpad.login_with('openstack-releasing', 'production')

    bugs = [line.strip() for line in sys.stdin.readlines()]
    for bug in _filter_bugs(lp, args.project, args.importance, bugs):
        print(bug)
示例#47
0
  def __init__(self):
    logger.info('Connecting to Launchpad')
    self.launchpad= Launchpad.login_with('Gerrit User Sync', LPNET_SERVICE_ROOT,
                                 GERRIT_CACHE_DIR,
                                 credentials_file = GERRIT_CREDENTIALS)

    logger.info('Getting Launchpad teams')
    self.lp_teams= self.get_all_sub_teams('openstack', [])
示例#48
0
文件: lprelease.py 项目: mjs/juju
def get_lp(script_name, credentials_file=None):
    """Return an LP API client."""
    lp_args = dict(service_root='https://api.launchpad.net', version='devel')
    if credentials_file:
        credentials_file = os.path.expanduser(credentials_file)
        lp_args['credentials_file'] = credentials_file
    lp = Launchpad.login_with(script_name, **lp_args)
    return lp
def main():
    args = _parse_args()

    lp = Launchpad.login_with('openstack-releasing', 'production')

    for line in sys.stdin.readlines():
        bugnum = line.strip()
        _annotate_bug(lp, args.project, bugnum)
示例#50
0
    def login(self):
        if self._client:
            return self._client

        self._client = Launchpad.login_with(application_name='k8s-jenkaas-bot',
                                            service_root=self.stage,
                                            launchpadlib_dir=self.cache,
                                            version=self.version,
                                            credentials_file=self.creds)
示例#51
0
 def __init__(self, name=""):
     cachedir = os.path.expanduser("~/.launchpadlib/cache/")
     self.launchpad = Launchpad.login_with(
         name,
         'production',
         cachedir,
         credential_save_failed=CredentialsError)
     self.project = self.get_project()
     self.set_state_map()
示例#52
0
def main(argv=None):
    """Upload new source packages to a PPA."""
    args = get_args(argv)
    lp = Launchpad.login_with(
        'upload-packages', service_root='https://api.launchpad.net',
        version='devel', credentials_file=args.credentials)
    upload_packages(
        lp, args.ppa, args.package_dirs, dry_run=args.dry_run)
    return 0
示例#53
0
def main(argv=None):
    """Upload new source packages to a PPA."""
    args = get_args(argv)
    lp = Launchpad.login_with('upload-packages',
                              service_root='https://api.launchpad.net',
                              version='devel',
                              credentials_file=args.credentials)
    upload_packages(lp, args.ppa, args.package_dirs, dry_run=args.dry_run)
    return 0
示例#54
0
 def connect(self):
     assert_main_thread()
     #launchpad = Launchpad.login_anonymously(
     #    'openerp-runbot', 'edge', 'lpcache')
     cachedir = os.path.expanduser("~/.launchpadlib/cache")
     lp_creds = os.path.expanduser("~/.launchpadlib/.lp_creds")
     self.con = Launchpad.login_with('openerp-runbot',
                                     EDGE_SERVICE_ROOT,
                                     cachedir,
                                     credentials_file=lp_creds)
def connect_launchpad():
    """Use the launchpad module connect to launchpad.

    Will connect you to the Launchpad website the first time you run
    this to authorize your system to connect.
    """
    cred_location = os.path.expanduser('~/.lp_creds')
    credential_store = UnencryptedFileCredentialStore(cred_location)
    return Launchpad.login_with('ustriage', 'production', version='devel',
                                credential_store=credential_store)
示例#56
0
def get_lp(script_name, credentials_file=None):
    """Return an LP API client."""
    lp_args = dict()
    if credentials_file:
        lp_args['credentials_file'] = credentials_file
    lp = Launchpad.login_with(script_name,
                              service_root=uris.LPNET_SERVICE_ROOT,
                              version='devel',
                              **lp_args)
    return lp
    def _get_lp(self):
        if not self.lp:
            # log in
            launchpad = Launchpad.login_with('Launchpad Snap Build Trigger',
                                             'production',
                                             configbag.cachedir,
                                             credentials_file=configbag.creds,
                                             version='devel')
            self.lp = launchpad

        return self.lp