common-smartgears-utils/src/main/java/org/gcube/smartgears/utils/sweeper/Sweeper.java

89 lines
2.6 KiB
Java

package org.gcube.smartgears.utils.sweeper;
import static org.gcube.common.authorization.client.Constants.authorizationService;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.List;
import org.gcube.common.authorization.library.AuthorizationEntry;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.resources.gcore.HostingNode;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.informationsystem.publisher.RegistryPublisher;
import org.gcube.informationsystem.publisher.RegistryPublisherFactory;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.gcube.resources.discovery.icclient.ICFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Andrea Manzi(CERN)
*
* Implements the sweeping on the IS in case a container state is cleaned
*
*/
public class Sweeper {
String ghn_state_path = "";
Logger logger;
public Sweeper () throws Exception {
logger = LoggerFactory.getLogger(Sweeper.class);
String ghn_path = System.getenv("GHN_HOME");
if (ghn_path == null ) {
logger.error("GHN_HOME not defined");
throw new Exception ("GHN_HOME not defined");
}
ghn_state_path=ghn_path+File.separator+"state";
}
@SuppressWarnings("unchecked")
public void forceDeleteHostingNode(){
String id ;
List<String> tokens ;
try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(ghn_state_path+File.separator+"ghn.xml"))){
id = (String)ois.readObject();
tokens = (List<String>) ois.readObject();
}catch(Exception e){
throw new RuntimeException("error loading persisted state");
}
RegistryPublisher rp=RegistryPublisherFactory.create();
System.out.println(" id to remove is "+id);
try{
DiscoveryClient<HostingNode> client = ICFactory.clientFor(HostingNode.class);
SimpleQuery query = ICFactory.queryFor(HostingNode.class);
query.addCondition("$resource/ID/text() = '"+id+"'");
for (String token : tokens){
AuthorizationEntry entry = authorizationService().get(token);
SecurityTokenProvider.instance.set(token);
ScopeProvider.instance.set(entry.getContext());
System.out.println("trying to remove resource in scope "+entry.getContext());
List<HostingNode> nodes = client.submit(query);
System.out.println(" node is empty? "+nodes.isEmpty());
if (nodes.isEmpty()) continue;
rp.remove(nodes.get(0));
}
}catch(Exception e){
throw new RuntimeException("error removing hosting node resource",e);
}
}
}