14 Replies Latest reply on Mar 13, 2015 4:10 PM by Bill Robinson

    Jython scripts - disconnecting established blcli connection

    Steven Alexson

      I am writing a jython script that makes a blcli connection as RBACAdmin to retrieve a list of roles for a given user. It then presents the script user with the list of roles. Once the user selects a role, the script needs to be able to reconnect to BLCLI as the given user and role. It seems that a jython script cannot establish 2 blcli connections simulateously, nor can it seem to reuse an existing one with new credentials.

       

      I am running this against BSA 8.3 SP3

       

      Initially, my code looked roughly like this:

       

      import bladelogic.cli.CLI as blcli

       

      jli = blcli.CLI()

       

      ...

      (define RBACAdmin authentication information by using jli.setOption...)

       

      jli.connect()

      (Connects successfully as RBACAdmin)

       

      ...

      (define user authentication information by using jli.setOption...)

       

      jli.connect()

      (Fails to connect as user)

       

      It appears that the jli.disconnect() function has been removed, as has the jli.destroy() function.

       

      So I thought I might be able to solve my problem by using different connection names for each connection:

       

      import bladelogic.cli.CLI as blcli

       

      admin_jli = blcli.CLI()

      user_jli = blcli.CLI()

       

      ...

      (define RBACAdmin authentication information by using admin_jli.setOption...)

       

      admin_jli.connect()

      (Connects successfully as RBACAdmin)

       

      ...

      (define user authentication information by using user_jli.setOption...)

       

      user_jli.connect()

      (Fails to connect as user)


      No matter what I do, I cannot get Jython to allow me to establish a second connection. I know each authentication procedure is coded correctly because the RBACAdmin one always works, and the user one works if I do not have the script establish the RBACAdmin connection. The real problem here is that the bladelogic module does not provide a way to disconnect active connections. Why would this have been removed?


      Any thoughts on how to destroy one connect to create another?

        • 2. Re: Jython scripts - disconnecting established blcli connection
          Steven Alexson

          Well, Bill...I knew you would have an answer, but Communities is saying I am not authorized to view the post/document even when I am logged in

          • 3. Re: Jython scripts - disconnecting established blcli connection
            Bill Robinson

            Try it again, it was in an internal community.

            • 4. Re: Re: Jython scripts - disconnecting established blcli connection
              Steven Alexson

              Ok, I can see it now, but I must be doing something wrong....

               

              I add the code to NSH/br/jython/cli/CLI.py (added it beneath the "connect" definition):

               

              def disconnect(self):

                   from com.bladelogic.client import *;

                   i = net.ClientConnectionPool.getInstance();

                   ii = net.ClientConnectionPool.getInstance().closeAllConnections();

                   BRProfile.setSessionCredential(None);

                   return net.ClientConnectionPool.getInstance().getConnectionCount();

               

              and now when I call jli.disconnect(), I get the following error:

               

              Traceback (most recent call last):

                File "./script.jy", line 711, in <module>

                  main()

                File "./script.jy", line 692, in main

                  jli.disconnect()

                File "/tech/bladelogic/NSH/br/jython/bladelogic/cli/CLI.py", line 89, in disconnect

                  i = net.ClientConnectionPool.getInstance();

              NameError: global name 'net' is not defined

               

              What am I missing?

              • 5. Re: Re: Jython scripts - disconnecting established blcli connection
                Bill Robinson

                what's in the script.jy ?  i think net is in the os module so you may have to import that.

                • 6. Re: Jython scripts - disconnecting established blcli connection

                  @Bill Robinson

                  from os import net does not work.Where is that .net name imported from? I would say its from the java libraries but I can't find it. Would you mind please share it?


                  Thanks.

                  • 7. Re: Re: Re: Jython scripts - disconnecting established blcli connection
                    Steven Alexson

                    Bill:

                     

                    I have include a copy of script.jy. It is a very basic script that attempts to connect as an RBACAdmin, then tries to connect as a user. Either connection works when it is the first connection established, and of course the second connection will not connect. This is where the need for jli.disconnect() comes in.

                     

                    I think Jorge is right in his post asking where 'net' is being imported from. I have tried to import it in CLI.py with no luck. I have tried:

                     

                    import net, import java.net as net, and import javax.net as net. All of them result in the same error:

                     

                    Traceback (most recent call last):

                      File "./script.jy", line 140, in <module>

                        main()

                      File "./script.jy", line 134, in main

                        jli.disconnect()

                      File "/usr/nsh/NSH/br/jython/bladelogic/cli/CLI.py", line 90, in disconnect

                        i = net.ClientConnectionPool.getInstance();

                    AttributeError: 'javapackage' object has no attribute 'ClientConnectionPool'

                     

                    In reading that message, the problem seems to be that jython cannot find 'ClientConnectionPool'. I have manually tried to find it in all 3 of the above mentioned 'net' modules using dir(net), and I can't seem to locate it. Where is that function supposed to exist?

                     

                    script.jy

                    #!/bin/env /usr/nsh/NSH/br/bljython
                    #
                    
                    #
                    # IMPORT STATEMENTS
                    #
                    import time
                    import re
                    import grp
                    import types
                    import socket
                    import sys
                    import os
                    import commands
                    import getopt
                    import getpass
                    import java.lang.System as System
                    import bladelogic
                    import bladelogic.cli.CLI as blcli
                    import com.bladelogic.om.infra.cli.CLIMain as bl
                    
                    #
                    # CLASS DEFINITIONS
                    #
                    
                    #
                    # GLOBAL VARIABLES
                    #
                    jli = blcli.CLI()
                    
                    aCredFile = '/home/admin/user_info.dat'
                    
                    username = 'user'
                    password = 'password'
                    userRole = 'myRole'
                    
                    blcred_bin = '/usr/nsh/NSH/br/blcred'
                    nexec_bin = '/usr/nsh/NSH/bin/nexec -n'
                    blquery_bin = '/usr/nsh/NSH/bin/blquery'
                    nsh_bin = '/bin/nsh -c'
                    
                    #
                    # FUNCTION DEFINITIONS/MAIN CODE
                    #
                    def _connect_admin_jli():
                        global jli
                    
                        _printInfo('Authenticating admin...')
                        
                        try:
                            commands.getoutput('%s cred -acquire -profile defaultProfile -i %s' % (blcred_bin, aCredFile))
                        except:
                            _printInfo('ERROR: Failed to authenticate admin...Exiting')
                            sys.exit(1)
                        else:
                            _printInfo(' * Admin authenticated')
                    
                        jli.setRoleName('RBACAdmins')
                        jli.setServiceProfileName('defaultProfile')
                    
                        try:
                            jli.connect()
                        except:
                            _printInfo('ERROR: Failed to connect...Exiting')
                            sys.exit(2)
                        else:
                            _printInfo('Connected')
                    
                        _checkUser()
                        
                    
                    def _connect_user_jli():
                        global jli
                    
                        global authInfo
                    
                        _printInfo("Generating cached credentials...")
                    
                        try:
                            commands.getoutput('%s cred -acquire -profile defaultProfile -username %s -password \'%s\' ' % (blcred_bin, username, password))
                        except:
                            _printInfo('ERROR: Failed to authenticate user "%s"...Exiting' % username)
                            sys.exit(3)
                        else:
                            _printInfo(' * User authenticated')
                    
                        _printInfo('Initializing BLCLI connection. Standby...')
                    
                    
                        jli.setUserName(username)
                        jli.setPassword(password)
                        jli.setRoleName(userRole)
                        jli.setServiceProfileName('defaultProfile')
                    
                        try:
                            jli.connect()
                        except:
                            _printInfo('ERROR: Failed to connect...Exiting')
                            sys.exit(4)
                        else:
                            _printInfo('Connected')
                    
                        checkUser()
                        
                    
                    def _checkUser():
                        cUser = _run_blcli_cmd(jli, 'Utility', 'getCurrentUserName').returnValue
                        
                        print 'Current User = %s' % cUser
                        
                        
                    def _run_blcli_cmd(jli, NameSpace, blcliCmd, *args):
                            cmd = []
                            cmd.append(NameSpace)
                            cmd.append(blcliCmd)
                            for arg in args:
                                    cmd.append(str(arg))
                    
                            try:
                                    blcliResult = jli.run(cmd)
                                    assert blcliResult, 'ERROR: Failed executing ' + blcliCmd
                            except AssertionError, e:
                                    _printInfo(e)
                    
                            if (blcliResult.getError()):
                                    _printInfo(str(blcliResult.error))
                    
                            return blcliResult
                    
                    def _printInfo(msg):
                        print(msg)
                    
                    def main():
                        _connect_admin_jli()
                        jli.disconnect()
                        _connect_user_jli()
                        
                        sys.exit(0)
                    
                    if(__name__ == "__main__"):
                        main()
                    

                     

                    CLI.py

                    import sys
                    import net
                    
                    from com.bladelogic.client import *;
                    from com.bladelogic.om.infra.cli import CLIMain;
                    from com.bladelogic.om.infra.app.option import BlOptionsManager;
                    
                    class CLI:
                        """The main class for accessing BLCLI commands"""
                        def __init__(self):
                            """Set defaults for every detail we need except the app server"""
                            # userfile has a default in the java, so we don't set one here
                            self.params = {
                                "debug" : None,
                                "optionsManager" : BlOptionsManager(),
                            }
                    
                        def __getitem__(self,param):
                            return self.params[param]
                    
                        def __setitem__(self,param,value):
                            self.params[param] = value
                    
                        def debug(self,text):
                            """Basic operational debugging"""
                            if self["debug"]:
                                print text
                    
                        def setAppServerHost(self, host):
                            options = self.params["optionsManager"];
                            options.setOptionValue(BlOptionsManager.APP_SERVER_HOST_OPT, host);
                    
                        def setAppServerPort(self, port):
                            options = self.params["optionsManager"];
                            options.setOptionValue(BlOptionsManager.APP_SERVER_PORT_OPT, port);
                    
                        def setAppServerDirectoryPort(self, port):
                            options = self.params["optionsManager"];
                            options.setOptionValue(BlOptionsManager.APP_SERVER_DIRECTORY_PORT_OPT, port);
                    
                        def setOperatingMode(self, opmode):
                            options = self.params["optionsManager"];
                            options.setOptionValue(BlOptionsManager.OPERATING_MODE_OPT, opmode);
                    
                        def setRoleName(self, role):
                            options = self.params["optionsManager"];
                            options.setOptionValue(BlOptionsManager.ROLE_NAME_OPT, role);
                    
                        def setUserName(self, user):
                            options = self.params["optionsManager"];
                            options.setOptionValue(BlOptionsManager.USER_NAME_OPT, user);
                    
                        def setPassword(self, password):
                            options = self.params["optionsManager"];
                            options.setOptionValue(BlOptionsManager.USER_PASSWORD_OPT, password);
                    
                        def setInteractiveLogin(self, trueFalse):
                            options = self.params["optionsManager"];
                            options.setOptionValue(BlOptionsManager.INTERACTIVE_LOGGIN_OPT, trueFalse);
                    
                        def setLanguage(self, language):
                            options = self.params["optionsManager"];
                            options.setOptionValue(BlOptionsManager.LANGUAGE_OPT, language);
                    
                        def setServiceProfileName(self, name):
                            options = self.params["optionsManager"];
                            options.setOptionValue(BlOptionsManager.SERVICE_PROFILE_NAME_OPT, name);
                    
                        def setServiceProfileFile(self, file):
                            options = self.params["optionsManager"];
                            options.setOptionValue(BlOptionsManager.SERVICE_PROFILES_FILE_OPT, file);
                    
                        def setSsoCredentialCache(self, file):
                            options = self.params["optionsManager"];
                            options.setOptionValue(BlOptionsManager.SSO_CRED_CACHE_OPT, file);
                    
                        def setTrustedCertificateStore(self, file):
                            options = self.params["optionsManager"];
                            options.setOptionValue(BlOptionsManager.SSO_TRUSTED_CERT_KEYSTORE_OPT, file);
                    
                        def connect(self):
                            options = self.params["optionsManager"];
                            CLIMain.initializeBRProfile(options);
                            cli = CLIMain(options);
                            self.params["cli"] = cli
                            cli.loginToAppServer();
                            dir(cli)
                    
                        def disconnect(self):
                            i = net.ClientConnectionPool.getInstance();
                            ii = net.ClientConnectionPool.getInstance().closeAllConnections();
                            BRProfile.setSessionCredential(None);
                            return net.ClientConnectionPool.getInstance().getConnectionCount();
                    
                        def run(self,ary):
                            """Execute a single BLCLI command"""
                            self.debug("> " + " ".join([str(item) for item in ary]))
                    
                            try:
                                nameSpace = ary.pop(0)
                                commandName = ary.pop(0)
                            except TypeError,detail:
                                print "uh, still a problem with types:", detail
                                import sys
                                sys.exit(11)
                    
                            try:
                                result = self.params["cli"].executeCommand(nameSpace, commandName, ary);
                    
                                if result.success():
                                    self.debug("=> " + str(result.returnValue))
                                    return result
                                else:
                                    self.debug(": " + str(result.getError()))
                                    return result
                    
                            except TypeError, detail:
                                print "=> Type error:", detail
                            except com.bladelogic.cli.factory.CommandNotFoundException, detail:
                                print "=> Factory error:", detail
                    
                    • 8. Re: Re: Re: Jython scripts - disconnecting established blcli connection

                      Thanks for sharing your code. I'm more or less at the same point as you (where net name is located?) With that information given, we would probably understand better how the connections are made.

                       

                      As a side note, instead of defining your own print function, I recommend you to make use of the Jython logging module (as far as I can tell, its usage it's exactly the same as in Python)

                      • 9. Re: Re: Re: Jython scripts - disconnecting established blcli connection
                        Bill Robinson

                        ok, try this:

                         

                        at the top of the CLI.py add:

                        from com.bladelogic.om.infra.client.ui.net import ClientConnectionPool;

                        from com.bladelogic.om.infra.client.ui import BRProfile;

                         

                        disconnect should look like this:

                            def disconnect(self): 
                                    i = ClientConnectionPool.getInstance();
                                    ii = ClientConnectionPool.getInstance().closeAllConnections();
                                    BRProfile.setSessionCredential(None); 
                                    BRProfile.setDefaultRoleName(None);
                                    return ClientConnectionPool.getInstance().getConnectionCount();

                         

                         

                        then try your original script you posted.

                        • 10. Re: Re: Re: Jython scripts - disconnecting established blcli connection
                          Steven Alexson

                          Well, that did the trick! I now have a working disconnect function.

                           

                          Thanks Bill!

                          • 11. Re: Jython scripts - disconnecting established blcli connection

                            do you mind sharing your final script? im still having issues

                            • 12. Re: Jython scripts - disconnecting established blcli connection
                              Bill Robinson

                              what issues are you having ?  what have you done so far ?

                              • 13. Re: Jython scripts - disconnecting established blcli connection

                                Hi Bill Robinson

                                 

                                i am still fairly new to this but I have inherited this script which creates/executes our blade logic package, which works fine for those activities

                                 

                                what i am trying to improve upon is the promotion part which uses aclTemplates

                                 

                                currently we need to do the following:

                                 

                                what i want is the user to log in as

                                 

                                1. log in as "teampay_dev_deploy" -role

                                2. Promote the bl package using the ACL Template(TeamPay_Transfer_to_TEST)

                                3. switch role : as "teampay_test_manager" -role

                                4. cPromote the bl package using the ACL Template(TeamPay_Transfer_to_HOST)

                                 

                                what happens is i get the following error:-- ERROR: com.bladelogic.om.infra.mfw.util.AccessDeniedException: Access Denied DepotFolder.Read on Depot

                                 

                                my apologies if i have missed something here

                                 

                                My script ( the method i have added is called promote and I am looking at "DIT3")

                                 

                                if special_action == "promote":
                                   print "---------------------------------------------------"
                                   print "Promoting job : " + PACKAGE_NAME

                                   print "---------------------------------------------------"
                                   connect_jli('TeamPay_DEV_Deployment')

                                   print "---------------------------------------------------"
                                   print "Promote package"
                                   promote_package()

                                def promote_package():
                                   BLPackageKey=run_blcli_cmd(True,'BlPackage','getDBKeyByGroupAndName',DEPOT_GROUP_PATH,PACKAGE_NAME)

                                   if ENV_TYPE == "FIT":
                                   run_blcli_cmd(True, 'DepotObject', 'applyAclTemplate', BLPackageKey.returnValue,'WFN_Transfer_to_TEST','false')

                                # run_blcli_cmd(True, 'DepotObject', 'applyAclTemplate', BLPackageKey.returnValue,'WFN_Transfer_to_HOST','false')
                                   if ENV_TYPE == "IPE":
                                   run_blcli_cmd(True, 'DepotObject', 'applyAclTemplate', BLPackageKey.returnValue,'USS_Transfer_to_E2E','false')

                                   if ENV_TYPE == "DIT3":
                                   connect_jli('TeamPay_DEV_Deployment')

                                   print "Connecting as TeamPay_DEV_Deployment"
                                   run_blcli_cmd(True, 'DepotObject', 'applyAclTemplate', BLPackageKey.returnValue,'TeamPay_Transfer_to_TEST','false')

                                  disconnect(jli)

                                   print "Connecting as TEST_Manager"
                                   connect_jli('TeamPay_TEST_Manager')

                                  run_blcli_cmd(True, 'DepotObject', 'applyAclTemplate', BLPackageKey.returnValue,'TeamPay_Transfer_to_HOST','false')

                                  disconnect(jli)

                                 

                                  run_blcli_cmd(True, 'DepotObject', 'applyAclTemplate', BLPackageKey.returnValue,'TeamPay_Transfer_to_HOST','false')

                                  disconnect(jli)

                                 

                                def disconnect(self):
                                   i = ClientConnectionPool.getInstance()

                                   ii = ClientConnectionPool.getInstance().closeAllConnections()

                                  BRProfile.setSessionCredential(None)

                                  BRProfile.setDefaultRoleName(None)

                                   return ClientConnectionPool.getInstance().getConnectionCount()

                                • 14. Re: Jython scripts - disconnecting established blcli connection
                                  Bill Robinson

                                  you don't need to disconnect from jython to switch roles.  steve needed to connect to one bsa env and then connect to another.  there's a 'Utility.assumeRole' command that will let you switch roles.  you should try that instead.