Пример #1
0
 def createPermissions(self, permissionsDict):
     permissionsDotJsonWritePath = os.path.join(self.getPermissionsDir(),
                                                "permissions.json")
     self.__permissions = Permissions(self.getUser(),
                                      initialPermissions=permissionsDict,
                                      writePath=permissionsDotJsonWritePath)
     return self.__permissions
Пример #2
0
    def getPermissions(self):
        if self.__permissions is None:
            permissionsDotJsonWritePath = os.path.join(
                self.getPermissionsDir(), "permissions.json")
            registryRepo = self.getUser().getRegistry().getGitRepository()
            if os.path.join(self.getRelativePermissionsDir(),
                            "permissions.json") in registryRepo.lsFiles(
                                self.getUser().getRegistry().getGitReadHash(),
                                self.getRelativePermissionsDir()):
                initialPermissions = subuserlib.permissions.getPermissions(
                    permissionsString=registryRepo.show(
                        self.getUser().getRegistry().getGitReadHash(),
                        os.path.join(self.getRelativePermissionsDir(),
                                     "permissions.json")))
            else:
                raise SubuserHasNoPermissionsException("The subuser <" +
                                                       self.getName() +
                                                       """> has no permissions.

If you are updating sometime around August 2014, you should move ~/.subuser/permissions to ~/.subuser/registry/permissions and run:

$ git add .
$ git commit

Otherwise, please run:

$ subuser repair

To repair your subuser installation.\n""")
            self.__permissions = Permissions(
                self.getUser(),
                initialPermissions,
                writePath=permissionsDotJsonWritePath)
        return self.__permissions
Пример #3
0
    def loadPermissions(self):
        registryFileStructure = self.getUser().getRegistry().getGitRepository(
        ).getFileStructureAtCommit(
            self.getUser().getRegistry().getGitReadHash())
        try:
            initialPermissions = subuserlib.permissions.load(
                permissionsString=registryFileStructure.read(
                    os.path.join(self.getRelativePermissionsDir(),
                                 "permissions.json")))
        except OSError:
            raise SubuserHasNoPermissionsException("The subuser <" +
                                                   self.getName() +
                                                   """> has no permissions.

Please run:

$ subuser repair

To repair your subuser installation.\n""")
        except SyntaxError as e:
            sys.exit("The subuser <" + self.getName() +
                     """>'s permissions appears to be corrupt.

Please file a bug report explaining how you got here.\n""" + str(e))
        self.__permissions = Permissions(
            self.getUser(),
            initialPermissions,
            writePath=self.getPermissionsDotJsonWritePath())
Пример #4
0
 def getPermissionsTemplate(self):
     if self.__permissionsTemplate is None:
         permissionsDotJsonWritePath = os.path.join(
             self.getPermissionsDir(), "permissions-template.json")
         registryRepo = self.getUser().getRegistry().getGitRepository()
         if os.path.join(
                 self.getRelativePermissionsDir(),
                 "permissions-template.json") in registryRepo.lsFiles(
                     self.getUser().getRegistry().getGitReadHash(),
                     self.getRelativePermissionsDir()):
             initialPermissions = subuserlib.permissions.getPermissions(
                 permissionsString=registryRepo.show(
                     self.getUser().getRegistry().getGitReadHash(),
                     os.path.join(self.getRelativePermissionsDir(),
                                  "permissions-template.json")))
             save = False
         else:
             initialPermissions = self.getImageSource().getPermissions()
             save = True
         self.__permissionsTemplate = Permissions(
             self.getUser(),
             initialPermissions,
             writePath=permissionsDotJsonWritePath)
         if save:
             self.__permissionsTemplate.save()
     return self.__permissionsTemplate
Пример #5
0
    def loadPermissions(self):
        registryFileStructure = self.getUser().getRegistry().getGitRepository(
        ).getFileStructureAtCommit(
            self.getUser().getRegistry().getGitReadHash())
        if registryFileStructure.exists(
                os.path.join(self.getRelativePermissionsDir(),
                             "permissions.json")):
            initialPermissions = subuserlib.permissions.getPermissions(
                permissionsString=registryFileStructure.read(
                    os.path.join(self.getRelativePermissionsDir(),
                                 "permissions.json")))
        else:
            raise SubuserHasNoPermissionsException("The subuser <" +
                                                   self.getName() +
                                                   """> has no permissions.

If you are updating sometime around August 2015, you should move ~/.subuser/permissions to ~/.subuser/registry/permissions and run:

$ git add .
$ git commit

Otherwise, please run:

$ subuser repair

To repair your subuser installation.\n""")
        self.__permissions = Permissions(
            self.getUser(),
            initialPermissions,
            writePath=self.getPermissionsDotJsonWritePath())
Пример #6
0
 def editPermissionsCLI(self):
   while True:
     self.user.endUser.runEditor(self.permissions.writePath)
     try:
       initialPermissions = subuserlib.permissions.load(permissionsFilePath=self.permissionsDotJsonWritePath)
       break
     except SyntaxError as e:
       print(e)
       input("Press ENTER to edit the permission file again.")
   self.__permissions = Permissions(self.user,initialPermissions,writePath=self.permissionsDotJsonWritePath)
   self.permissions.save()
Пример #7
0
 def editPermissionsCLI(self):
   while True:
     subuserlib.subprocessExtras.runEditor(self.getPermissions().getWritePath())
     try:
       initialPermissions = subuserlib.permissions.load(permissionsFilePath=self.getPermissionsDotJsonWritePath())
       break
     except SyntaxError as e:
       print(e)
       input("Press ENTER to edit the permission file again.")
   self.__permissions = Permissions(self.getUser(),initialPermissions,writePath=self.getPermissionsDotJsonWritePath())
   self.getPermissions().save()
Пример #8
0
  def loadPermissions(self):
    registryFileStructure = self.getUser().getRegistry().getGitRepository().getFileStructureAtCommit(self.getUser().getRegistry().getGitReadHash())
    if registryFileStructure.exists(os.path.join(self.getRelativePermissionsDir(),"permissions.json")):
      initialPermissions = subuserlib.permissions.load(permissionsString=registryFileStructure.read(os.path.join(self.getRelativePermissionsDir(),"permissions.json")))
    else:
      raise SubuserHasNoPermissionsException("The subuser <"+self.getName()+"""> has no permissions.

Please run:

$ subuser repair

To repair your subuser installation.\n""")
    self.__permissions = Permissions(self.getUser(),initialPermissions,writePath=self.getPermissionsDotJsonWritePath())
Пример #9
0
 def getPermissionsTemplate(self):
   if self.__permissionsTemplate is None:
     permissionsDotJsonWritePath = os.path.join(self.permissionsDir,"permissions-template.json")
     registryFileStructure = self.user.registry.gitRepository.getFileStructureAtCommit(self.user.registry.gitReadHash)
     if "permissions-template.json" in registryFileStructure.lsFiles(self.relativePermissionsDir):
       initialPermissions = subuserlib.permissions.load(permissionsString=registryFileStructure.read(os.path.join(self.relativePermissionsDir,"permissions-template.json")),logger=self.user.registry)
       save = False
     else:
       initialPermissions = self.imageSource.permissions
       save = True
     self.__permissionsTemplate = Permissions(self.user,initialPermissions,writePath=permissionsDotJsonWritePath)
     if save:
       self.__permissionsTemplate.save()
   return self.__permissionsTemplate
Пример #10
0
 def editPermissionsCLI(self):
     try:
         editor = os.environ["EDITOR"]
     except KeyError:
         editor = "/usr/bin/nano"
     subuserlib.subprocessExtras.call(
         [editor, self.getPermissions().getWritePath()])
     initialPermissions = subuserlib.permissions.getPermissions(
         permissionsFilePath=self.getPermissionsDotJsonWritePath())
     self.__permissions = Permissions(
         self.getUser(),
         initialPermissions,
         writePath=self.getPermissionsDotJsonWritePath())
     self.getPermissions().save()
Пример #11
0
def runCommand(realArgs):
    """
  Run packaging subcommands.
  """
    options, args = parseCliArgs(realArgs)
    try:
        subcommand = args[0]
        subcommands = ["init", "add", "test"]
        if not subcommand in subcommands:
            sys.exit(
                subcommand +
                " not a recognized subcommand of pkg. Use --help for help.")
    except IndexError:
        sys.exit("No command given, use -h for help.")
    user = User()
    if subcommand == "init":
        if not os.path.exists("./.subuser.json"):
            repoConfig = {}
            if options.imageSourcesDir:
                repoConfig["image-sources-dir"] = options.imageSourcesDir
            with user.getEndUser().get_file("./.subuser.json",
                                            "w") as subuserDotJson:
                json.dump(repoConfig, subuserDotJson)
                if options.imageSourcesDir:
                    user.getEndUser().makedirs(options.imageSourcesDir)
            subuserlib.print.printWithoutCrashing(
                "Subuser repository initialized successfully!")
            subuserlib.print.printWithoutCrashing(
                "You can add new image sources with:")
            subuserlib.print.printWithoutCrashing(
                "$ subuser pkg add image-source-name")
        else:
            sys.exit("Subuser repository already initialized. Exiting.")
    if subcommand == "add":
        repo = subuserlib.resolve.getRepositoryFromPath(
            user, os.environ["PWD"])
        imageSourceToAdd = args[1]
        if imageSourceToAdd in repo:
            sys.exit(
                "An image source named " + imageSourceToAdd +
                " is already present in the repository. Cannot add. Exiting.")
        subuserlib.print.printWithoutCrashing("Adding new image source " +
                                              imageSourceToAdd)
        useDefaultLocations = options.imageFile is None and options.permissionsFile is None and options.buildContext is None
        if useDefaultLocations:
            imageSourceDir = os.path.join(repo.getImageSourcesDir(),
                                          imageSourceToAdd)
            buildContext = os.path.join(imageSourceDir, "image")
            imageFile = os.path.join(buildContext, "SubuserImagefile")
            permissionsFile = os.path.join(imageSourceDir, "permissions.json")
            try:
                user.getEndUser().makedirs(buildContext)
            except OSError:
                pass
        else:
            if repo.getRepoConfig() is None:
                sys.exit(
                    "You must initialize your repository with 'pkg init' before adding image sources to it."
                )
            if options.buildContext is None or options.imageFile is None or options.permissionsFile is None:
                sys.exit(
                    "If you specify non-default paths you must specify all of them. That is --image-file, --build-context AND --permissions-file. Cannot add image. Exiting..."
                )
            imageFile = options.imageFile
            try:
                user.getEndUser().makedirs(os.path.dirname(imageFile))
            except OSError:
                pass
            buildContext = options.buildContext
            try:
                user.getEndUser().makedirs(buildContext)
            except OSError:
                pass
            permissionsFile = options.permissionsFile
            try:
                user.getEndUser().makedirs(os.path.dirname(permissionsFile))
            except OSError:
                pass
            repoConfig = repo.getRepoConfig()
            if not "explicit-image-sources" in repoConfig:
                repoConfig["explicit-image-sources"] = {}
            repoConfig["explicit-image-sources"][imageSourceToAdd] = {
                "image-file": imageFile,
                "build-context": buildContext,
                "permissions-file": permissionsFile
            }
            with user.getEndUser().get_file("./.subuser.json",
                                            "w") as subuserDotJson:
                json.dump(repoConfig,
                          subuserDotJson,
                          indent=1,
                          separators=(",", ": "))
        permissions = defaultPermissions
        (returncode, maintainerName,
         stderr) = user.getEndUser().callCollectOutput(
             ["git", "config", "user.name"])
        subuserlib.print.printWithoutCrashing(stderr)
        (returncode, maintainerEmail,
         stderr) = user.getEndUser().callCollectOutput(
             ["git", "config", "user.email"])
        subuserlib.print.printWithoutCrashing(stderr)
        permissions["maintainer"] = maintainerName.rstrip(
            "\n") + " <" + maintainerEmail.rstrip("\n") + ">"
        if not os.path.exists(permissionsFile):
            with user.getEndUser().get_file(permissionsFile, "w") as pf:
                json.dump(permissions, pf, indent=1, separators=(",", ": "))
        while True:
            user.getEndUser().runEditor(permissionsFile)
            try:
                Permissions(user,
                            initialPermissions=subuserlib.permissions.load(
                                permissionsFilePath=permissionsFile),
                            writePath=permissionsFile).save()
                break
            except SyntaxError as e:
                input(str(e) + "\nPress ENTER to edit the file again.")
        if not os.path.exists(imageFile):
            with user.getEndUser().get_file(imageFile, "w") as imgf:
                imgf.write(defaultImageFileTemplate)
        user.getEndUser().runEditor(imageFile)
        try:
            if input("Would you like to test your new image? [Y/n]") == "n":
                sys.exit(0)
        except EOFError:
            subuserlib.print.printWithoutCrashing("")
            if not subuserlib.test.testing:
                sys.exit(0)
    if subcommand == "test" or subcommand == "add":
        user = User()
        repo = subuserlib.resolve.getRepositoryFromPath(
            user, os.environ["PWD"])
        permissionsAccepter = AcceptPermissionsAtCLI(
            user, alwaysAccept=options.accept)
        imageSourceNames = args[1:]
        with user.getRegistry().getLock() as lockFileHandler:
            subusers = []
            subuserNamePrefix = "!test-image-subuser-"
            # Build the images
            for imageSourceName in imageSourceNames:
                subuserName = subuserNamePrefix + imageSourceName
                subuserlib.subuser.addFromImageSourceNoVerify(
                    user, subuserName, repo[imageSourceName])
                subusers.append(user.getRegistry().getSubusers()[subuserName])
            subuserlib.verify.verify(user,
                                     subusers=subusers,
                                     permissionsAccepter=permissionsAccepter,
                                     prompt=options.prompt,
                                     useCache=True)
            subusersToTryBuildingAgain = None
            while not subusersToTryBuildingAgain == []:
                subusersToTryBuildingAgain = []
                for subuser in subusers:
                    if subuser.getImageId() is None:
                        try:
                            if not input(subuser.getName(
                            ) + " failed to build. Edit its image file and try again? [Y/n]"
                                         ) == "n":
                                subusersToTryBuildingAgain.append(subuser)
                                user.getEndUser().runEditor(
                                    subuser.getImageSource().getImageFile())
                        except EOFError:
                            subuserlib.print.printWithoutCrashing("")
                            subuserlib.print.printWithoutCrashing(
                                "Not editing and not trying again due to lack of terminal."
                            )
                if subusersToTryBuildingAgain:
                    subuserlib.verify.verify(
                        user,
                        subusers=subusersToTryBuildingAgain,
                        permissionsAccepter=permissionsAccepter,
                        prompt=options.prompt,
                        useCache=True)
            user.getRegistry().commit(
                "subuser pkg %s\n%s" %
                (subcommand, "\n".join(imageSourceNames)))
        # Run the images
        for subuser in subusers:
            if subuser.getPermissions()["executable"] and subuser.getImageId():
                try:
                    arguments = input(
                        "Running " + subuser.getName() +
                        " enter arguments and press enter to continue:")
                except EOFError:
                    subuserlib.print.printWithoutCrashing("")
                    arguments = ""
                arguments = arguments.split(" ")
                if arguments == [""]:
                    arguments = []
                runtime = subuser.getRuntime(os.environ)
                if runtime:
                    runtime.run(arguments)
        with user.getRegistry().getLock() as lockFileHandler:
            # Remove the subusers
            user = User()
            subuserlib.subuser.remove(user, subusers)
            user.getRegistry().commit(
                "subuser pkg: Remove temp subusers after test.")
Пример #12
0
def pkg(realArgs):
    """
  Run packaging subcommands.
  """
    options, args = parseCliArgs(realArgs)
    user = User()
    subcommand = args[0]
    if subcommand == "init":
        if not os.path.exists("./.subuser.json"):
            repoConfig = {}
            if options.imageSourcesDir:
                repoConfig["image-sources-dir"] = options.imageSourcesDir
            with open("./.subuser.json", "w") as subuserDotJson:
                json.dump(repoConfig, subuserDotJson)
                if options.imageSourcesDir:
                    user.getEndUser().makedirs(options.imageSourcesDir)
            user.getEndUser().chown("./.subuser.json")
            print("Subuser repository initialized successfully!")
            print("You can add new image sources with:")
            print("$ subuser pkg add image-source-name")
        else:
            sys.exit("Subuser repository already initialized. Exiting.")
    if subcommand == "add":
        repo = subuserlib.resolve.getRepositoryFromPath(
            user, os.environ["PWD"])
        imageSourceToAdd = args[1]
        if imageSourceToAdd in repo:
            sys.exit(
                "An image source named " + imageSourceToAdd +
                " is already present in the repository. Cannot add. Exiting.")
        useDefaultLocations = options.imageFile is None and options.permissionsFile is None and options.buildContext is None
        if useDefaultLocations:
            imageSourceDir = os.path.join(repo.getImageSourcesDir(),
                                          imageSourceToAdd)
            buildContext = os.path.join(imageSourceDir, "image")
            imageFile = os.path.join(buildContext, "SubuserImagefile")
            permissionsFile = os.path.join(imageSourceDir, "permissions.json")
            try:
                user.getEndUser().makedirs(buildContext)
            except OSError:
                pass
        else:
            if options.buildContext is None or options.imageFile is None or options.permissionsFile is None:
                sys.exit(
                    "If you specify non-default paths you must specify all of them. That is --image-file, --build-context AND --permissions-file. Cannot add image. Exiting..."
                )
            imageFile = options.imageFile
            try:
                user.getEndUser().makedirs(os.path.dirname(imageFile))
            except OSError:
                pass
            buildContext = options.buildContext
            try:
                user.getEndUser().makedirs(os.path.dirname(buildContext))
            except OSError:
                pass
            permissionsFile = options.permissionsFile
            try:
                user.getEndUser().makedirs(os.path.dirname(permissionsFile))
            except OSError:
                pass
            repoConfig = repo.getRepoConfig()
            if not "explicit-image-sources" in repoConfig:
                repoConfig["explicit-image-sources"] = {}
            repoConfig["explicit-image-sources"][imageSourceToAdd] = {
                "image-file": imageFile,
                "build-context": buildContext,
                "permissions-file": permissionsFile
            }
            with open("./.subuser.json", "w") as subuserDotJson:
                json.dump(repoConfig,
                          subuserDotJson,
                          indent=1,
                          separators=(",", ": "))
        permissions = copy.deepcopy(subuserlib.permissions.defaults)
        (returncode,
         maintainerName) = subuserlib.subprocessExtras.callCollectOutput(
             ["git", "config", "user.name"])
        (returncode,
         maintainerEmail) = subuserlib.subprocessExtras.callCollectOutput(
             ["git", "config", "user.email"])
        permissions["maintainer"] = maintainerName.rstrip(
            "\n") + " <" + maintainerEmail.rstrip("\n") + ">"
        if not os.path.exists(permissionsFile):
            with open(permissionsFile, "w") as pf:
                json.dump(permissions, pf, indent=1, separators=(",", ": "))
        subuserlib.subprocessExtras.runEditor(permissionsFile)
        Permissions(user,
                    initialPermissions=subuserlib.permissions.load(
                        permissionsFilePath=permissionsFile),
                    writePath=permissionsFile).save()
        user.getEndUser().chown(permissionsFile)
        if not os.path.exists(imageFile):
            with open(imageFile, "w") as imgf:
                imgf.write("""FROM-SUBUSER-IMAGE libx11@default
RUN apt-get update && apt-get upgrade -y && apt-get install -y PKG""")
            user.getEndUser().chown(imageFile)
        subuserlib.subprocessExtras.runEditor(imageFile)
        if raw_input("Would you like to test your new image? [Y/n]") == "n":
            sys.exit(0)
    if subcommand == "test" or subcommand == "add":
        user = User()
        repo = subuserlib.resolve.getRepositoryFromPath(
            user, os.environ["PWD"])
        permissionsAccepter = AcceptPermissionsAtCLI(
            user, alwaysAccept=options.accept)
        imageSourceNames = args[1:]
        with user.getRegistry().getLock() as lockFileHandler:
            subuserNames = []
            subuserNamePrefix = "!test-image-subuser-"
            # Build the images
            for imageSourceName in imageSourceNames:
                subuserName = subuserNamePrefix + imageSourceName
                subuserNames.append(subuserName)
                subuserlib.subuser.addFromImageSourceNoVerify(
                    user, subuserName, repo[imageSourceName])
            subuserlib.verify.verify(user,
                                     subuserNames=subuserNames,
                                     permissionsAccepter=permissionsAccepter,
                                     prompt=options.prompt)
            for subuserName in subuserNames:
                if user.getRegistry().getSubusers()[subuserName].getImageId(
                ) is None and not raw_input(
                        subuserName +
                        " failed to build. Edit its image file and try again? [Y/n]"
                ) == "n":
                    subuserlib.subprocessExtras.runEditor(
                        user.getRegistry().getSubusers()
                        [subuserName].getImageSource().getImageFile())
                    subuserlib.verify.verify(
                        user,
                        subuserNames=[subuserName],
                        permissionsAccepter=permissionsAccepter,
                        prompt=options.prompt)
            user.getRegistry().commit()
        # Create a list of the names of the new subusers
        subuserNames = []
        for imageSourceName in imageSourceNames:
            subuserNames.append(subuserNamePrefix + imageSourceName)
        # Run the images
        for subuserName in subuserNames:
            arguments = raw_input(
                "Running " + subuserName +
                " enter arguments and press enter to continue:")
            arguments = arguments.split(" ")
            if arguments == [""]:
                arguments = []
            subuser = user.getRegistry().getSubusers()[subuserName]
            if subuser.getPermissions()["executable"]:
                runtime = subuser.getRuntime(os.environ)
                if runtime:
                    runtime.run(arguments)
        with user.getRegistry().getLock() as lockFileHandler:
            # Remove the subusers
            user = User()
            subuserlib.subuser.remove(user, subuserNames)
            user.getRegistry().commit()
Пример #13
0
 def editPermissionsCLI(self):
   subuserlib.subprocessExtras.runEditor(self.getPermissions().getWritePath())
   initialPermissions = subuserlib.permissions.load(permissionsFilePath=self.getPermissionsDotJsonWritePath())
   self.__permissions = Permissions(self.getUser(),initialPermissions,writePath=self.getPermissionsDotJsonWritePath())
   self.getPermissions().save()